5be295d72301b7f54b2e74712c700b3f9bf5a4b8
[org-mode.git] / lisp / org.el
blob5be295d72301b7f54b2e74712c700b3f9bf5a4b8
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-table-calc-current-TBLFM "org-table" (&optional arg))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-agenda-redo "org-agenda" (&optional all))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-restriction "org-element" (element))
161 (declare-function org-element-type "org-element" (element))
163 ;; load languages based on value of `org-babel-load-languages'
164 (defvar org-babel-load-languages)
166 ;;;###autoload
167 (defun org-babel-do-load-languages (sym value)
168 "Load the languages defined in `org-babel-load-languages'."
169 (set-default sym value)
170 (mapc (lambda (pair)
171 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
172 (if active
173 (progn
174 (require (intern (concat "ob-" lang))))
175 (progn
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-execute:" lang)))
178 (funcall 'fmakunbound
179 (intern (concat "org-babel-expand-body:" lang)))))))
180 org-babel-load-languages))
182 ;;;###autoload
183 (defun org-babel-load-file (file &optional compile)
184 "Load Emacs Lisp source code blocks in the Org-mode FILE.
185 This function exports the source code using `org-babel-tangle'
186 and then loads the resulting file using `load-file'. With prefix
187 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
188 file to byte-code before it is loaded."
189 (interactive "fFile to load: \nP")
190 (require 'ob-core)
191 (let* ((age (lambda (file)
192 (float-time
193 (time-subtract (current-time)
194 (nth 5 (or (file-attributes (file-truename file))
195 (file-attributes file)))))))
196 (base-name (file-name-sans-extension file))
197 (exported-file (concat base-name ".el")))
198 ;; tangle if the org-mode file is newer than the elisp file
199 (unless (and (file-exists-p exported-file)
200 (> (funcall age file) (funcall age exported-file)))
201 (org-babel-tangle-file file exported-file "emacs-lisp"))
202 (message "%s %s"
203 (if compile
204 (progn (byte-compile-file exported-file 'load)
205 "Compiled and loaded")
206 (progn (load-file exported-file) "Loaded"))
207 exported-file)))
209 (defcustom org-babel-load-languages '((emacs-lisp . t))
210 "Languages which can be evaluated in Org-mode buffers.
211 This list can be used to load support for any of the languages
212 below, note that each language will depend on a different set of
213 system executables and/or Emacs modes. When a language is
214 \"loaded\", then code blocks in that language can be evaluated
215 with `org-babel-execute-src-block' bound by default to C-c
216 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
217 be set to remove code block evaluation from the C-c C-c
218 keybinding. By default only Emacs Lisp (which has no
219 requirements) is loaded."
220 :group 'org-babel
221 :set 'org-babel-do-load-languages
222 :version "24.1"
223 :type '(alist :tag "Babel Languages"
224 :key-type
225 (choice
226 (const :tag "Awk" awk)
227 (const :tag "C" C)
228 (const :tag "R" R)
229 (const :tag "Asymptote" asymptote)
230 (const :tag "Calc" calc)
231 (const :tag "Clojure" clojure)
232 (const :tag "CSS" css)
233 (const :tag "Ditaa" ditaa)
234 (const :tag "Dot" dot)
235 (const :tag "Emacs Lisp" emacs-lisp)
236 (const :tag "Fortran" fortran)
237 (const :tag "Gnuplot" gnuplot)
238 (const :tag "Haskell" haskell)
239 (const :tag "IO" io)
240 (const :tag "Java" java)
241 (const :tag "Javascript" js)
242 (const :tag "LaTeX" latex)
243 (const :tag "Ledger" ledger)
244 (const :tag "Lilypond" lilypond)
245 (const :tag "Lisp" lisp)
246 (const :tag "Makefile" makefile)
247 (const :tag "Maxima" maxima)
248 (const :tag "Matlab" matlab)
249 (const :tag "Mscgen" mscgen)
250 (const :tag "Ocaml" ocaml)
251 (const :tag "Octave" octave)
252 (const :tag "Org" org)
253 (const :tag "Perl" perl)
254 (const :tag "Pico Lisp" picolisp)
255 (const :tag "PlantUML" plantuml)
256 (const :tag "Python" python)
257 (const :tag "Ruby" ruby)
258 (const :tag "Sass" sass)
259 (const :tag "Scala" scala)
260 (const :tag "Scheme" scheme)
261 (const :tag "Screen" screen)
262 (const :tag "Shell Script" sh)
263 (const :tag "Shen" shen)
264 (const :tag "Sql" sql)
265 (const :tag "Sqlite" sqlite))
266 :value-type (boolean :tag "Activate" :value t)))
268 ;;;; Customization variables
269 (defcustom org-clone-delete-id nil
270 "Remove ID property of clones of a subtree.
271 When non-nil, clones of a subtree don't inherit the ID property.
272 Otherwise they inherit the ID property with a new unique
273 identifier."
274 :type 'boolean
275 :version "24.1"
276 :group 'org-id)
278 ;;; Version
279 (org-check-version)
281 ;;;###autoload
282 (defun org-version (&optional here full message)
283 "Show the org-mode version in the echo area.
284 With prefix argument HERE, insert it at point.
285 When FULL is non-nil, use a verbose version string.
286 When MESSAGE is non-nil, display a message with the version."
287 (interactive "P")
288 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
289 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
290 (load-suffixes (list ".el"))
291 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
292 (org-trash (or
293 (and (fboundp 'org-release) (fboundp 'org-git-version))
294 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
295 (load-suffixes save-load-suffixes)
296 (org-version (org-release))
297 (git-version (org-git-version))
298 (version (format "Org-mode version %s (%s @ %s)"
299 org-version
300 git-version
301 (if org-install-dir
302 (if (string= org-dir org-install-dir)
303 org-install-dir
304 (concat "mixed installation! " org-install-dir " and " org-dir))
305 "org-loaddefs.el can not be found!")))
306 (_version (if full version org-version)))
307 (if (org-called-interactively-p 'interactive)
308 (if here
309 (insert version)
310 (message version))
311 (if message (message _version))
312 _version)))
314 (defconst org-version (org-version))
316 ;;; Compatibility constants
318 ;;; The custom variables
320 (defgroup org nil
321 "Outline-based notes management and organizer."
322 :tag "Org"
323 :group 'outlines
324 :group 'calendar)
326 (defcustom org-mode-hook nil
327 "Mode hook for Org-mode, run after the mode was turned on."
328 :group 'org
329 :type 'hook)
331 (defcustom org-load-hook nil
332 "Hook that is run after org.el has been loaded."
333 :group 'org
334 :type 'hook)
336 (defcustom org-log-buffer-setup-hook nil
337 "Hook that is run after an Org log buffer is created."
338 :group 'org
339 :version "24.1"
340 :type 'hook)
342 (defvar org-modules) ; defined below
343 (defvar org-modules-loaded nil
344 "Have the modules been loaded already?")
346 (defun org-load-modules-maybe (&optional force)
347 "Load all extensions listed in `org-modules'."
348 (when (or force (not org-modules-loaded))
349 (mapc (lambda (ext)
350 (condition-case nil (require ext)
351 (error (message "Problems while trying to load feature `%s'" ext))))
352 org-modules)
353 (setq org-modules-loaded t)))
355 (defun org-set-modules (var value)
356 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
357 (set var value)
358 (when (featurep 'org)
359 (org-load-modules-maybe 'force)))
361 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
362 "Modules that should always be loaded together with org.el.
364 If a description starts with <C>, the file is not part of Emacs
365 and loading it will require that you have downloaded and properly
366 installed the Org mode distribution.
368 You can also use this system to load external packages (i.e. neither Org
369 core modules, nor modules from the CONTRIB directory). Just add symbols
370 to the end of the list. If the package is called org-xyz.el, then you need
371 to add the symbol `xyz', and the package must have a call to:
373 \(provide 'org-xyz)
375 For export specific modules, see also `org-export-backends'."
376 :group 'org
377 :set 'org-set-modules
378 :version "24.4"
379 :package-version '(Org . "8.0")
380 :type
381 '(set :greedy t
382 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
383 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
384 (const :tag " crypt: Encryption of subtrees" org-crypt)
385 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
386 (const :tag " docview: Links to doc-view buffers" org-docview)
387 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
388 (const :tag " habit: Track your consistency with habits" org-habit)
389 (const :tag " id: Global IDs for identifying entries" org-id)
390 (const :tag " info: Links to Info nodes" org-info)
391 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
392 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
393 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
394 (const :tag " mouse: Additional mouse support" org-mouse)
395 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
396 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
397 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
399 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
400 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
401 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
402 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
403 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
404 (const :tag "C collector: Collect properties into tables" org-collector)
405 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
406 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
407 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
408 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
409 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
410 (const :tag "C eval: Include command output as text" org-eval)
411 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
412 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
413 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
414 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
415 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
416 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
417 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
418 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
419 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
420 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
421 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
422 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
423 (const :tag "C mew: Links to Mew folders/messages" org-mew)
424 (const :tag "C mtags: Support for muse-like tags" org-mtags)
425 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
426 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
427 (const :tag "C registry: A registry for Org-mode links" org-registry)
428 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
429 (const :tag "C secretary: Team management with org-mode" org-secretary)
430 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
431 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
432 (const :tag "C track: Keep up with Org-mode development" org-track)
433 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
434 (const :tag "C vm: Links to VM folders/messages" org-vm)
435 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
436 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
437 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
439 (defvar org-export-registered-backends) ; From ox.el
440 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
441 (defcustom org-export-backends '(ascii html icalendar latex)
442 "List of export back-ends that should be always available.
444 If a description starts with <C>, the file is not part of Emacs
445 and loading it will require that you have downloaded and properly
446 installed the Org mode distribution.
448 Unlike to `org-modules', libraries in this list will not be
449 loaded along with Org, but only once the export framework is
450 needed.
452 This variable needs to be set before org.el is loaded. If you
453 need to make a change while Emacs is running, use the customize
454 interface or run the following code, where VALUE stands for the
455 new value of the variable, after updating it:
457 \(progn
458 \(setq org-export-registered-backends
459 \(org-remove-if-not
460 \(lambda (backend)
461 \(or (memq backend val)
462 \(catch 'parentp
463 \(mapc
464 \(lambda (b)
465 \(and (org-export-derived-backend-p b (car backend))
466 \(throw 'parentp t)))
467 val)
468 nil)))
469 org-export-registered-backends))
470 \(let ((new-list (mapcar 'car org-export-registered-backends)))
471 \(dolist (backend val)
472 \(cond
473 \((not (load (format \"ox-%s\" backend) t t))
474 \(message \"Problems while trying to load export back-end `%s'\"
475 backend))
476 \((not (memq backend new-list)) (push backend new-list))))
477 \(set-default var new-list)))
479 Adding a back-end to this list will also pull the back-end it
480 depends on, if any."
481 :group 'org
482 :group 'org-export
483 :version "24.4"
484 :package-version '(Org . "8.0")
485 :initialize 'custom-initialize-set
486 :set (lambda (var val)
487 (if (not (featurep 'ox)) (set-default var val)
488 ;; Any back-end not required anymore (not present in VAL and not
489 ;; a parent of any back-end in the new value) is removed from the
490 ;; list of registered back-ends.
491 (setq org-export-registered-backends
492 (org-remove-if-not
493 (lambda (backend)
494 (or (memq backend val)
495 (catch 'parentp
496 (mapc
497 (lambda (b)
498 (and (org-export-derived-backend-p b (car backend))
499 (throw 'parentp t)))
500 val)
501 nil)))
502 org-export-registered-backends))
503 ;; Now build NEW-LIST of both new back-ends and required
504 ;; parents.
505 (let ((new-list (mapcar 'car org-export-registered-backends)))
506 (dolist (backend val)
507 (cond
508 ((not (load (format "ox-%s" backend) t t))
509 (message "Problems while trying to load export back-end `%s'"
510 backend))
511 ((not (memq backend new-list)) (push backend new-list))))
512 ;; Set VAR to that list with fixed dependencies.
513 (set-default var new-list))))
514 :type '(set :greedy t
515 (const :tag " ascii Export buffer to ASCII format" ascii)
516 (const :tag " beamer Export buffer to Beamer presentation" beamer)
517 (const :tag " html Export buffer to HTML format" html)
518 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
519 (const :tag " latex Export buffer to LaTeX format" latex)
520 (const :tag " man Export buffer to MAN format" man)
521 (const :tag " md Export buffer to Markdown format" md)
522 (const :tag " odt Export buffer to ODT format" odt)
523 (const :tag " org Export buffer to Org format" org)
524 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
525 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
526 (const :tag "C deck Export buffer to deck.js presentations" deck)
527 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
528 (const :tag "C groff Export buffer to Groff format" groff)
529 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
530 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
531 (const :tag "C s5 Export buffer to s5 presentations" s5)
532 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
534 (eval-after-load 'ox
535 '(mapc
536 (lambda (backend)
537 (condition-case nil (require (intern (format "ox-%s" backend)))
538 (error (message "Problems while trying to load export back-end `%s'"
539 backend))))
540 org-export-backends))
542 (defcustom org-support-shift-select nil
543 "Non-nil means make shift-cursor commands select text when possible.
545 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
546 start selecting a region, or enlarge regions started in this way.
547 In Org-mode, in special contexts, these same keys are used for
548 other purposes, important enough to compete with shift selection.
549 Org tries to balance these needs by supporting `shift-select-mode'
550 outside these special contexts, under control of this variable.
552 The default of this variable is nil, to avoid confusing behavior. Shifted
553 cursor keys will then execute Org commands in the following contexts:
554 - on a headline, changing TODO state (left/right) and priority (up/down)
555 - on a time stamp, changing the time
556 - in a plain list item, changing the bullet type
557 - in a property definition line, switching between allowed values
558 - in the BEGIN line of a clock table (changing the time block).
559 Outside these contexts, the commands will throw an error.
561 When this variable is t and the cursor is not in a special
562 context, Org-mode will support shift-selection for making and
563 enlarging regions. To make this more effective, the bullet
564 cycling will no longer happen anywhere in an item line, but only
565 if the cursor is exactly on the bullet.
567 If you set this variable to the symbol `always', then the keys
568 will not be special in headlines, property lines, and item lines,
569 to make shift selection work there as well. If this is what you
570 want, you can use the following alternative commands: `C-c C-t'
571 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
572 can be used to switch TODO sets, `C-c -' to cycle item bullet
573 types, and properties can be edited by hand or in column view.
575 However, when the cursor is on a timestamp, shift-cursor commands
576 will still edit the time stamp - this is just too good to give up.
578 XEmacs user should have this variable set to nil, because
579 `shift-select-mode' is in Emacs 23 or later only."
580 :group 'org
581 :type '(choice
582 (const :tag "Never" nil)
583 (const :tag "When outside special context" t)
584 (const :tag "Everywhere except timestamps" always)))
586 (defcustom org-loop-over-headlines-in-active-region nil
587 "Shall some commands act upon headlines in the active region?
589 When set to `t', some commands will be performed in all headlines
590 within the active region.
592 When set to `start-level', some commands will be performed in all
593 headlines within the active region, provided that these headlines
594 are of the same level than the first one.
596 When set to a string, those commands will be performed on the
597 matching headlines within the active region. Such string must be
598 a tags/property/todo match as it is used in the agenda tags view.
600 The list of commands is: `org-schedule', `org-deadline',
601 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
602 `org-archive-to-archive-sibling'. The archiving commands skip
603 already archived entries."
604 :type '(choice (const :tag "Don't loop" nil)
605 (const :tag "All headlines in active region" t)
606 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
607 (string :tag "Tags/Property/Todo matcher"))
608 :version "24.1"
609 :group 'org-todo
610 :group 'org-archive)
612 (defgroup org-startup nil
613 "Options concerning startup of Org-mode."
614 :tag "Org Startup"
615 :group 'org)
617 (defcustom org-startup-folded t
618 "Non-nil means entering Org-mode will switch to OVERVIEW.
619 This can also be configured on a per-file basis by adding one of
620 the following lines anywhere in the buffer:
622 #+STARTUP: fold (or `overview', this is equivalent)
623 #+STARTUP: nofold (or `showall', this is equivalent)
624 #+STARTUP: content
625 #+STARTUP: showeverything
627 By default, this option is ignored when Org opens agenda files
628 for the first time. If you want the agenda to honor the startup
629 option, set `org-agenda-inhibit-startup' to nil."
630 :group 'org-startup
631 :type '(choice
632 (const :tag "nofold: show all" nil)
633 (const :tag "fold: overview" t)
634 (const :tag "content: all headlines" content)
635 (const :tag "show everything, even drawers" showeverything)))
637 (defcustom org-startup-truncated t
638 "Non-nil means entering Org-mode will set `truncate-lines'.
639 This is useful since some lines containing links can be very long and
640 uninteresting. Also tables look terrible when wrapped."
641 :group 'org-startup
642 :type 'boolean)
644 (defcustom org-startup-indented nil
645 "Non-nil means turn on `org-indent-mode' on startup.
646 This can also be configured on a per-file basis by adding one of
647 the following lines anywhere in the buffer:
649 #+STARTUP: indent
650 #+STARTUP: noindent"
651 :group 'org-structure
652 :type '(choice
653 (const :tag "Not" nil)
654 (const :tag "Globally (slow on startup in large files)" t)))
656 (defcustom org-use-sub-superscripts t
657 "Non-nil means interpret \"_\" and \"^\" for display.
658 When this option is turned on, you can use TeX-like syntax for sub- and
659 superscripts. Several characters after \"_\" or \"^\" will be
660 considered as a single item - so grouping with {} is normally not
661 needed. For example, the following things will be parsed as single
662 sub- or superscripts.
664 10^24 or 10^tau several digits will be considered 1 item.
665 10^-12 or 10^-tau a leading sign with digits or a word
666 x^2-y^3 will be read as x^2 - y^3, because items are
667 terminated by almost any nonword/nondigit char.
668 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
670 Still, ambiguity is possible - so when in doubt use {} to enclose
671 the sub/superscript. If you set this variable to the symbol
672 `{}', the braces are *required* in order to trigger
673 interpretations as sub/superscript. This can be helpful in
674 documents that need \"_\" frequently in plain text."
675 :group 'org-startup
676 :version "24.1"
677 :type '(choice
678 (const :tag "Always interpret" t)
679 (const :tag "Only with braces" {})
680 (const :tag "Never interpret" nil)))
682 (defcustom org-startup-with-beamer-mode nil
683 "Non-nil means turn on `org-beamer-mode' on startup.
684 This can also be configured on a per-file basis by adding one of
685 the following lines anywhere in the buffer:
687 #+STARTUP: beamer"
688 :group 'org-startup
689 :version "24.1"
690 :type 'boolean)
692 (defcustom org-startup-align-all-tables nil
693 "Non-nil means align all tables when visiting a file.
694 This is useful when the column width in tables is forced with <N> cookies
695 in table fields. Such tables will look correct only after the first re-align.
696 This can also be configured on a per-file basis by adding one of
697 the following lines anywhere in the buffer:
698 #+STARTUP: align
699 #+STARTUP: noalign"
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-startup-with-inline-images nil
704 "Non-nil means show inline images when loading a new Org file.
705 This can also be configured on a per-file basis by adding one of
706 the following lines anywhere in the buffer:
707 #+STARTUP: inlineimages
708 #+STARTUP: noinlineimages"
709 :group 'org-startup
710 :version "24.1"
711 :type 'boolean)
713 (defcustom org-startup-with-latex-preview nil
714 "Non-nil means preview LaTeX fragments when loading a new Org file.
716 This can also be configured on a per-file basis by adding one of
717 the followinglines anywhere in the buffer:
718 #+STARTUP: latexpreview
719 #+STARTUP: nolatexpreview"
720 :group 'org-startup
721 :version "24.4"
722 :package-version '(Org . "8.0")
723 :type 'boolean)
725 (defcustom org-insert-mode-line-in-empty-file nil
726 "Non-nil means insert the first line setting Org-mode in empty files.
727 When the function `org-mode' is called interactively in an empty file, this
728 normally means that the file name does not automatically trigger Org-mode.
729 To ensure that the file will always be in Org-mode in the future, a
730 line enforcing Org-mode will be inserted into the buffer, if this option
731 has been set."
732 :group 'org-startup
733 :type 'boolean)
735 (defcustom org-replace-disputed-keys nil
736 "Non-nil means use alternative key bindings for some keys.
737 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
738 These keys are also used by other packages like shift-selection-mode'
739 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
740 If you want to use Org-mode together with one of these other modes,
741 or more generally if you would like to move some Org-mode commands to
742 other keys, set this variable and configure the keys with the variable
743 `org-disputed-keys'.
745 This option is only relevant at load-time of Org-mode, and must be set
746 *before* org.el is loaded. Changing it requires a restart of Emacs to
747 become effective."
748 :group 'org-startup
749 :type 'boolean)
751 (defcustom org-use-extra-keys nil
752 "Non-nil means use extra key sequence definitions for certain commands.
753 This happens automatically if you run XEmacs or if `window-system'
754 is nil. This variable lets you do the same manually. You must
755 set it before loading org.
757 Example: on Carbon Emacs 22 running graphically, with an external
758 keyboard on a Powerbook, the default way of setting M-left might
759 not work for either Alt or ESC. Setting this variable will make
760 it work for ESC."
761 :group 'org-startup
762 :type 'boolean)
764 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
766 (defcustom org-disputed-keys
767 '(([(shift up)] . [(meta p)])
768 ([(shift down)] . [(meta n)])
769 ([(shift left)] . [(meta -)])
770 ([(shift right)] . [(meta +)])
771 ([(control shift right)] . [(meta shift +)])
772 ([(control shift left)] . [(meta shift -)]))
773 "Keys for which Org-mode and other modes compete.
774 This is an alist, cars are the default keys, second element specifies
775 the alternative to use when `org-replace-disputed-keys' is t.
777 Keys can be specified in any syntax supported by `define-key'.
778 The value of this option takes effect only at Org-mode's startup,
779 therefore you'll have to restart Emacs to apply it after changing."
780 :group 'org-startup
781 :type 'alist)
783 (defun org-key (key)
784 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
785 Or return the original if not disputed.
786 Also apply the translations defined in `org-xemacs-key-equivalents'."
787 (when org-replace-disputed-keys
788 (let* ((nkey (key-description key))
789 (x (org-find-if (lambda (x)
790 (equal (key-description (car x)) nkey))
791 org-disputed-keys)))
792 (setq key (if x (cdr x) key))))
793 (when (featurep 'xemacs)
794 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
795 key)
797 (defun org-find-if (predicate seq)
798 (catch 'exit
799 (while seq
800 (if (funcall predicate (car seq))
801 (throw 'exit (car seq))
802 (pop seq)))))
804 (defun org-defkey (keymap key def)
805 "Define a key, possibly translated, as returned by `org-key'."
806 (define-key keymap (org-key key) def))
808 (defcustom org-ellipsis nil
809 "The ellipsis to use in the Org-mode outline.
810 When nil, just use the standard three dots. When a string, use that instead,
811 When a face, use the standard 3 dots, but with the specified face.
812 The change affects only Org-mode (which will then use its own display table).
813 Changing this requires executing `M-x org-mode' in a buffer to become
814 effective."
815 :group 'org-startup
816 :type '(choice (const :tag "Default" nil)
817 (face :tag "Face" :value org-warning)
818 (string :tag "String" :value "...#")))
820 (defvar org-display-table nil
821 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
823 (defgroup org-keywords nil
824 "Keywords in Org-mode."
825 :tag "Org Keywords"
826 :group 'org)
828 (defcustom org-deadline-string "DEADLINE:"
829 "String to mark deadline entries.
830 A deadline is this string, followed by a time stamp. Should be a word,
831 terminated by a colon. You can insert a schedule keyword and
832 a timestamp with \\[org-deadline].
833 Changes become only effective after restarting Emacs."
834 :group 'org-keywords
835 :type 'string)
837 (defcustom org-scheduled-string "SCHEDULED:"
838 "String to mark scheduled TODO entries.
839 A schedule is this string, followed by a time stamp. Should be a word,
840 terminated by a colon. You can insert a schedule keyword and
841 a timestamp with \\[org-schedule].
842 Changes become only effective after restarting Emacs."
843 :group 'org-keywords
844 :type 'string)
846 (defcustom org-closed-string "CLOSED:"
847 "String used as the prefix for timestamps logging closing a TODO entry."
848 :group 'org-keywords
849 :type 'string)
851 (defcustom org-clock-string "CLOCK:"
852 "String used as prefix for timestamps clocking work hours on an item."
853 :group 'org-keywords
854 :type 'string)
856 (defcustom org-closed-keep-when-no-todo nil
857 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
858 :group 'org-todo
859 :group 'org-keywords
860 :version "24.4"
861 :package-version '(Org . "8.0")
862 :type 'boolean)
864 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
865 org-scheduled-string "\\|"
866 org-deadline-string "\\|"
867 org-closed-string "\\|"
868 org-clock-string "\\)")
869 "Matches a line with planning or clock info.")
871 (defcustom org-comment-string "COMMENT"
872 "Entries starting with this keyword will never be exported.
873 An entry can be toggled between COMMENT and normal with
874 \\[org-toggle-comment].
875 Changes become only effective after restarting Emacs."
876 :group 'org-keywords
877 :type 'string)
879 (defcustom org-quote-string "QUOTE"
880 "Entries starting with this keyword will be exported in fixed-width font.
881 Quoting applies only to the text in the entry following the headline, and does
882 not extend beyond the next headline, even if that is lower level.
883 An entry can be toggled between QUOTE and normal with
884 \\[org-toggle-fixed-width-section]."
885 :group 'org-keywords
886 :type 'string)
888 (defconst org-repeat-re
889 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
890 "Regular expression for specifying repeated events.
891 After a match, group 1 contains the repeat expression.")
893 (defgroup org-structure nil
894 "Options concerning the general structure of Org-mode files."
895 :tag "Org Structure"
896 :group 'org)
898 (defgroup org-reveal-location nil
899 "Options about how to make context of a location visible."
900 :tag "Org Reveal Location"
901 :group 'org-structure)
903 (defconst org-context-choice
904 '(choice
905 (const :tag "Always" t)
906 (const :tag "Never" nil)
907 (repeat :greedy t :tag "Individual contexts"
908 (cons
909 (choice :tag "Context"
910 (const agenda)
911 (const org-goto)
912 (const occur-tree)
913 (const tags-tree)
914 (const link-search)
915 (const mark-goto)
916 (const bookmark-jump)
917 (const isearch)
918 (const default))
919 (boolean))))
920 "Contexts for the reveal options.")
922 (defcustom org-show-hierarchy-above '((default . t))
923 "Non-nil means show full hierarchy when revealing a location.
924 Org-mode often shows locations in an org-mode file which might have
925 been invisible before. When this is set, the hierarchy of headings
926 above the exposed location is shown.
927 Turning this off for example for sparse trees makes them very compact.
928 Instead of t, this can also be an alist specifying this option for different
929 contexts. Valid contexts are
930 agenda when exposing an entry from the agenda
931 org-goto when using the command `org-goto' on key C-c C-j
932 occur-tree when using the command `org-occur' on key C-c /
933 tags-tree when constructing a sparse tree based on tags matches
934 link-search when exposing search matches associated with a link
935 mark-goto when exposing the jump goal of a mark
936 bookmark-jump when exposing a bookmark location
937 isearch when exiting from an incremental search
938 default default for all contexts not set explicitly"
939 :group 'org-reveal-location
940 :type org-context-choice)
942 (defcustom org-show-following-heading '((default . nil))
943 "Non-nil means show following heading when revealing a location.
944 Org-mode often shows locations in an org-mode file which might have
945 been invisible before. When this is set, the heading following the
946 match is shown.
947 Turning this off for example for sparse trees makes them very compact,
948 but makes it harder to edit the location of the match. In such a case,
949 use the command \\[org-reveal] to show more context.
950 Instead of t, this can also be an alist specifying this option for different
951 contexts. See `org-show-hierarchy-above' for valid contexts."
952 :group 'org-reveal-location
953 :type org-context-choice)
955 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
956 "Non-nil means show all sibling heading when revealing a location.
957 Org-mode often shows locations in an org-mode file which might have
958 been invisible before. When this is set, the sibling of the current entry
959 heading are all made visible. If `org-show-hierarchy-above' is t,
960 the same happens on each level of the hierarchy above the current entry.
962 By default this is on for the isearch context, off for all other contexts.
963 Turning this off for example for sparse trees makes them very compact,
964 but makes it harder to edit the location of the match. In such a case,
965 use the command \\[org-reveal] to show more context.
966 Instead of t, this can also be an alist specifying this option for different
967 contexts. See `org-show-hierarchy-above' for valid contexts."
968 :group 'org-reveal-location
969 :type org-context-choice
970 :version "24.4"
971 :package-version '(Org . "8.0"))
973 (defcustom org-show-entry-below '((default . nil))
974 "Non-nil means show the entry below a headline when revealing a location.
975 Org-mode often shows locations in an org-mode file which might have
976 been invisible before. When this is set, the text below the headline that is
977 exposed is also shown.
979 By default this is off for all contexts.
980 Instead of t, this can also be an alist specifying this option for different
981 contexts. See `org-show-hierarchy-above' for valid contexts."
982 :group 'org-reveal-location
983 :type org-context-choice)
985 (defcustom org-indirect-buffer-display 'other-window
986 "How should indirect tree buffers be displayed?
987 This applies to indirect buffers created with the commands
988 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
989 Valid values are:
990 current-window Display in the current window
991 other-window Just display in another window.
992 dedicated-frame Create one new frame, and re-use it each time.
993 new-frame Make a new frame each time. Note that in this case
994 previously-made indirect buffers are kept, and you need to
995 kill these buffers yourself."
996 :group 'org-structure
997 :group 'org-agenda-windows
998 :type '(choice
999 (const :tag "In current window" current-window)
1000 (const :tag "In current frame, other window" other-window)
1001 (const :tag "Each time a new frame" new-frame)
1002 (const :tag "One dedicated frame" dedicated-frame)))
1004 (defcustom org-use-speed-commands nil
1005 "Non-nil means activate single letter commands at beginning of a headline.
1006 This may also be a function to test for appropriate locations where speed
1007 commands should be active."
1008 :group 'org-structure
1009 :type '(choice
1010 (const :tag "Never" nil)
1011 (const :tag "At beginning of headline stars" t)
1012 (function)))
1014 (defcustom org-speed-commands-user nil
1015 "Alist of additional speed commands.
1016 This list will be checked before `org-speed-commands-default'
1017 when the variable `org-use-speed-commands' is non-nil
1018 and when the cursor is at the beginning of a headline.
1019 The car if each entry is a string with a single letter, which must
1020 be assigned to `self-insert-command' in the global map.
1021 The cdr is either a command to be called interactively, a function
1022 to be called, or a form to be evaluated.
1023 An entry that is just a list with a single string will be interpreted
1024 as a descriptive headline that will be added when listing the speed
1025 commands in the Help buffer using the `?' speed command."
1026 :group 'org-structure
1027 :type '(repeat :value ("k" . ignore)
1028 (choice :value ("k" . ignore)
1029 (list :tag "Descriptive Headline" (string :tag "Headline"))
1030 (cons :tag "Letter and Command"
1031 (string :tag "Command letter")
1032 (choice
1033 (function)
1034 (sexp))))))
1036 (defgroup org-cycle nil
1037 "Options concerning visibility cycling in Org-mode."
1038 :tag "Org Cycle"
1039 :group 'org-structure)
1041 (defcustom org-cycle-skip-children-state-if-no-children t
1042 "Non-nil means skip CHILDREN state in entries that don't have any."
1043 :group 'org-cycle
1044 :type 'boolean)
1046 (defcustom org-cycle-max-level nil
1047 "Maximum level which should still be subject to visibility cycling.
1048 Levels higher than this will, for cycling, be treated as text, not a headline.
1049 When `org-odd-levels-only' is set, a value of N in this variable actually
1050 means 2N-1 stars as the limiting headline.
1051 When nil, cycle all levels.
1052 Note that the limiting level of cycling is also influenced by
1053 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1054 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1055 than its value."
1056 :group 'org-cycle
1057 :type '(choice
1058 (const :tag "No limit" nil)
1059 (integer :tag "Maximum level")))
1061 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1062 "Names of drawers. Drawers are not opened by cycling on the headline above.
1063 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1064 this:
1065 :DRAWERNAME:
1066 .....
1067 :END:
1068 The drawer \"PROPERTIES\" is special for capturing properties through
1069 the property API.
1071 Drawers can be defined on the per-file basis with a line like:
1073 #+DRAWERS: HIDDEN STATE PROPERTIES"
1074 :group 'org-structure
1075 :group 'org-cycle
1076 :type '(repeat (string :tag "Drawer Name")))
1078 (defcustom org-hide-block-startup nil
1079 "Non-nil means entering Org-mode will fold all blocks.
1080 This can also be set in on a per-file basis with
1082 #+STARTUP: hideblocks
1083 #+STARTUP: showblocks"
1084 :group 'org-startup
1085 :group 'org-cycle
1086 :type 'boolean)
1088 (defcustom org-cycle-global-at-bob nil
1089 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1090 This makes it possible to do global cycling without having to use S-TAB or
1091 \\[universal-argument] TAB. For this special case to work, the first line
1092 of the buffer must not be a headline -- it may be empty or some other text.
1093 When used in this way, `org-cycle-hook' is disabled temporarily to make
1094 sure the cursor stays at the beginning of the buffer. When this option is
1095 nil, don't do anything special at the beginning of the buffer."
1096 :group 'org-cycle
1097 :type 'boolean)
1099 (defcustom org-cycle-level-after-item/entry-creation t
1100 "Non-nil means cycle entry level or item indentation in new empty entries.
1102 When the cursor is at the end of an empty headline, i.e., with only stars
1103 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1104 and then all possible ancestor states, before returning to the original state.
1105 This makes data entry extremely fast: M-RET to create a new headline,
1106 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1108 When the cursor is at the end of an empty plain list item, one TAB will
1109 make it a subitem, two or more tabs will back up to make this an item
1110 higher up in the item hierarchy."
1111 :group 'org-cycle
1112 :type 'boolean)
1114 (defcustom org-cycle-emulate-tab t
1115 "Where should `org-cycle' emulate TAB.
1116 nil Never
1117 white Only in completely white lines
1118 whitestart Only at the beginning of lines, before the first non-white char
1119 t Everywhere except in headlines
1120 exc-hl-bol Everywhere except at the start of a headline
1121 If TAB is used in a place where it does not emulate TAB, the current subtree
1122 visibility is cycled."
1123 :group 'org-cycle
1124 :type '(choice (const :tag "Never" nil)
1125 (const :tag "Only in completely white lines" white)
1126 (const :tag "Before first char in a line" whitestart)
1127 (const :tag "Everywhere except in headlines" t)
1128 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1130 (defcustom org-cycle-separator-lines 2
1131 "Number of empty lines needed to keep an empty line between collapsed trees.
1132 If you leave an empty line between the end of a subtree and the following
1133 headline, this empty line is hidden when the subtree is folded.
1134 Org-mode will leave (exactly) one empty line visible if the number of
1135 empty lines is equal or larger to the number given in this variable.
1136 So the default 2 means at least 2 empty lines after the end of a subtree
1137 are needed to produce free space between a collapsed subtree and the
1138 following headline.
1140 If the number is negative, and the number of empty lines is at least -N,
1141 all empty lines are shown.
1143 Special case: when 0, never leave empty lines in collapsed view."
1144 :group 'org-cycle
1145 :type 'integer)
1146 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1148 (defcustom org-pre-cycle-hook nil
1149 "Hook that is run before visibility cycling is happening.
1150 The function(s) in this hook must accept a single argument which indicates
1151 the new state that will be set right after running this hook. The
1152 argument is a symbol. Before a global state change, it can have the values
1153 `overview', `content', or `all'. Before a local state change, it can have
1154 the values `folded', `children', or `subtree'."
1155 :group 'org-cycle
1156 :type 'hook)
1158 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1159 org-cycle-hide-drawers
1160 org-cycle-hide-inline-tasks
1161 org-cycle-show-empty-lines
1162 org-optimize-window-after-visibility-change)
1163 "Hook that is run after `org-cycle' has changed the buffer visibility.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that was set by the most recent `org-cycle' command. The
1166 argument is a symbol. After a global state change, it can have the values
1167 `overview', `contents', or `all'. After a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defgroup org-edit-structure nil
1173 "Options concerning structure editing in Org-mode."
1174 :tag "Org Edit Structure"
1175 :group 'org-structure)
1177 (defcustom org-odd-levels-only nil
1178 "Non-nil means skip even levels and only use odd levels for the outline.
1179 This has the effect that two stars are being added/taken away in
1180 promotion/demotion commands. It also influences how levels are
1181 handled by the exporters.
1182 Changing it requires restart of `font-lock-mode' to become effective
1183 for fontification also in regions already fontified.
1184 You may also set this on a per-file basis by adding one of the following
1185 lines to the buffer:
1187 #+STARTUP: odd
1188 #+STARTUP: oddeven"
1189 :group 'org-edit-structure
1190 :group 'org-appearance
1191 :type 'boolean)
1193 (defcustom org-adapt-indentation t
1194 "Non-nil means adapt indentation to outline node level.
1196 When this variable is set, Org assumes that you write outlines by
1197 indenting text in each node to align with the headline (after the stars).
1198 The following issues are influenced by this variable:
1200 - When this is set and the *entire* text in an entry is indented, the
1201 indentation is increased by one space in a demotion command, and
1202 decreased by one in a promotion command. If any line in the entry
1203 body starts with text at column 0, indentation is not changed at all.
1205 - Property drawers and planning information is inserted indented when
1206 this variable s set. When nil, they will not be indented.
1208 - TAB indents a line relative to context. The lines below a headline
1209 will be indented when this variable is set.
1211 Note that this is all about true indentation, by adding and removing
1212 space characters. See also `org-indent.el' which does level-dependent
1213 indentation in a virtual way, i.e. at display time in Emacs."
1214 :group 'org-edit-structure
1215 :type 'boolean)
1217 (defcustom org-special-ctrl-a/e nil
1218 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1220 When t, `C-a' will bring back the cursor to the beginning of the
1221 headline text, i.e. after the stars and after a possible TODO
1222 keyword. In an item, this will be the position after bullet and
1223 check-box, if any. When the cursor is already at that position,
1224 another `C-a' will bring it to the beginning of the line.
1226 `C-e' will jump to the end of the headline, ignoring the presence
1227 of tags in the headline. A second `C-e' will then jump to the
1228 true end of the line, after any tags. This also means that, when
1229 this variable is non-nil, `C-e' also will never jump beyond the
1230 end of the heading of a folded section, i.e. not after the
1231 ellipses.
1233 When set to the symbol `reversed', the first `C-a' or `C-e' works
1234 normally, going to the true line boundary first. Only a directly
1235 following, identical keypress will bring the cursor to the
1236 special positions.
1238 This may also be a cons cell where the behavior for `C-a' and
1239 `C-e' is set separately."
1240 :group 'org-edit-structure
1241 :type '(choice
1242 (const :tag "off" nil)
1243 (const :tag "on: after stars/bullet and before tags first" t)
1244 (const :tag "reversed: true line boundary first" reversed)
1245 (cons :tag "Set C-a and C-e separately"
1246 (choice :tag "Special C-a"
1247 (const :tag "off" nil)
1248 (const :tag "on: after stars/bullet first" t)
1249 (const :tag "reversed: before stars/bullet first" reversed))
1250 (choice :tag "Special C-e"
1251 (const :tag "off" nil)
1252 (const :tag "on: before tags first" t)
1253 (const :tag "reversed: after tags first" reversed)))))
1254 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1256 (defcustom org-special-ctrl-k nil
1257 "Non-nil means `C-k' will behave specially in headlines.
1258 When nil, `C-k' will call the default `kill-line' command.
1259 When t, the following will happen while the cursor is in the headline:
1261 - When the cursor is at the beginning of a headline, kill the entire
1262 line and possible the folded subtree below the line.
1263 - When in the middle of the headline text, kill the headline up to the tags.
1264 - When after the headline text, kill the tags."
1265 :group 'org-edit-structure
1266 :type 'boolean)
1268 (defcustom org-ctrl-k-protect-subtree nil
1269 "Non-nil means, do not delete a hidden subtree with C-k.
1270 When set to the symbol `error', simply throw an error when C-k is
1271 used to kill (part-of) a headline that has hidden text behind it.
1272 Any other non-nil value will result in a query to the user, if it is
1273 OK to kill that hidden subtree. When nil, kill without remorse."
1274 :group 'org-edit-structure
1275 :version "24.1"
1276 :type '(choice
1277 (const :tag "Do not protect hidden subtrees" nil)
1278 (const :tag "Protect hidden subtrees with a security query" t)
1279 (const :tag "Never kill a hidden subtree with C-k" error)))
1281 (defcustom org-catch-invisible-edits nil
1282 "Check if in invisible region before inserting or deleting a character.
1283 Valid values are:
1285 nil Do not check, so just do invisible edits.
1286 error Throw an error and do nothing.
1287 show Make point visible, and do the requested edit.
1288 show-and-error Make point visible, then throw an error and abort the edit.
1289 smart Make point visible, and do insertion/deletion if it is
1290 adjacent to visible text and the change feels predictable.
1291 Never delete a previously invisible character or add in the
1292 middle or right after an invisible region. Basically, this
1293 allows insertion and backward-delete right before ellipses.
1294 FIXME: maybe in this case we should not even show?"
1295 :group 'org-edit-structure
1296 :version "24.1"
1297 :type '(choice
1298 (const :tag "Do not check" nil)
1299 (const :tag "Throw error when trying to edit" error)
1300 (const :tag "Unhide, but do not do the edit" show-and-error)
1301 (const :tag "Show invisible part and do the edit" show)
1302 (const :tag "Be smart and do the right thing" smart)))
1304 (defcustom org-yank-folded-subtrees t
1305 "Non-nil means when yanking subtrees, fold them.
1306 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1307 it starts with a heading and all other headings in it are either children
1308 or siblings, then fold all the subtrees. However, do this only if no
1309 text after the yank would be swallowed into a folded tree by this action."
1310 :group 'org-edit-structure
1311 :type 'boolean)
1313 (defcustom org-yank-adjusted-subtrees nil
1314 "Non-nil means when yanking subtrees, adjust the level.
1315 With this setting, `org-paste-subtree' is used to insert the subtree, see
1316 this function for details."
1317 :group 'org-edit-structure
1318 :type 'boolean)
1320 (defcustom org-M-RET-may-split-line '((default . t))
1321 "Non-nil means M-RET will split the line at the cursor position.
1322 When nil, it will go to the end of the line before making a
1323 new line.
1324 You may also set this option in a different way for different
1325 contexts. Valid contexts are:
1327 headline when creating a new headline
1328 item when creating a new item
1329 table in a table field
1330 default the value to be used for all contexts not explicitly
1331 customized"
1332 :group 'org-structure
1333 :group 'org-table
1334 :type '(choice
1335 (const :tag "Always" t)
1336 (const :tag "Never" nil)
1337 (repeat :greedy t :tag "Individual contexts"
1338 (cons
1339 (choice :tag "Context"
1340 (const headline)
1341 (const item)
1342 (const table)
1343 (const default))
1344 (boolean)))))
1347 (defcustom org-insert-heading-respect-content nil
1348 "Non-nil means insert new headings after the current subtree.
1349 When nil, the new heading is created directly after the current line.
1350 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1351 this variable on for the duration of the command."
1352 :group 'org-structure
1353 :type 'boolean)
1355 (defcustom org-blank-before-new-entry '((heading . auto)
1356 (plain-list-item . auto))
1357 "Should `org-insert-heading' leave a blank line before new heading/item?
1358 The value is an alist, with `heading' and `plain-list-item' as CAR,
1359 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1360 which case Org will look at the surrounding headings/items and try to
1361 make an intelligent decision whether to insert a blank line or not.
1363 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1364 the setting here is ignored and no empty line is inserted to avoid breaking
1365 the list structure."
1366 :group 'org-edit-structure
1367 :type '(list
1368 (cons (const heading)
1369 (choice (const :tag "Never" nil)
1370 (const :tag "Always" t)
1371 (const :tag "Auto" auto)))
1372 (cons (const plain-list-item)
1373 (choice (const :tag "Never" nil)
1374 (const :tag "Always" t)
1375 (const :tag "Auto" auto)))))
1377 (defcustom org-insert-heading-hook nil
1378 "Hook being run after inserting a new heading."
1379 :group 'org-edit-structure
1380 :type 'hook)
1382 (defcustom org-enable-fixed-width-editor t
1383 "Non-nil means lines starting with \":\" are treated as fixed-width.
1384 This currently only means they are never auto-wrapped.
1385 When nil, such lines will be treated like ordinary lines.
1386 See also the QUOTE keyword."
1387 :group 'org-edit-structure
1388 :type 'boolean)
1390 (defcustom org-goto-auto-isearch t
1391 "Non-nil means typing characters in `org-goto' starts incremental search.
1392 When nil, you can use these keybindings to navigate the buffer:
1394 q Quit the org-goto interface
1395 n Go to the next visible heading
1396 p Go to the previous visible heading
1397 f Go one heading forward on same level
1398 b Go one heading backward on same level
1399 u Go one heading up"
1400 :group 'org-edit-structure
1401 :type 'boolean)
1403 (defgroup org-sparse-trees nil
1404 "Options concerning sparse trees in Org-mode."
1405 :tag "Org Sparse Trees"
1406 :group 'org-structure)
1408 (defcustom org-highlight-sparse-tree-matches t
1409 "Non-nil means highlight all matches that define a sparse tree.
1410 The highlights will automatically disappear the next time the buffer is
1411 changed by an edit command."
1412 :group 'org-sparse-trees
1413 :type 'boolean)
1415 (defcustom org-remove-highlights-with-change t
1416 "Non-nil means any change to the buffer will remove temporary highlights.
1417 Such highlights are created by `org-occur' and `org-clock-display'.
1418 When nil, `C-c C-c needs to be used to get rid of the highlights.
1419 The highlights created by `org-preview-latex-fragment' always need
1420 `C-c C-c' to be removed."
1421 :group 'org-sparse-trees
1422 :group 'org-time
1423 :type 'boolean)
1426 (defcustom org-occur-hook '(org-first-headline-recenter)
1427 "Hook that is run after `org-occur' has constructed a sparse tree.
1428 This can be used to recenter the window to show as much of the structure
1429 as possible."
1430 :group 'org-sparse-trees
1431 :type 'hook)
1433 (defgroup org-imenu-and-speedbar nil
1434 "Options concerning imenu and speedbar in Org-mode."
1435 :tag "Org Imenu and Speedbar"
1436 :group 'org-structure)
1438 (defcustom org-imenu-depth 2
1439 "The maximum level for Imenu access to Org-mode headlines.
1440 This also applied for speedbar access."
1441 :group 'org-imenu-and-speedbar
1442 :type 'integer)
1444 (defgroup org-table nil
1445 "Options concerning tables in Org-mode."
1446 :tag "Org Table"
1447 :group 'org)
1449 (defcustom org-enable-table-editor 'optimized
1450 "Non-nil means lines starting with \"|\" are handled by the table editor.
1451 When nil, such lines will be treated like ordinary lines.
1453 When equal to the symbol `optimized', the table editor will be optimized to
1454 do the following:
1455 - Automatic overwrite mode in front of whitespace in table fields.
1456 This makes the structure of the table stay in tact as long as the edited
1457 field does not exceed the column width.
1458 - Minimize the number of realigns. Normally, the table is aligned each time
1459 TAB or RET are pressed to move to another field. With optimization this
1460 happens only if changes to a field might have changed the column width.
1461 Optimization requires replacing the functions `self-insert-command',
1462 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1463 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1464 very good at guessing when a re-align will be necessary, but you can always
1465 force one with \\[org-ctrl-c-ctrl-c].
1467 If you would like to use the optimized version in Org-mode, but the
1468 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1470 This variable can be used to turn on and off the table editor during a session,
1471 but in order to toggle optimization, a restart is required.
1473 See also the variable `org-table-auto-blank-field'."
1474 :group 'org-table
1475 :type '(choice
1476 (const :tag "off" nil)
1477 (const :tag "on" t)
1478 (const :tag "on, optimized" optimized)))
1480 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1481 (version<= emacs-version "24.1"))
1482 "Non-nil means cluster self-insert commands for undo when possible.
1483 If this is set, then, like in the Emacs command loop, 20 consecutive
1484 characters will be undone together.
1485 This is configurable, because there is some impact on typing performance."
1486 :group 'org-table
1487 :type 'boolean)
1489 (defcustom org-table-tab-recognizes-table.el t
1490 "Non-nil means TAB will automatically notice a table.el table.
1491 When it sees such a table, it moves point into it and - if necessary -
1492 calls `table-recognize-table'."
1493 :group 'org-table-editing
1494 :type 'boolean)
1496 (defgroup org-link nil
1497 "Options concerning links in Org-mode."
1498 :tag "Org Link"
1499 :group 'org)
1501 (defvar org-link-abbrev-alist-local nil
1502 "Buffer-local version of `org-link-abbrev-alist', which see.
1503 The value of this is taken from the #+LINK lines.")
1504 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1506 (defcustom org-link-abbrev-alist nil
1507 "Alist of link abbreviations.
1508 The car of each element is a string, to be replaced at the start of a link.
1509 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1510 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1512 [[linkkey:tag][description]]
1514 The 'linkkey' must be a word word, starting with a letter, followed
1515 by letters, numbers, '-' or '_'.
1517 If REPLACE is a string, the tag will simply be appended to create the link.
1518 If the string contains \"%s\", the tag will be inserted there. If the string
1519 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1520 at that point (see the function `url-hexify-string'). If the string contains
1521 the specifier \"%(my-function)\", then the custom function `my-function' will
1522 be invoked: this function takes the tag as its only argument and must return
1523 a string.
1525 REPLACE may also be a function that will be called with the tag as the
1526 only argument to create the link, which should be returned as a string.
1528 See the manual for examples."
1529 :group 'org-link
1530 :type '(repeat
1531 (cons
1532 (string :tag "Protocol")
1533 (choice
1534 (string :tag "Format")
1535 (function)))))
1537 (defcustom org-descriptive-links t
1538 "Non-nil means Org will display descriptive links.
1539 E.g. [[http://orgmode.org][Org website]] will be displayed as
1540 \"Org Website\", hiding the link itself and just displaying its
1541 description. When set to `nil', Org will display the full links
1542 literally.
1544 You can interactively set the value of this variable by calling
1545 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1546 :group 'org-link
1547 :type 'boolean)
1549 (defcustom org-link-file-path-type 'adaptive
1550 "How the path name in file links should be stored.
1551 Valid values are:
1553 relative Relative to the current directory, i.e. the directory of the file
1554 into which the link is being inserted.
1555 absolute Absolute path, if possible with ~ for home directory.
1556 noabbrev Absolute path, no abbreviation of home directory.
1557 adaptive Use relative path for files in the current directory and sub-
1558 directories of it. For other files, use an absolute path."
1559 :group 'org-link
1560 :type '(choice
1561 (const relative)
1562 (const absolute)
1563 (const noabbrev)
1564 (const adaptive)))
1566 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1567 "Types of links that should be activated in Org-mode files.
1568 This is a list of symbols, each leading to the activation of a certain link
1569 type. In principle, it does not hurt to turn on most link types - there may
1570 be a small gain when turning off unused link types. The types are:
1572 bracket The recommended [[link][description]] or [[link]] links with hiding.
1573 angle Links in angular brackets that may contain whitespace like
1574 <bbdb:Carsten Dominik>.
1575 plain Plain links in normal text, no whitespace, like http://google.com.
1576 radio Text that is matched by a radio target, see manual for details.
1577 tag Tag settings in a headline (link to tag search).
1578 date Time stamps (link to calendar).
1579 footnote Footnote labels.
1581 Changing this variable requires a restart of Emacs to become effective."
1582 :group 'org-link
1583 :type '(set :greedy t
1584 (const :tag "Double bracket links" bracket)
1585 (const :tag "Angular bracket links" angle)
1586 (const :tag "Plain text links" plain)
1587 (const :tag "Radio target matches" radio)
1588 (const :tag "Tags" tag)
1589 (const :tag "Timestamps" date)
1590 (const :tag "Footnotes" footnote)))
1592 (defcustom org-make-link-description-function nil
1593 "Function to use for generating link descriptions from links.
1594 When nil, the link location will be used. This function must take
1595 two parameters: the first one is the link, the second one is the
1596 description generated by `org-insert-link'. The function should
1597 return the description to use."
1598 :group 'org-link
1599 :type 'function)
1601 (defgroup org-link-store nil
1602 "Options concerning storing links in Org-mode."
1603 :tag "Org Store Link"
1604 :group 'org-link)
1606 (defcustom org-url-hexify-p t
1607 "When non-nil, hexify URL when creating a link."
1608 :type 'boolean
1609 :version "24.3"
1610 :group 'org-link-store)
1612 (defcustom org-email-link-description-format "Email %c: %.30s"
1613 "Format of the description part of a link to an email or usenet message.
1614 The following %-escapes will be replaced by corresponding information:
1616 %F full \"From\" field
1617 %f name, taken from \"From\" field, address if no name
1618 %T full \"To\" field
1619 %t first name in \"To\" field, address if no name
1620 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1621 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1622 %s subject
1623 %d date
1624 %m message-id.
1626 You may use normal field width specification between the % and the letter.
1627 This is for example useful to limit the length of the subject.
1629 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1630 :group 'org-link-store
1631 :type 'string)
1633 (defcustom org-from-is-user-regexp
1634 (let (r1 r2)
1635 (when (and user-mail-address (not (string= user-mail-address "")))
1636 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1637 (when (and user-full-name (not (string= user-full-name "")))
1638 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1639 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1640 "Regexp matched against the \"From:\" header of an email or usenet message.
1641 It should match if the message is from the user him/herself."
1642 :group 'org-link-store
1643 :type 'regexp)
1645 (defcustom org-context-in-file-links t
1646 "Non-nil means file links from `org-store-link' contain context.
1647 A search string will be added to the file name with :: as separator and
1648 used to find the context when the link is activated by the command
1649 `org-open-at-point'. When this option is t, the entire active region
1650 will be placed in the search string of the file link. If set to a
1651 positive integer, only the first n lines of context will be stored.
1653 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1654 negates this setting for the duration of the command."
1655 :group 'org-link-store
1656 :type '(choice boolean integer))
1658 (defcustom org-keep-stored-link-after-insertion nil
1659 "Non-nil means keep link in list for entire session.
1661 The command `org-store-link' adds a link pointing to the current
1662 location to an internal list. These links accumulate during a session.
1663 The command `org-insert-link' can be used to insert links into any
1664 Org-mode file (offering completion for all stored links). When this
1665 option is nil, every link which has been inserted once using \\[org-insert-link]
1666 will be removed from the list, to make completing the unused links
1667 more efficient."
1668 :group 'org-link-store
1669 :type 'boolean)
1671 (defgroup org-link-follow nil
1672 "Options concerning following links in Org-mode."
1673 :tag "Org Follow Link"
1674 :group 'org-link)
1676 (defcustom org-link-translation-function nil
1677 "Function to translate links with different syntax to Org syntax.
1678 This can be used to translate links created for example by the Planner
1679 or emacs-wiki packages to Org syntax.
1680 The function must accept two parameters, a TYPE containing the link
1681 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1682 which is everything after the link protocol. It should return a cons
1683 with possibly modified values of type and path.
1684 Org contains a function for this, so if you set this variable to
1685 `org-translate-link-from-planner', you should be able follow many
1686 links created by planner."
1687 :group 'org-link-follow
1688 :type 'function)
1690 (defcustom org-follow-link-hook nil
1691 "Hook that is run after a link has been followed."
1692 :group 'org-link-follow
1693 :type 'hook)
1695 (defcustom org-tab-follows-link nil
1696 "Non-nil means on links TAB will follow the link.
1697 Needs to be set before org.el is loaded.
1698 This really should not be used, it does not make sense, and the
1699 implementation is bad."
1700 :group 'org-link-follow
1701 :type 'boolean)
1703 (defcustom org-return-follows-link nil
1704 "Non-nil means on links RET will follow the link.
1705 In tables, the special behavior of RET has precedence."
1706 :group 'org-link-follow
1707 :type 'boolean)
1709 (defcustom org-mouse-1-follows-link
1710 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1711 "Non-nil means mouse-1 on a link will follow the link.
1712 A longer mouse click will still set point. Does not work on XEmacs.
1713 Needs to be set before org.el is loaded."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-mark-ring-length 4
1718 "Number of different positions to be recorded in the ring.
1719 Changing this requires a restart of Emacs to work correctly."
1720 :group 'org-link-follow
1721 :type 'integer)
1723 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1724 "Non-nil means internal links in Org files must exactly match a headline.
1725 When nil, the link search tries to match a phrase with all words
1726 in the search text."
1727 :group 'org-link-follow
1728 :version "24.1"
1729 :type '(choice
1730 (const :tag "Use fuzzy text search" nil)
1731 (const :tag "Match only exact headline" t)
1732 (const :tag "Match exact headline or query to create it"
1733 query-to-create)))
1735 (defcustom org-link-frame-setup
1736 '((vm . vm-visit-folder-other-frame)
1737 (vm-imap . vm-visit-imap-folder-other-frame)
1738 (gnus . org-gnus-no-new-news)
1739 (file . find-file-other-window)
1740 (wl . wl-other-frame))
1741 "Setup the frame configuration for following links.
1742 When following a link with Emacs, it may often be useful to display
1743 this link in another window or frame. This variable can be used to
1744 set this up for the different types of links.
1745 For VM, use any of
1746 `vm-visit-folder'
1747 `vm-visit-folder-other-window'
1748 `vm-visit-folder-other-frame'
1749 For Gnus, use any of
1750 `gnus'
1751 `gnus-other-frame'
1752 `org-gnus-no-new-news'
1753 For FILE, use any of
1754 `find-file'
1755 `find-file-other-window'
1756 `find-file-other-frame'
1757 For Wanderlust use any of
1758 `wl'
1759 `wl-other-frame'
1760 For the calendar, use the variable `calendar-setup'.
1761 For BBDB, it is currently only possible to display the matches in
1762 another window."
1763 :group 'org-link-follow
1764 :type '(list
1765 (cons (const vm)
1766 (choice
1767 (const vm-visit-folder)
1768 (const vm-visit-folder-other-window)
1769 (const vm-visit-folder-other-frame)))
1770 (cons (const gnus)
1771 (choice
1772 (const gnus)
1773 (const gnus-other-frame)
1774 (const org-gnus-no-new-news)))
1775 (cons (const file)
1776 (choice
1777 (const find-file)
1778 (const find-file-other-window)
1779 (const find-file-other-frame)))
1780 (cons (const wl)
1781 (choice
1782 (const wl)
1783 (const wl-other-frame)))))
1785 (defcustom org-display-internal-link-with-indirect-buffer nil
1786 "Non-nil means use indirect buffer to display infile links.
1787 Activating internal links (from one location in a file to another location
1788 in the same file) normally just jumps to the location. When the link is
1789 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1790 is displayed in
1791 another window. When this option is set, the other window actually displays
1792 an indirect buffer clone of the current buffer, to avoid any visibility
1793 changes to the current buffer."
1794 :group 'org-link-follow
1795 :type 'boolean)
1797 (defcustom org-open-non-existing-files nil
1798 "Non-nil means `org-open-file' will open non-existing files.
1799 When nil, an error will be generated.
1800 This variable applies only to external applications because they
1801 might choke on non-existing files. If the link is to a file that
1802 will be opened in Emacs, the variable is ignored."
1803 :group 'org-link-follow
1804 :type 'boolean)
1806 (defcustom org-open-directory-means-index-dot-org nil
1807 "Non-nil means a link to a directory really means to index.org.
1808 When nil, following a directory link will run dired or open a finder/explorer
1809 window on that directory."
1810 :group 'org-link-follow
1811 :type 'boolean)
1813 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1814 "Function and arguments to call for following mailto links.
1815 This is a list with the first element being a Lisp function, and the
1816 remaining elements being arguments to the function. In string arguments,
1817 %a will be replaced by the address, and %s will be replaced by the subject
1818 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1822 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1823 (const :tag "message-mail" (message-mail "%a" "%s"))
1824 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1826 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1827 "Non-nil means ask for confirmation before executing shell links.
1828 Shell links can be dangerous: just think about a link
1830 [[shell:rm -rf ~/*][Google Search]]
1832 This link would show up in your Org-mode document as \"Google Search\",
1833 but really it would remove your entire home directory.
1834 Therefore we advise against setting this variable to nil.
1835 Just change it to `y-or-n-p' if you want to confirm with a
1836 single keystroke rather than having to type \"yes\"."
1837 :group 'org-link-follow
1838 :type '(choice
1839 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1840 (const :tag "with y-or-n (faster)" y-or-n-p)
1841 (const :tag "no confirmation (dangerous)" nil)))
1842 (put 'org-confirm-shell-link-function
1843 'safe-local-variable
1844 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1846 (defcustom org-confirm-shell-link-not-regexp ""
1847 "A regexp to skip confirmation for shell links."
1848 :group 'org-link-follow
1849 :version "24.1"
1850 :type 'regexp)
1852 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1853 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1854 Elisp links can be dangerous: just think about a link
1856 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1858 This link would show up in your Org-mode document as \"Google Search\",
1859 but really it would remove your entire home directory.
1860 Therefore we advise against setting this variable to nil.
1861 Just change it to `y-or-n-p' if you want to confirm with a
1862 single keystroke rather than having to type \"yes\"."
1863 :group 'org-link-follow
1864 :type '(choice
1865 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1866 (const :tag "with y-or-n (faster)" y-or-n-p)
1867 (const :tag "no confirmation (dangerous)" nil)))
1868 (put 'org-confirm-shell-link-function
1869 'safe-local-variable
1870 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1872 (defcustom org-confirm-elisp-link-not-regexp ""
1873 "A regexp to skip confirmation for Elisp links."
1874 :group 'org-link-follow
1875 :version "24.1"
1876 :type 'regexp)
1878 (defconst org-file-apps-defaults-gnu
1879 '((remote . emacs)
1880 (system . mailcap)
1881 (t . mailcap))
1882 "Default file applications on a UNIX or GNU/Linux system.
1883 See `org-file-apps'.")
1885 (defconst org-file-apps-defaults-macosx
1886 '((remote . emacs)
1887 (t . "open %s")
1888 (system . "open %s")
1889 ("ps.gz" . "gv %s")
1890 ("eps.gz" . "gv %s")
1891 ("dvi" . "xdvi %s")
1892 ("fig" . "xfig %s"))
1893 "Default file applications on a MacOS X system.
1894 The system \"open\" is known as a default, but we use X11 applications
1895 for some files for which the OS does not have a good default.
1896 See `org-file-apps'.")
1898 (defconst org-file-apps-defaults-windowsnt
1899 (list
1900 '(remote . emacs)
1901 (cons t
1902 (list (if (featurep 'xemacs)
1903 'mswindows-shell-execute
1904 'w32-shell-execute)
1905 "open" 'file))
1906 (cons 'system
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file)))
1911 "Default file applications on a Windows NT system.
1912 The system \"open\" is used for most files.
1913 See `org-file-apps'.")
1915 (defcustom org-file-apps
1916 '((auto-mode . emacs)
1917 ("\\.mm\\'" . default)
1918 ("\\.x?html?\\'" . default)
1919 ("\\.pdf\\'" . default))
1920 "External applications for opening `file:path' items in a document.
1921 Org-mode uses system defaults for different file types, but
1922 you can use this variable to set the application for a given file
1923 extension. The entries in this list are cons cells where the car identifies
1924 files and the cdr the corresponding command. Possible values for the
1925 file identifier are
1926 \"string\" A string as a file identifier can be interpreted in different
1927 ways, depending on its contents:
1929 - Alphanumeric characters only:
1930 Match links with this file extension.
1931 Example: (\"pdf\" . \"evince %s\")
1932 to open PDFs with evince.
1934 - Regular expression: Match links where the
1935 filename matches the regexp. If you want to
1936 use groups here, use shy groups.
1938 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1939 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1940 to open *.html and *.xhtml with firefox.
1942 - Regular expression which contains (non-shy) groups:
1943 Match links where the whole link, including \"::\", and
1944 anything after that, matches the regexp.
1945 In a custom command string, %1, %2, etc. are replaced with
1946 the parts of the link that were matched by the groups.
1947 For backwards compatibility, if a command string is given
1948 that does not use any of the group matches, this case is
1949 handled identically to the second one (i.e. match against
1950 file name only).
1951 In a custom lisp form, you can access the group matches with
1952 (match-string n link).
1954 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1955 to open [[file:document.pdf::5]] with evince at page 5.
1957 `directory' Matches a directory
1958 `remote' Matches a remote file, accessible through tramp or efs.
1959 Remote files most likely should be visited through Emacs
1960 because external applications cannot handle such paths.
1961 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1962 so all files Emacs knows how to handle. Using this with
1963 command `emacs' will open most files in Emacs. Beware that this
1964 will also open html files inside Emacs, unless you add
1965 (\"html\" . default) to the list as well.
1966 t Default for files not matched by any of the other options.
1967 `system' The system command to open files, like `open' on Windows
1968 and Mac OS X, and mailcap under GNU/Linux. This is the command
1969 that will be selected if you call `C-c C-o' with a double
1970 \\[universal-argument] \\[universal-argument] prefix.
1972 Possible values for the command are:
1973 `emacs' The file will be visited by the current Emacs process.
1974 `default' Use the default application for this file type, which is the
1975 association for t in the list, most likely in the system-specific
1976 part.
1977 This can be used to overrule an unwanted setting in the
1978 system-specific variable.
1979 `system' Use the system command for opening files, like \"open\".
1980 This command is specified by the entry whose car is `system'.
1981 Most likely, the system-specific version of this variable
1982 does define this command, but you can overrule/replace it
1983 here.
1984 string A command to be executed by a shell; %s will be replaced
1985 by the path to the file.
1986 sexp A Lisp form which will be evaluated. The file path will
1987 be available in the Lisp variable `file'.
1988 For more examples, see the system specific constants
1989 `org-file-apps-defaults-macosx'
1990 `org-file-apps-defaults-windowsnt'
1991 `org-file-apps-defaults-gnu'."
1992 :group 'org-link-follow
1993 :type '(repeat
1994 (cons (choice :value ""
1995 (string :tag "Extension")
1996 (const :tag "System command to open files" system)
1997 (const :tag "Default for unrecognized files" t)
1998 (const :tag "Remote file" remote)
1999 (const :tag "Links to a directory" directory)
2000 (const :tag "Any files that have Emacs modes"
2001 auto-mode))
2002 (choice :value ""
2003 (const :tag "Visit with Emacs" emacs)
2004 (const :tag "Use default" default)
2005 (const :tag "Use the system command" system)
2006 (string :tag "Command")
2007 (sexp :tag "Lisp form")))))
2009 (defcustom org-doi-server-url "http://dx.doi.org/"
2010 "The URL of the DOI server."
2011 :type 'string
2012 :version "24.3"
2013 :group 'org-link-follow)
2015 (defgroup org-refile nil
2016 "Options concerning refiling entries in Org-mode."
2017 :tag "Org Refile"
2018 :group 'org)
2020 (defcustom org-directory "~/org"
2021 "Directory with org files.
2022 This is just a default location to look for Org files. There is no need
2023 at all to put your files into this directory. It is only used in the
2024 following situations:
2026 1. When a capture template specifies a target file that is not an
2027 absolute path. The path will then be interpreted relative to
2028 `org-directory'
2029 2. When a capture note is filed away in an interactive way (when exiting the
2030 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2031 with `org-directory' as the default path."
2032 :group 'org-refile
2033 :group 'org-remember
2034 :group 'org-capture
2035 :type 'directory)
2037 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2038 "Default target for storing notes.
2039 Used as a fall back file for org-remember.el and org-capture.el, for
2040 templates that do not specify a target file."
2041 :group 'org-refile
2042 :group 'org-remember
2043 :group 'org-capture
2044 :type '(choice
2045 (const :tag "Default from remember-data-file" nil)
2046 file))
2048 (defcustom org-goto-interface 'outline
2049 "The default interface to be used for `org-goto'.
2050 Allowed values are:
2051 outline The interface shows an outline of the relevant file
2052 and the correct heading is found by moving through
2053 the outline or by searching with incremental search.
2054 outline-path-completion Headlines in the current buffer are offered via
2055 completion. This is the interface also used by
2056 the refile command."
2057 :group 'org-refile
2058 :type '(choice
2059 (const :tag "Outline" outline)
2060 (const :tag "Outline-path-completion" outline-path-completion)))
2062 (defcustom org-goto-max-level 5
2063 "Maximum target level when running `org-goto' with refile interface."
2064 :group 'org-refile
2065 :type 'integer)
2067 (defcustom org-reverse-note-order nil
2068 "Non-nil means store new notes at the beginning of a file or entry.
2069 When nil, new notes will be filed to the end of a file or entry.
2070 This can also be a list with cons cells of regular expressions that
2071 are matched against file names, and values."
2072 :group 'org-remember
2073 :group 'org-capture
2074 :group 'org-refile
2075 :type '(choice
2076 (const :tag "Reverse always" t)
2077 (const :tag "Reverse never" nil)
2078 (repeat :tag "By file name regexp"
2079 (cons regexp boolean))))
2081 (defcustom org-log-refile nil
2082 "Information to record when a task is refiled.
2084 Possible values are:
2086 nil Don't add anything
2087 time Add a time stamp to the task
2088 note Prompt for a note and add it with template `org-log-note-headings'
2090 This option can also be set with on a per-file-basis with
2092 #+STARTUP: nologrefile
2093 #+STARTUP: logrefile
2094 #+STARTUP: lognoterefile
2096 You can have local logging settings for a subtree by setting the LOGGING
2097 property to one or more of these keywords.
2099 When bulk-refiling from the agenda, the value `note' is forbidden and
2100 will temporarily be changed to `time'."
2101 :group 'org-refile
2102 :group 'org-progress
2103 :version "24.1"
2104 :type '(choice
2105 (const :tag "No logging" nil)
2106 (const :tag "Record timestamp" time)
2107 (const :tag "Record timestamp with note." note)))
2109 (defcustom org-refile-targets nil
2110 "Targets for refiling entries with \\[org-refile].
2111 This is a list of cons cells. Each cell contains:
2112 - a specification of the files to be considered, either a list of files,
2113 or a symbol whose function or variable value will be used to retrieve
2114 a file name or a list of file names. If you use `org-agenda-files' for
2115 that, all agenda files will be scanned for targets. Nil means consider
2116 headings in the current buffer.
2117 - A specification of how to find candidate refile targets. This may be
2118 any of:
2119 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2120 This tag has to be present in all target headlines, inheritance will
2121 not be considered.
2122 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2123 todo keyword.
2124 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2125 headlines that are refiling targets.
2126 - a cons cell (:level . N). Any headline of level N is considered a target.
2127 Note that, when `org-odd-levels-only' is set, level corresponds to
2128 order in hierarchy, not to the number of stars.
2129 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2130 Note that, when `org-odd-levels-only' is set, level corresponds to
2131 order in hierarchy, not to the number of stars.
2133 Each element of this list generates a set of possible targets.
2134 The union of these sets is presented (with completion) to
2135 the user by `org-refile'.
2137 You can set the variable `org-refile-target-verify-function' to a function
2138 to verify each headline found by the simple criteria above.
2140 When this variable is nil, all top-level headlines in the current buffer
2141 are used, equivalent to the value `((nil . (:level . 1))'."
2142 :group 'org-refile
2143 :type '(repeat
2144 (cons
2145 (choice :value org-agenda-files
2146 (const :tag "All agenda files" org-agenda-files)
2147 (const :tag "Current buffer" nil)
2148 (function) (variable) (file))
2149 (choice :tag "Identify target headline by"
2150 (cons :tag "Specific tag" (const :value :tag) (string))
2151 (cons :tag "TODO keyword" (const :value :todo) (string))
2152 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2153 (cons :tag "Level number" (const :value :level) (integer))
2154 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2156 (defcustom org-refile-target-verify-function nil
2157 "Function to verify if the headline at point should be a refile target.
2158 The function will be called without arguments, with point at the
2159 beginning of the headline. It should return t and leave point
2160 where it is if the headline is a valid target for refiling.
2162 If the target should not be selected, the function must return nil.
2163 In addition to this, it may move point to a place from where the search
2164 should be continued. For example, the function may decide that the entire
2165 subtree of the current entry should be excluded and move point to the end
2166 of the subtree."
2167 :group 'org-refile
2168 :type 'function)
2170 (defcustom org-refile-use-cache nil
2171 "Non-nil means cache refile targets to speed up the process.
2172 The cache for a particular file will be updated automatically when
2173 the buffer has been killed, or when any of the marker used for flagging
2174 refile targets no longer points at a live buffer.
2175 If you have added new entries to a buffer that might themselves be targets,
2176 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2177 find that easier, `C-u C-u C-u C-c C-w'."
2178 :group 'org-refile
2179 :version "24.1"
2180 :type 'boolean)
2182 (defcustom org-refile-use-outline-path nil
2183 "Non-nil means provide refile targets as paths.
2184 So a level 3 headline will be available as level1/level2/level3.
2186 When the value is `file', also include the file name (without directory)
2187 into the path. In this case, you can also stop the completion after
2188 the file name, to get entries inserted as top level in the file.
2190 When `full-file-path', include the full file path."
2191 :group 'org-refile
2192 :type '(choice
2193 (const :tag "Not" nil)
2194 (const :tag "Yes" t)
2195 (const :tag "Start with file name" file)
2196 (const :tag "Start with full file path" full-file-path)))
2198 (defcustom org-outline-path-complete-in-steps t
2199 "Non-nil means complete the outline path in hierarchical steps.
2200 When Org-mode uses the refile interface to select an outline path
2201 \(see variable `org-refile-use-outline-path'), the completion of
2202 the path can be done is a single go, or if can be done in steps down
2203 the headline hierarchy. Going in steps is probably the best if you
2204 do not use a special completion package like `ido' or `icicles'.
2205 However, when using these packages, going in one step can be very
2206 fast, while still showing the whole path to the entry."
2207 :group 'org-refile
2208 :type 'boolean)
2210 (defcustom org-refile-allow-creating-parent-nodes nil
2211 "Non-nil means allow to create new nodes as refile targets.
2212 New nodes are then created by adding \"/new node name\" to the completion
2213 of an existing node. When the value of this variable is `confirm',
2214 new node creation must be confirmed by the user (recommended)
2215 When nil, the completion must match an existing entry.
2217 Note that, if the new heading is not seen by the criteria
2218 listed in `org-refile-targets', multiple instances of the same
2219 heading would be created by trying again to file under the new
2220 heading."
2221 :group 'org-refile
2222 :type '(choice
2223 (const :tag "Never" nil)
2224 (const :tag "Always" t)
2225 (const :tag "Prompt for confirmation" confirm)))
2227 (defcustom org-refile-active-region-within-subtree nil
2228 "Non-nil means also refile active region within a subtree.
2230 By default `org-refile' doesn't allow refiling regions if they
2231 don't contain a set of subtrees, but it might be convenient to
2232 do so sometimes: in that case, the first line of the region is
2233 converted to a headline before refiling."
2234 :group 'org-refile
2235 :version "24.1"
2236 :type 'boolean)
2238 (defgroup org-todo nil
2239 "Options concerning TODO items in Org-mode."
2240 :tag "Org TODO"
2241 :group 'org)
2243 (defgroup org-progress nil
2244 "Options concerning Progress logging in Org-mode."
2245 :tag "Org Progress"
2246 :group 'org-time)
2248 (defvar org-todo-interpretation-widgets
2249 '((:tag "Sequence (cycling hits every state)" sequence)
2250 (:tag "Type (cycling directly to DONE)" type))
2251 "The available interpretation symbols for customizing `org-todo-keywords'.
2252 Interested libraries should add to this list.")
2254 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2255 "List of TODO entry keyword sequences and their interpretation.
2256 \\<org-mode-map>This is a list of sequences.
2258 Each sequence starts with a symbol, either `sequence' or `type',
2259 indicating if the keywords should be interpreted as a sequence of
2260 action steps, or as different types of TODO items. The first
2261 keywords are states requiring action - these states will select a headline
2262 for inclusion into the global TODO list Org-mode produces. If one of
2263 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2264 signify that no further action is necessary. If \"|\" is not found,
2265 the last keyword is treated as the only DONE state of the sequence.
2267 The command \\[org-todo] cycles an entry through these states, and one
2268 additional state where no keyword is present. For details about this
2269 cycling, see the manual.
2271 TODO keywords and interpretation can also be set on a per-file basis with
2272 the special #+SEQ_TODO and #+TYP_TODO lines.
2274 Each keyword can optionally specify a character for fast state selection
2275 \(in combination with the variable `org-use-fast-todo-selection')
2276 and specifiers for state change logging, using the same syntax that
2277 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2278 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2279 indicates to record a time stamp each time this state is selected.
2281 Each keyword may also specify if a timestamp or a note should be
2282 recorded when entering or leaving the state, by adding additional
2283 characters in the parenthesis after the keyword. This looks like this:
2284 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2285 record only the time of the state change. With X and Y being either
2286 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2287 Y when leaving the state if and only if the *target* state does not
2288 define X. You may omit any of the fast-selection key or X or /Y,
2289 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2291 For backward compatibility, this variable may also be just a list
2292 of keywords. In this case the interpretation (sequence or type) will be
2293 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2294 :group 'org-todo
2295 :group 'org-keywords
2296 :type '(choice
2297 (repeat :tag "Old syntax, just keywords"
2298 (string :tag "Keyword"))
2299 (repeat :tag "New syntax"
2300 (cons
2301 (choice
2302 :tag "Interpretation"
2303 ;;Quick and dirty way to see
2304 ;;`org-todo-interpretations'. This takes the
2305 ;;place of item arguments
2306 :convert-widget
2307 (lambda (widget)
2308 (widget-put widget
2309 :args (mapcar
2310 #'(lambda (x)
2311 (widget-convert
2312 (cons 'const x)))
2313 org-todo-interpretation-widgets))
2314 widget))
2315 (repeat
2316 (string :tag "Keyword"))))))
2318 (defvar org-todo-keywords-1 nil
2319 "All TODO and DONE keywords active in a buffer.")
2320 (make-variable-buffer-local 'org-todo-keywords-1)
2321 (defvar org-todo-keywords-for-agenda nil)
2322 (defvar org-done-keywords-for-agenda nil)
2323 (defvar org-drawers-for-agenda nil)
2324 (defvar org-todo-keyword-alist-for-agenda nil)
2325 (defvar org-tag-alist-for-agenda nil
2326 "Alist of all tags from all agenda files.")
2327 (defvar org-tag-groups-alist-for-agenda nil
2328 "Alist of all groups tags from all current agenda files.")
2329 (defvar org-tag-groups-alist nil)
2330 (make-variable-buffer-local 'org-tag-groups-alist)
2331 (defvar org-agenda-contributing-files nil)
2332 (defvar org-not-done-keywords nil)
2333 (make-variable-buffer-local 'org-not-done-keywords)
2334 (defvar org-done-keywords nil)
2335 (make-variable-buffer-local 'org-done-keywords)
2336 (defvar org-todo-heads nil)
2337 (make-variable-buffer-local 'org-todo-heads)
2338 (defvar org-todo-sets nil)
2339 (make-variable-buffer-local 'org-todo-sets)
2340 (defvar org-todo-log-states nil)
2341 (make-variable-buffer-local 'org-todo-log-states)
2342 (defvar org-todo-kwd-alist nil)
2343 (make-variable-buffer-local 'org-todo-kwd-alist)
2344 (defvar org-todo-key-alist nil)
2345 (make-variable-buffer-local 'org-todo-key-alist)
2346 (defvar org-todo-key-trigger nil)
2347 (make-variable-buffer-local 'org-todo-key-trigger)
2349 (defcustom org-todo-interpretation 'sequence
2350 "Controls how TODO keywords are interpreted.
2351 This variable is in principle obsolete and is only used for
2352 backward compatibility, if the interpretation of todo keywords is
2353 not given already in `org-todo-keywords'. See that variable for
2354 more information."
2355 :group 'org-todo
2356 :group 'org-keywords
2357 :type '(choice (const sequence)
2358 (const type)))
2360 (defcustom org-use-fast-todo-selection t
2361 "Non-nil means use the fast todo selection scheme with C-c C-t.
2362 This variable describes if and under what circumstances the cycling
2363 mechanism for TODO keywords will be replaced by a single-key, direct
2364 selection scheme.
2366 When nil, fast selection is never used.
2368 When the symbol `prefix', it will be used when `org-todo' is called
2369 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2370 `C-u t' in an agenda buffer.
2372 When t, fast selection is used by default. In this case, the prefix
2373 argument forces cycling instead.
2375 In all cases, the special interface is only used if access keys have
2376 actually been assigned by the user, i.e. if keywords in the configuration
2377 are followed by a letter in parenthesis, like TODO(t)."
2378 :group 'org-todo
2379 :type '(choice
2380 (const :tag "Never" nil)
2381 (const :tag "By default" t)
2382 (const :tag "Only with C-u C-c C-t" prefix)))
2384 (defcustom org-provide-todo-statistics t
2385 "Non-nil means update todo statistics after insert and toggle.
2386 ALL-HEADLINES means update todo statistics by including headlines
2387 with no TODO keyword as well, counting them as not done.
2388 A list of TODO keywords means the same, but skip keywords that are
2389 not in this list.
2391 When this is set, todo statistics is updated in the parent of the
2392 current entry each time a todo state is changed."
2393 :group 'org-todo
2394 :type '(choice
2395 (const :tag "Yes, only for TODO entries" t)
2396 (const :tag "Yes, including all entries" 'all-headlines)
2397 (repeat :tag "Yes, for TODOs in this list"
2398 (string :tag "TODO keyword"))
2399 (other :tag "No TODO statistics" nil)))
2401 (defcustom org-hierarchical-todo-statistics t
2402 "Non-nil means TODO statistics covers just direct children.
2403 When nil, all entries in the subtree are considered.
2404 This has only an effect if `org-provide-todo-statistics' is set.
2405 To set this to nil for only a single subtree, use a COOKIE_DATA
2406 property and include the word \"recursive\" into the value."
2407 :group 'org-todo
2408 :type 'boolean)
2410 (defcustom org-after-todo-state-change-hook nil
2411 "Hook which is run after the state of a TODO item was changed.
2412 The new state (a string with a TODO keyword, or nil) is available in the
2413 Lisp variable `org-state'."
2414 :group 'org-todo
2415 :type 'hook)
2417 (defvar org-blocker-hook nil
2418 "Hook for functions that are allowed to block a state change.
2420 Functions in this hook should not modify the buffer.
2421 Each function gets as its single argument a property list,
2422 see `org-trigger-hook' for more information about this list.
2424 If any of the functions in this hook returns nil, the state change
2425 is blocked.")
2427 (defvar org-trigger-hook nil
2428 "Hook for functions that are triggered by a state change.
2430 Each function gets as its single argument a property list with at
2431 least the following elements:
2433 (:type type-of-change :position pos-at-entry-start
2434 :from old-state :to new-state)
2436 Depending on the type, more properties may be present.
2438 This mechanism is currently implemented for:
2440 TODO state changes
2441 ------------------
2442 :type todo-state-change
2443 :from previous state (keyword as a string), or nil, or a symbol
2444 'todo' or 'done', to indicate the general type of state.
2445 :to new state, like in :from")
2447 (defcustom org-enforce-todo-dependencies nil
2448 "Non-nil means undone TODO entries will block switching the parent to DONE.
2449 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2450 be blocked if any prior sibling is not yet done.
2451 Finally, if the parent is blocked because of ordered siblings of its own,
2452 the child will also be blocked."
2453 :set (lambda (var val)
2454 (set var val)
2455 (if val
2456 (add-hook 'org-blocker-hook
2457 'org-block-todo-from-children-or-siblings-or-parent)
2458 (remove-hook 'org-blocker-hook
2459 'org-block-todo-from-children-or-siblings-or-parent)))
2460 :group 'org-todo
2461 :type 'boolean)
2463 (defcustom org-enforce-todo-checkbox-dependencies nil
2464 "Non-nil means unchecked boxes will block switching the parent to DONE.
2465 When this is nil, checkboxes have no influence on switching TODO states.
2466 When non-nil, you first need to check off all check boxes before the TODO
2467 entry can be switched to DONE.
2468 This variable needs to be set before org.el is loaded, and you need to
2469 restart Emacs after a change to make the change effective. The only way
2470 to change is while Emacs is running is through the customize interface."
2471 :set (lambda (var val)
2472 (set var val)
2473 (if val
2474 (add-hook 'org-blocker-hook
2475 'org-block-todo-from-checkboxes)
2476 (remove-hook 'org-blocker-hook
2477 'org-block-todo-from-checkboxes)))
2478 :group 'org-todo
2479 :type 'boolean)
2481 (defcustom org-treat-insert-todo-heading-as-state-change nil
2482 "Non-nil means inserting a TODO heading is treated as state change.
2483 So when the command \\[org-insert-todo-heading] is used, state change
2484 logging will apply if appropriate. When nil, the new TODO item will
2485 be inserted directly, and no logging will take place."
2486 :group 'org-todo
2487 :type 'boolean)
2489 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2490 "Non-nil means switching TODO states with S-cursor counts as state change.
2491 This is the default behavior. However, setting this to nil allows a
2492 convenient way to select a TODO state and bypass any logging associated
2493 with that."
2494 :group 'org-todo
2495 :type 'boolean)
2497 (defcustom org-todo-state-tags-triggers nil
2498 "Tag changes that should be triggered by TODO state changes.
2499 This is a list. Each entry is
2501 (state-change (tag . flag) .......)
2503 State-change can be a string with a state, and empty string to indicate the
2504 state that has no TODO keyword, or it can be one of the symbols `todo'
2505 or `done', meaning any not-done or done state, respectively."
2506 :group 'org-todo
2507 :group 'org-tags
2508 :type '(repeat
2509 (cons (choice :tag "When changing to"
2510 (const :tag "Not-done state" todo)
2511 (const :tag "Done state" done)
2512 (string :tag "State"))
2513 (repeat
2514 (cons :tag "Tag action"
2515 (string :tag "Tag")
2516 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2518 (defcustom org-log-done nil
2519 "Information to record when a task moves to the DONE state.
2521 Possible values are:
2523 nil Don't add anything, just change the keyword
2524 time Add a time stamp to the task
2525 note Prompt for a note and add it with template `org-log-note-headings'
2527 This option can also be set with on a per-file-basis with
2529 #+STARTUP: nologdone
2530 #+STARTUP: logdone
2531 #+STARTUP: lognotedone
2533 You can have local logging settings for a subtree by setting the LOGGING
2534 property to one or more of these keywords."
2535 :group 'org-todo
2536 :group 'org-progress
2537 :type '(choice
2538 (const :tag "No logging" nil)
2539 (const :tag "Record CLOSED timestamp" time)
2540 (const :tag "Record CLOSED timestamp with note." note)))
2542 ;; Normalize old uses of org-log-done.
2543 (cond
2544 ((eq org-log-done t) (setq org-log-done 'time))
2545 ((and (listp org-log-done) (memq 'done org-log-done))
2546 (setq org-log-done 'note)))
2548 (defcustom org-log-reschedule nil
2549 "Information to record when the scheduling date of a tasks is modified.
2551 Possible values are:
2553 nil Don't add anything, just change the date
2554 time Add a time stamp to the task
2555 note Prompt for a note and add it with template `org-log-note-headings'
2557 This option can also be set with on a per-file-basis with
2559 #+STARTUP: nologreschedule
2560 #+STARTUP: logreschedule
2561 #+STARTUP: lognotereschedule"
2562 :group 'org-todo
2563 :group 'org-progress
2564 :type '(choice
2565 (const :tag "No logging" nil)
2566 (const :tag "Record timestamp" time)
2567 (const :tag "Record timestamp with note." note)))
2569 (defcustom org-log-redeadline nil
2570 "Information to record when the deadline date of a tasks is modified.
2572 Possible values are:
2574 nil Don't add anything, just change the date
2575 time Add a time stamp to the task
2576 note Prompt for a note and add it with template `org-log-note-headings'
2578 This option can also be set with on a per-file-basis with
2580 #+STARTUP: nologredeadline
2581 #+STARTUP: logredeadline
2582 #+STARTUP: lognoteredeadline
2584 You can have local logging settings for a subtree by setting the LOGGING
2585 property to one or more of these keywords."
2586 :group 'org-todo
2587 :group 'org-progress
2588 :type '(choice
2589 (const :tag "No logging" nil)
2590 (const :tag "Record timestamp" time)
2591 (const :tag "Record timestamp with note." note)))
2593 (defcustom org-log-note-clock-out nil
2594 "Non-nil means record a note when clocking out of an item.
2595 This can also be configured on a per-file basis by adding one of
2596 the following lines anywhere in the buffer:
2598 #+STARTUP: lognoteclock-out
2599 #+STARTUP: nolognoteclock-out"
2600 :group 'org-todo
2601 :group 'org-progress
2602 :type 'boolean)
2604 (defcustom org-log-done-with-time t
2605 "Non-nil means the CLOSED time stamp will contain date and time.
2606 When nil, only the date will be recorded."
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-note-headings
2611 '((done . "CLOSING NOTE %t")
2612 (state . "State %-12s from %-12S %t")
2613 (note . "Note taken on %t")
2614 (reschedule . "Rescheduled from %S on %t")
2615 (delschedule . "Not scheduled, was %S on %t")
2616 (redeadline . "New deadline from %S on %t")
2617 (deldeadline . "Removed deadline, was %S on %t")
2618 (refile . "Refiled on %t")
2619 (clock-out . ""))
2620 "Headings for notes added to entries.
2621 The value is an alist, with the car being a symbol indicating the note
2622 context, and the cdr is the heading to be used. The heading may also be the
2623 empty string.
2624 %t in the heading will be replaced by a time stamp.
2625 %T will be an active time stamp instead the default inactive one
2626 %d will be replaced by a short-format time stamp.
2627 %D will be replaced by an active short-format time stamp.
2628 %s will be replaced by the new TODO state, in double quotes.
2629 %S will be replaced by the old TODO state, in double quotes.
2630 %u will be replaced by the user name.
2631 %U will be replaced by the full user name.
2633 In fact, it is not a good idea to change the `state' entry, because
2634 agenda log mode depends on the format of these entries."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(list :greedy t
2638 (cons (const :tag "Heading when closing an item" done) string)
2639 (cons (const :tag
2640 "Heading when changing todo state (todo sequence only)"
2641 state) string)
2642 (cons (const :tag "Heading when just taking a note" note) string)
2643 (cons (const :tag "Heading when clocking out" clock-out) string)
2644 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2645 (cons (const :tag "Heading when rescheduling" reschedule) string)
2646 (cons (const :tag "Heading when changing deadline" redeadline) string)
2647 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2648 (cons (const :tag "Heading when refiling" refile) string)))
2650 (unless (assq 'note org-log-note-headings)
2651 (push '(note . "%t") org-log-note-headings))
2653 (defcustom org-log-into-drawer nil
2654 "Non-nil means insert state change notes and time stamps into a drawer.
2655 When nil, state changes notes will be inserted after the headline and
2656 any scheduling and clock lines, but not inside a drawer.
2658 The value of this variable should be the name of the drawer to use.
2659 LOGBOOK is proposed as the default drawer for this purpose, you can
2660 also set this to a string to define the drawer of your choice.
2662 A value of t is also allowed, representing \"LOGBOOK\".
2664 A value of t or nil can also be set with on a per-file-basis with
2666 #+STARTUP: logdrawer
2667 #+STARTUP: nologdrawer
2669 If this variable is set, `org-log-state-notes-insert-after-drawers'
2670 will be ignored.
2672 You can set the property LOG_INTO_DRAWER to overrule this setting for
2673 a subtree."
2674 :group 'org-todo
2675 :group 'org-progress
2676 :type '(choice
2677 (const :tag "Not into a drawer" nil)
2678 (const :tag "LOGBOOK" t)
2679 (string :tag "Other")))
2681 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2683 (defun org-log-into-drawer ()
2684 "Return the value of `org-log-into-drawer', but let properties overrule.
2685 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2686 used instead of the default value."
2687 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2688 (cond
2689 ((not p) org-log-into-drawer)
2690 ((equal p "nil") nil)
2691 ((equal p "t") "LOGBOOK")
2692 (t p))))
2694 (defcustom org-log-state-notes-insert-after-drawers nil
2695 "Non-nil means insert state change notes after any drawers in entry.
2696 Only the drawers that *immediately* follow the headline and the
2697 deadline/scheduled line are skipped.
2698 When nil, insert notes right after the heading and perhaps the line
2699 with deadline/scheduling if present.
2701 This variable will have no effect if `org-log-into-drawer' is
2702 set."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type 'boolean)
2707 (defcustom org-log-states-order-reversed t
2708 "Non-nil means the latest state note will be directly after heading.
2709 When nil, the state change notes will be ordered according to time.
2711 This option can also be set with on a per-file-basis with
2713 #+STARTUP: logstatesreversed
2714 #+STARTUP: nologstatesreversed"
2715 :group 'org-todo
2716 :group 'org-progress
2717 :type 'boolean)
2719 (defcustom org-todo-repeat-to-state nil
2720 "The TODO state to which a repeater should return the repeating task.
2721 By default this is the first task in a TODO sequence, or the previous state
2722 in a TODO_TYP set. But you can specify another task here.
2723 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2724 :group 'org-todo
2725 :version "24.1"
2726 :type '(choice (const :tag "Head of sequence" nil)
2727 (string :tag "Specific state")))
2729 (defcustom org-log-repeat 'time
2730 "Non-nil means record moving through the DONE state when triggering repeat.
2731 An auto-repeating task is immediately switched back to TODO when
2732 marked DONE. If you are not logging state changes (by adding \"@\"
2733 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2734 record a closing note, there will be no record of the task moving
2735 through DONE. This variable forces taking a note anyway.
2737 nil Don't force a record
2738 time Record a time stamp
2739 note Prompt for a note and add it with template `org-log-note-headings'
2741 This option can also be set with on a per-file-basis with
2743 #+STARTUP: nologrepeat
2744 #+STARTUP: logrepeat
2745 #+STARTUP: lognoterepeat
2747 You can have local logging settings for a subtree by setting the LOGGING
2748 property to one or more of these keywords."
2749 :group 'org-todo
2750 :group 'org-progress
2751 :type '(choice
2752 (const :tag "Don't force a record" nil)
2753 (const :tag "Force recording the DONE state" time)
2754 (const :tag "Force recording a note with the DONE state" note)))
2757 (defgroup org-priorities nil
2758 "Priorities in Org-mode."
2759 :tag "Org Priorities"
2760 :group 'org-todo)
2762 (defcustom org-enable-priority-commands t
2763 "Non-nil means priority commands are active.
2764 When nil, these commands will be disabled, so that you never accidentally
2765 set a priority."
2766 :group 'org-priorities
2767 :type 'boolean)
2769 (defcustom org-highest-priority ?A
2770 "The highest priority of TODO items. A character like ?A, ?B etc.
2771 Must have a smaller ASCII number than `org-lowest-priority'."
2772 :group 'org-priorities
2773 :type 'character)
2775 (defcustom org-lowest-priority ?C
2776 "The lowest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a larger ASCII number than `org-highest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-default-priority ?B
2782 "The default priority of TODO items.
2783 This is the priority an item gets if no explicit priority is given.
2784 When starting to cycle on an empty priority the first step in the cycle
2785 depends on `org-priority-start-cycle-with-default'. The resulting first
2786 step priority must not exceed the range from `org-highest-priority' to
2787 `org-lowest-priority' which means that `org-default-priority' has to be
2788 in this range exclusive or inclusive the range boundaries. Else the
2789 first step refuses to set the default and the second will fall back
2790 to (depending on the command used) the highest or lowest priority."
2791 :group 'org-priorities
2792 :type 'character)
2794 (defcustom org-priority-start-cycle-with-default t
2795 "Non-nil means start with default priority when starting to cycle.
2796 When this is nil, the first step in the cycle will be (depending on the
2797 command used) one higher or lower than the default priority.
2798 See also `org-default-priority'."
2799 :group 'org-priorities
2800 :type 'boolean)
2802 (defcustom org-get-priority-function nil
2803 "Function to extract the priority from a string.
2804 The string is normally the headline. If this is nil Org computes the
2805 priority from the priority cookie like [#A] in the headline. It returns
2806 an integer, increasing by 1000 for each priority level.
2807 The user can set a different function here, which should take a string
2808 as an argument and return the numeric priority."
2809 :group 'org-priorities
2810 :version "24.1"
2811 :type 'function)
2813 (defgroup org-time nil
2814 "Options concerning time stamps and deadlines in Org-mode."
2815 :tag "Org Time"
2816 :group 'org)
2818 (defcustom org-insert-labeled-timestamps-at-point nil
2819 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2820 When nil, these labeled time stamps are forces into the second line of an
2821 entry, just after the headline. When scheduling from the global TODO list,
2822 the time stamp will always be forced into the second line."
2823 :group 'org-time
2824 :type 'boolean)
2826 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2827 "Formats for `format-time-string' which are used for time stamps.
2828 It is not recommended to change this constant.")
2830 (defcustom org-time-stamp-rounding-minutes '(0 5)
2831 "Number of minutes to round time stamps to.
2832 These are two values, the first applies when first creating a time stamp.
2833 The second applies when changing it with the commands `S-up' and `S-down'.
2834 When changing the time stamp, this means that it will change in steps
2835 of N minutes, as given by the second value.
2837 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2838 numbers should be factors of 60, so for example 5, 10, 15.
2840 When this is larger than 1, you can still force an exact time stamp by using
2841 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2842 and by using a prefix arg to `S-up/down' to specify the exact number
2843 of minutes to shift."
2844 :group 'org-time
2845 :get #'(lambda (var) ; Make sure both elements are there
2846 (if (integerp (default-value var))
2847 (list (default-value var) 5)
2848 (default-value var)))
2849 :type '(list
2850 (integer :tag "when inserting times")
2851 (integer :tag "when modifying times")))
2853 ;; Normalize old customizations of this variable.
2854 (when (integerp org-time-stamp-rounding-minutes)
2855 (setq org-time-stamp-rounding-minutes
2856 (list org-time-stamp-rounding-minutes
2857 org-time-stamp-rounding-minutes)))
2859 (defcustom org-display-custom-times nil
2860 "Non-nil means overlay custom formats over all time stamps.
2861 The formats are defined through the variable `org-time-stamp-custom-formats'.
2862 To turn this on on a per-file basis, insert anywhere in the file:
2863 #+STARTUP: customtime"
2864 :group 'org-time
2865 :set 'set-default
2866 :type 'sexp)
2867 (make-variable-buffer-local 'org-display-custom-times)
2869 (defcustom org-time-stamp-custom-formats
2870 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2871 "Custom formats for time stamps. See `format-time-string' for the syntax.
2872 These are overlaid over the default ISO format if the variable
2873 `org-display-custom-times' is set. Time like %H:%M should be at the
2874 end of the second format. The custom formats are also honored by export
2875 commands, if custom time display is turned on at the time of export."
2876 :group 'org-time
2877 :type 'sexp)
2879 (defun org-time-stamp-format (&optional long inactive)
2880 "Get the right format for a time string."
2881 (let ((f (if long (cdr org-time-stamp-formats)
2882 (car org-time-stamp-formats))))
2883 (if inactive
2884 (concat "[" (substring f 1 -1) "]")
2885 f)))
2887 (defcustom org-time-clocksum-format
2888 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2889 "The format string used when creating CLOCKSUM lines.
2890 This is also used when Org mode generates a time duration.
2892 The value can be a single format string containing two
2893 %-sequences, which will be filled with the number of hours and
2894 minutes in that order.
2896 Alternatively, the value can be a plist associating any of the
2897 keys :years, :months, :weeks, :days, :hours or :minutes with
2898 format strings. The time duration is formatted using only the
2899 time components that are needed and concatenating the results.
2900 If a time unit in absent, it falls back to the next smallest
2901 unit.
2903 The keys :require-years, :require-months, :require-days,
2904 :require-weeks, :require-hours, :require-minutes are also
2905 meaningful. A non-nil value for these keys indicates that the
2906 corresponding time component should always be included, even if
2907 its value is 0.
2910 For example,
2912 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2913 :require-minutes t)
2915 means durations longer than a day will be expressed in days,
2916 hours and minutes, and durations less than a day will always be
2917 expressed in hours and minutes (even for durations less than an
2918 hour).
2920 The value
2922 \(:days \"%dd\" :minutes \"%dm\")
2924 means durations longer than a day will be expressed in days and
2925 minutes, and durations less than a day will be expressed entirely
2926 in minutes (even for durations longer than an hour)."
2927 :group 'org-time
2928 :group 'org-clock
2929 :version "24.4"
2930 :package-version '(Org . "8.0")
2931 :type '(choice (string :tag "Format string")
2932 (set :tag "Plist"
2933 (group :inline t (const :tag "Years" :years)
2934 (string :tag "Format string"))
2935 (group :inline t
2936 (const :tag "Always show years" :require-years)
2937 (const t))
2938 (group :inline t (const :tag "Months" :months)
2939 (string :tag "Format string"))
2940 (group :inline t
2941 (const :tag "Always show months" :require-months)
2942 (const t))
2943 (group :inline t (const :tag "Weeks" :weeks)
2944 (string :tag "Format string"))
2945 (group :inline t
2946 (const :tag "Always show weeks" :require-weeks)
2947 (const t))
2948 (group :inline t (const :tag "Days" :days)
2949 (string :tag "Format string"))
2950 (group :inline t
2951 (const :tag "Always show days" :require-days)
2952 (const t))
2953 (group :inline t (const :tag "Hours" :hours)
2954 (string :tag "Format string"))
2955 (group :inline t
2956 (const :tag "Always show hours" :require-hours)
2957 (const t))
2958 (group :inline t (const :tag "Minutes" :minutes)
2959 (string :tag "Format string"))
2960 (group :inline t
2961 (const :tag "Always show minutes" :require-minutes)
2962 (const t)))))
2964 (defcustom org-time-clocksum-use-fractional nil
2965 "When non-nil, \\[org-clock-display] uses fractional times.
2966 See `org-time-clocksum-format' for more on time clock formats."
2967 :group 'org-time
2968 :group 'org-clock
2969 :version "24.3"
2970 :type 'boolean)
2972 (defcustom org-time-clocksum-use-effort-durations nil
2973 "When non-nil, \\[org-clock-display] uses effort durations.
2974 E.g. by default, one day is considered to be a 8 hours effort,
2975 so a task that has been clocked for 16 hours will be displayed
2976 as during 2 days in the clock display or in the clocktable.
2978 See `org-effort-durations' on how to set effort durations
2979 and `org-time-clocksum-format' for more on time clock formats."
2980 :group 'org-time
2981 :group 'org-clock
2982 :version "24.4"
2983 :package-version '(Org . "8.0")
2984 :type 'boolean)
2986 (defcustom org-time-clocksum-fractional-format "%.2f"
2987 "The format string used when creating CLOCKSUM lines,
2988 or when Org mode generates a time duration, if
2989 `org-time-clocksum-use-fractional' is enabled.
2991 The value can be a single format string containing one
2992 %-sequence, which will be filled with the number of hours as
2993 a float.
2995 Alternatively, the value can be a plist associating any of the
2996 keys :years, :months, :weeks, :days, :hours or :minutes with
2997 a format string. The time duration is formatted using the
2998 largest time unit which gives a non-zero integer part. If all
2999 specified formats have zero integer part, the smallest time unit
3000 is used."
3001 :group 'org-time
3002 :type '(choice (string :tag "Format string")
3003 (set (group :inline t (const :tag "Years" :years)
3004 (string :tag "Format string"))
3005 (group :inline t (const :tag "Months" :months)
3006 (string :tag "Format string"))
3007 (group :inline t (const :tag "Weeks" :weeks)
3008 (string :tag "Format string"))
3009 (group :inline t (const :tag "Days" :days)
3010 (string :tag "Format string"))
3011 (group :inline t (const :tag "Hours" :hours)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Minutes" :minutes)
3014 (string :tag "Format string")))))
3016 (defcustom org-deadline-warning-days 14
3017 "Number of days before expiration during which a deadline becomes active.
3018 This variable governs the display in sparse trees and in the agenda.
3019 When 0 or negative, it means use this number (the absolute value of it)
3020 even if a deadline has a different individual lead time specified.
3022 Custom commands can set this variable in the options section."
3023 :group 'org-time
3024 :group 'org-agenda-daily/weekly
3025 :type 'integer)
3027 (defcustom org-scheduled-delay-days 0
3028 "Number of days before a scheduled item becomes active.
3029 This variable governs the display in sparse trees and in the agenda.
3030 The default value (i.e. 0) means: don't delay scheduled item.
3031 When negative, it means use this number (the absolute value of it)
3032 even if a scheduled item has a different individual delay time
3033 specified.
3035 Custom commands can set this variable in the options section."
3036 :group 'org-time
3037 :group 'org-agenda-daily/weekly
3038 :version "24.4"
3039 :package-version '(Org . "8.0")
3040 :type 'integer)
3042 (defcustom org-read-date-prefer-future t
3043 "Non-nil means assume future for incomplete date input from user.
3044 This affects the following situations:
3045 1. The user gives a month but not a year.
3046 For example, if it is April and you enter \"feb 2\", this will be read
3047 as Feb 2, *next* year. \"May 5\", however, will be this year.
3048 2. The user gives a day, but no month.
3049 For example, if today is the 15th, and you enter \"3\", Org-mode will
3050 read this as the third of *next* month. However, if you enter \"17\",
3051 it will be considered as *this* month.
3053 If you set this variable to the symbol `time', then also the following
3054 will work:
3056 3. If the user gives a time.
3057 If the time is before now, it will be interpreted as tomorrow.
3059 Currently none of this works for ISO week specifications.
3061 When this option is nil, the current day, month and year will always be
3062 used as defaults.
3064 See also `org-agenda-jump-prefer-future'."
3065 :group 'org-time
3066 :type '(choice
3067 (const :tag "Never" nil)
3068 (const :tag "Check month and day" t)
3069 (const :tag "Check month, day, and time" time)))
3071 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3072 "Should the agenda jump command prefer the future for incomplete dates?
3073 The default is to do the same as configured in `org-read-date-prefer-future'.
3074 But you can also set a deviating value here.
3075 This may t or nil, or the symbol `org-read-date-prefer-future'."
3076 :group 'org-agenda
3077 :group 'org-time
3078 :version "24.1"
3079 :type '(choice
3080 (const :tag "Use org-read-date-prefer-future"
3081 org-read-date-prefer-future)
3082 (const :tag "Never" nil)
3083 (const :tag "Always" t)))
3085 (defcustom org-read-date-force-compatible-dates t
3086 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3088 Depending on the system Emacs is running on, certain dates cannot
3089 be represented with the type used internally to represent time.
3090 Dates between 1970-1-1 and 2038-1-1 can always be represented
3091 correctly. Some systems allow for earlier dates, some for later,
3092 some for both. One way to find out it to insert any date into an
3093 Org buffer, putting the cursor on the year and hitting S-up and
3094 S-down to test the range.
3096 When this variable is set to t, the date/time prompt will not let
3097 you specify dates outside the 1970-2037 range, so it is certain that
3098 these dates will work in whatever version of Emacs you are
3099 running, and also that you can move a file from one Emacs implementation
3100 to another. WHenever Org is forcing the year for you, it will display
3101 a message and beep.
3103 When this variable is nil, Org will check if the date is
3104 representable in the specific Emacs implementation you are using.
3105 If not, it will force a year, usually the current year, and beep
3106 to remind you. Currently this setting is not recommended because
3107 the likelihood that you will open your Org files in an Emacs that
3108 has limited date range is not negligible.
3110 A workaround for this problem is to use diary sexp dates for time
3111 stamps outside of this range."
3112 :group 'org-time
3113 :version "24.1"
3114 :type 'boolean)
3116 (defcustom org-read-date-display-live t
3117 "Non-nil means display current interpretation of date prompt live.
3118 This display will be in an overlay, in the minibuffer."
3119 :group 'org-time
3120 :type 'boolean)
3122 (defcustom org-read-date-popup-calendar t
3123 "Non-nil means pop up a calendar when prompting for a date.
3124 In the calendar, the date can be selected with mouse-1. However, the
3125 minibuffer will also be active, and you can simply enter the date as well.
3126 When nil, only the minibuffer will be available."
3127 :group 'org-time
3128 :type 'boolean)
3129 (org-defvaralias 'org-popup-calendar-for-date-prompt
3130 'org-read-date-popup-calendar)
3132 (make-obsolete-variable
3133 'org-read-date-minibuffer-setup-hook
3134 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3135 (defcustom org-read-date-minibuffer-setup-hook nil
3136 "Hook to be used to set up keys for the date/time interface.
3137 Add key definitions to `minibuffer-local-map', which will be a
3138 temporary copy.
3140 WARNING: This option is obsolete, you should use
3141 `org-read-date-minibuffer-local-map' to set up keys."
3142 :group 'org-time
3143 :type 'hook)
3145 (defcustom org-extend-today-until 0
3146 "The hour when your day really ends. Must be an integer.
3147 This has influence for the following applications:
3148 - When switching the agenda to \"today\". It it is still earlier than
3149 the time given here, the day recognized as TODAY is actually yesterday.
3150 - When a date is read from the user and it is still before the time given
3151 here, the current date and time will be assumed to be yesterday, 23:59.
3152 Also, timestamps inserted in capture templates follow this rule.
3154 IMPORTANT: This is a feature whose implementation is and likely will
3155 remain incomplete. Really, it is only here because past midnight seems to
3156 be the favorite working time of John Wiegley :-)"
3157 :group 'org-time
3158 :type 'integer)
3160 (defcustom org-use-effective-time nil
3161 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3162 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3163 \"effective time\" of any timestamps between midnight and 8am will be
3164 23:59 of the previous day."
3165 :group 'org-time
3166 :version "24.1"
3167 :type 'boolean)
3169 (defcustom org-use-last-clock-out-time-as-effective-time nil
3170 "When non-nil, use the last clock out time for `org-todo'.
3171 Note that this option has precedence over the combined use of
3172 `org-use-effective-time' and `org-extend-today-until'."
3173 :group 'org-time
3174 :version "24.4"
3175 :package-version '(Org . "8.0")
3176 :type 'boolean)
3178 (defcustom org-edit-timestamp-down-means-later nil
3179 "Non-nil means S-down will increase the time in a time stamp.
3180 When nil, S-up will increase."
3181 :group 'org-time
3182 :type 'boolean)
3184 (defcustom org-calendar-follow-timestamp-change t
3185 "Non-nil means make the calendar window follow timestamp changes.
3186 When a timestamp is modified and the calendar window is visible, it will be
3187 moved to the new date."
3188 :group 'org-time
3189 :type 'boolean)
3191 (defgroup org-tags nil
3192 "Options concerning tags in Org-mode."
3193 :tag "Org Tags"
3194 :group 'org)
3196 (defcustom org-tag-alist nil
3197 "List of tags allowed in Org-mode files.
3198 When this list is nil, Org-mode will base TAG input on what is already in the
3199 buffer.
3200 The value of this variable is an alist, the car of each entry must be a
3201 keyword as a string, the cdr may be a character that is used to select
3202 that tag through the fast-tag-selection interface.
3203 See the manual for details."
3204 :group 'org-tags
3205 :type '(repeat
3206 (choice
3207 (cons (string :tag "Tag name")
3208 (character :tag "Access char"))
3209 (list :tag "Start radio group"
3210 (const :startgroup)
3211 (option (string :tag "Group description")))
3212 (list :tag "Group tags delimiter"
3213 (const :grouptags))
3214 (list :tag "End radio group"
3215 (const :endgroup)
3216 (option (string :tag "Group description")))
3217 (const :tag "New line" (:newline)))))
3219 (defcustom org-tag-persistent-alist nil
3220 "List of tags that will always appear in all Org-mode files.
3221 This is in addition to any in buffer settings or customizations
3222 of `org-tag-alist'.
3223 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3224 The value of this variable is an alist, the car of each entry must be a
3225 keyword as a string, the cdr may be a character that is used to select
3226 that tag through the fast-tag-selection interface.
3227 See the manual for details.
3228 To disable these tags on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: noptag"
3230 :group 'org-tags
3231 :type '(repeat
3232 (choice
3233 (cons (string :tag "Tag name")
3234 (character :tag "Access char"))
3235 (const :tag "Start radio group" (:startgroup))
3236 (const :tag "Group tags delimiter" (:grouptags))
3237 (const :tag "End radio group" (:endgroup))
3238 (const :tag "New line" (:newline)))))
3240 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3241 "If non-nil, always offer completion for all tags of all agenda files.
3242 Instead of customizing this variable directly, you might want to
3243 set it locally for capture buffers, because there no list of
3244 tags in that file can be created dynamically (there are none).
3246 (add-hook 'org-capture-mode-hook
3247 (lambda ()
3248 (set (make-local-variable
3249 'org-complete-tags-always-offer-all-agenda-tags)
3250 t)))"
3251 :group 'org-tags
3252 :version "24.1"
3253 :type 'boolean)
3255 (defvar org-file-tags nil
3256 "List of tags that can be inherited by all entries in the file.
3257 The tags will be inherited if the variable `org-use-tag-inheritance'
3258 says they should be.
3259 This variable is populated from #+FILETAGS lines.")
3261 (defcustom org-use-fast-tag-selection 'auto
3262 "Non-nil means use fast tag selection scheme.
3263 This is a special interface to select and deselect tags with single keys.
3264 When nil, fast selection is never used.
3265 When the symbol `auto', fast selection is used if and only if selection
3266 characters for tags have been configured, either through the variable
3267 `org-tag-alist' or through a #+TAGS line in the buffer.
3268 When t, fast selection is always used and selection keys are assigned
3269 automatically if necessary."
3270 :group 'org-tags
3271 :type '(choice
3272 (const :tag "Always" t)
3273 (const :tag "Never" nil)
3274 (const :tag "When selection characters are configured" 'auto)))
3276 (defcustom org-fast-tag-selection-single-key nil
3277 "Non-nil means fast tag selection exits after first change.
3278 When nil, you have to press RET to exit it.
3279 During fast tag selection, you can toggle this flag with `C-c'.
3280 This variable can also have the value `expert'. In this case, the window
3281 displaying the tags menu is not even shown, until you press C-c again."
3282 :group 'org-tags
3283 :type '(choice
3284 (const :tag "No" nil)
3285 (const :tag "Yes" t)
3286 (const :tag "Expert" expert)))
3288 (defvar org-fast-tag-selection-include-todo nil
3289 "Non-nil means fast tags selection interface will also offer TODO states.
3290 This is an undocumented feature, you should not rely on it.")
3292 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3293 "The column to which tags should be indented in a headline.
3294 If this number is positive, it specifies the column. If it is negative,
3295 it means that the tags should be flushright to that column. For example,
3296 -80 works well for a normal 80 character screen.
3297 When 0, place tags directly after headline text, with only one space in
3298 between."
3299 :group 'org-tags
3300 :type 'integer)
3302 (defcustom org-auto-align-tags t
3303 "Non-nil keeps tags aligned when modifying headlines.
3304 Some operations (i.e. demoting) change the length of a headline and
3305 therefore shift the tags around. With this option turned on, after
3306 each such operation the tags are again aligned to `org-tags-column'."
3307 :group 'org-tags
3308 :type 'boolean)
3310 (defcustom org-use-tag-inheritance t
3311 "Non-nil means tags in levels apply also for sublevels.
3312 When nil, only the tags directly given in a specific line apply there.
3313 This may also be a list of tags that should be inherited, or a regexp that
3314 matches tags that should be inherited. Additional control is possible
3315 with the variable `org-tags-exclude-from-inheritance' which gives an
3316 explicit list of tags to be excluded from inheritance, even if the value of
3317 `org-use-tag-inheritance' would select it for inheritance.
3319 If this option is t, a match early-on in a tree can lead to a large
3320 number of matches in the subtree when constructing the agenda or creating
3321 a sparse tree. If you only want to see the first match in a tree during
3322 a search, check out the variable `org-tags-match-list-sublevels'."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "Not" nil)
3326 (const :tag "Always" t)
3327 (repeat :tag "Specific tags" (string :tag "Tag"))
3328 (regexp :tag "Tags matched by regexp")))
3330 (defcustom org-tags-exclude-from-inheritance nil
3331 "List of tags that should never be inherited.
3332 This is a way to exclude a few tags from inheritance. For way to do
3333 the opposite, to actively allow inheritance for selected tags,
3334 see the variable `org-use-tag-inheritance'."
3335 :group 'org-tags
3336 :type '(repeat (string :tag "Tag")))
3338 (defun org-tag-inherit-p (tag)
3339 "Check if TAG is one that should be inherited."
3340 (cond
3341 ((member tag org-tags-exclude-from-inheritance) nil)
3342 ((eq org-use-tag-inheritance t) t)
3343 ((not org-use-tag-inheritance) nil)
3344 ((stringp org-use-tag-inheritance)
3345 (string-match org-use-tag-inheritance tag))
3346 ((listp org-use-tag-inheritance)
3347 (member tag org-use-tag-inheritance))
3348 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3350 (defcustom org-tags-match-list-sublevels t
3351 "Non-nil means list also sublevels of headlines matching a search.
3352 This variable applies to tags/property searches, and also to stuck
3353 projects because this search is based on a tags match as well.
3355 When set to the symbol `indented', sublevels are indented with
3356 leading dots.
3358 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3359 the sublevels of a headline matching a tag search often also match
3360 the same search. Listing all of them can create very long lists.
3361 Setting this variable to nil causes subtrees of a match to be skipped.
3363 This variable is semi-obsolete and probably should always be true. It
3364 is better to limit inheritance to certain tags using the variables
3365 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3366 :group 'org-tags
3367 :type '(choice
3368 (const :tag "No, don't list them" nil)
3369 (const :tag "Yes, do list them" t)
3370 (const :tag "List them, indented with leading dots" indented)))
3372 (defcustom org-tags-sort-function nil
3373 "When set, tags are sorted using this function as a comparator."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No sorting" nil)
3377 (const :tag "Alphabetical" string<)
3378 (const :tag "Reverse alphabetical" string>)
3379 (function :tag "Custom function" nil)))
3381 (defvar org-tags-history nil
3382 "History of minibuffer reads for tags.")
3383 (defvar org-last-tags-completion-table nil
3384 "The last used completion table for tags.")
3385 (defvar org-after-tags-change-hook nil
3386 "Hook that is run after the tags in a line have changed.")
3388 (defgroup org-properties nil
3389 "Options concerning properties in Org-mode."
3390 :tag "Org Properties"
3391 :group 'org)
3393 (defcustom org-property-format "%-10s %s"
3394 "How property key/value pairs should be formatted by `indent-line'.
3395 When `indent-line' hits a property definition, it will format the line
3396 according to this format, mainly to make sure that the values are
3397 lined-up with respect to each other."
3398 :group 'org-properties
3399 :type 'string)
3401 (defcustom org-properties-postprocess-alist nil
3402 "Alist of properties and functions to adjust inserted values.
3403 Elements of this alist must be of the form
3405 ([string] [function])
3407 where [string] must be a property name and [function] must be a
3408 lambda expression: this lambda expression must take one argument,
3409 the value to adjust, and return the new value as a string.
3411 For example, this element will allow the property \"Remaining\"
3412 to be updated wrt the relation between the \"Effort\" property
3413 and the clock summary:
3415 ((\"Remaining\" (lambda(value)
3416 (let ((clocksum (org-clock-sum-current-item))
3417 (effort (org-duration-string-to-minutes
3418 (org-entry-get (point) \"Effort\"))))
3419 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3420 :group 'org-properties
3421 :version "24.1"
3422 :type '(alist :key-type (string :tag "Property")
3423 :value-type (function :tag "Function")))
3425 (defcustom org-use-property-inheritance nil
3426 "Non-nil means properties apply also for sublevels.
3428 This setting is chiefly used during property searches. Turning it on can
3429 cause significant overhead when doing a search, which is why it is not
3430 on by default.
3432 When nil, only the properties directly given in the current entry count.
3433 When t, every property is inherited. The value may also be a list of
3434 properties that should have inheritance, or a regular expression matching
3435 properties that should be inherited.
3437 However, note that some special properties use inheritance under special
3438 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3439 and the properties ending in \"_ALL\" when they are used as descriptor
3440 for valid values of a property.
3442 Note for programmers:
3443 When querying an entry with `org-entry-get', you can control if inheritance
3444 should be used. By default, `org-entry-get' looks only at the local
3445 properties. You can request inheritance by setting the inherit argument
3446 to t (to force inheritance) or to `selective' (to respect the setting
3447 in this variable)."
3448 :group 'org-properties
3449 :type '(choice
3450 (const :tag "Not" nil)
3451 (const :tag "Always" t)
3452 (repeat :tag "Specific properties" (string :tag "Property"))
3453 (regexp :tag "Properties matched by regexp")))
3455 (defun org-property-inherit-p (property)
3456 "Check if PROPERTY is one that should be inherited."
3457 (cond
3458 ((eq org-use-property-inheritance t) t)
3459 ((not org-use-property-inheritance) nil)
3460 ((stringp org-use-property-inheritance)
3461 (string-match org-use-property-inheritance property))
3462 ((listp org-use-property-inheritance)
3463 (member property org-use-property-inheritance))
3464 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3466 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3467 "The default column format, if no other format has been defined.
3468 This variable can be set on the per-file basis by inserting a line
3470 #+COLUMNS: %25ITEM ....."
3471 :group 'org-properties
3472 :type 'string)
3474 (defcustom org-columns-ellipses ".."
3475 "The ellipses to be used when a field in column view is truncated.
3476 When this is the empty string, as many characters as possible are shown,
3477 but then there will be no visual indication that the field has been truncated.
3478 When this is a string of length N, the last N characters of a truncated
3479 field are replaced by this string. If the column is narrower than the
3480 ellipses string, only part of the ellipses string will be shown."
3481 :group 'org-properties
3482 :type 'string)
3484 (defcustom org-columns-modify-value-for-display-function nil
3485 "Function that modifies values for display in column view.
3486 For example, it can be used to cut out a certain part from a time stamp.
3487 The function must take 2 arguments:
3489 column-title The title of the column (*not* the property name)
3490 value The value that should be modified.
3492 The function should return the value that should be displayed,
3493 or nil if the normal value should be used."
3494 :group 'org-properties
3495 :type 'function)
3497 (defcustom org-effort-property "Effort"
3498 "The property that is being used to keep track of effort estimates.
3499 Effort estimates given in this property need to have the format H:MM."
3500 :group 'org-properties
3501 :group 'org-progress
3502 :type '(string :tag "Property"))
3504 (defconst org-global-properties-fixed
3505 '(("VISIBILITY_ALL" . "folded children content all")
3506 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3507 "List of property/value pairs that can be inherited by any entry.
3509 These are fixed values, for the preset properties. The user variable
3510 that can be used to add to this list is `org-global-properties'.
3512 The entries in this list are cons cells where the car is a property
3513 name and cdr is a string with the value. If the value represents
3514 multiple items like an \"_ALL\" property, separate the items by
3515 spaces.")
3517 (defcustom org-global-properties nil
3518 "List of property/value pairs that can be inherited by any entry.
3520 This list will be combined with the constant `org-global-properties-fixed'.
3522 The entries in this list are cons cells where the car is a property
3523 name and cdr is a string with the value.
3525 You can set buffer-local values for the same purpose in the variable
3526 `org-file-properties' this by adding lines like
3528 #+PROPERTY: NAME VALUE"
3529 :group 'org-properties
3530 :type '(repeat
3531 (cons (string :tag "Property")
3532 (string :tag "Value"))))
3534 (defvar org-file-properties nil
3535 "List of property/value pairs that can be inherited by any entry.
3536 Valid for the current buffer.
3537 This variable is populated from #+PROPERTY lines.")
3538 (make-variable-buffer-local 'org-file-properties)
3540 (defgroup org-agenda nil
3541 "Options concerning agenda views in Org-mode."
3542 :tag "Org Agenda"
3543 :group 'org)
3545 (defvar org-category nil
3546 "Variable used by org files to set a category for agenda display.
3547 Such files should use a file variable to set it, for example
3549 # -*- mode: org; org-category: \"ELisp\"
3551 or contain a special line
3553 #+CATEGORY: ELisp
3555 If the file does not specify a category, then file's base name
3556 is used instead.")
3557 (make-variable-buffer-local 'org-category)
3558 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3560 (defcustom org-agenda-files nil
3561 "The files to be used for agenda display.
3562 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3563 \\[org-remove-file]. You can also use customize to edit the list.
3565 If an entry is a directory, all files in that directory that are matched by
3566 `org-agenda-file-regexp' will be part of the file list.
3568 If the value of the variable is not a list but a single file name, then
3569 the list of agenda files is actually stored and maintained in that file, one
3570 agenda file per line. In this file paths can be given relative to
3571 `org-directory'. Tilde expansion and environment variable substitution
3572 are also made."
3573 :group 'org-agenda
3574 :type '(choice
3575 (repeat :tag "List of files and directories" file)
3576 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3578 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3579 "Regular expression to match files for `org-agenda-files'.
3580 If any element in the list in that variable contains a directory instead
3581 of a normal file, all files in that directory that are matched by this
3582 regular expression will be included."
3583 :group 'org-agenda
3584 :type 'regexp)
3586 (defcustom org-agenda-text-search-extra-files nil
3587 "List of extra files to be searched by text search commands.
3588 These files will be searched in addition to the agenda files by the
3589 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3590 Note that these files will only be searched for text search commands,
3591 not for the other agenda views like todo lists, tag searches or the weekly
3592 agenda. This variable is intended to list notes and possibly archive files
3593 that should also be searched by these two commands.
3594 In fact, if the first element in the list is the symbol `agenda-archives',
3595 then all archive files of all agenda files will be added to the search
3596 scope."
3597 :group 'org-agenda
3598 :type '(set :greedy t
3599 (const :tag "Agenda Archives" agenda-archives)
3600 (repeat :inline t (file))))
3602 (org-defvaralias 'org-agenda-multi-occur-extra-files
3603 'org-agenda-text-search-extra-files)
3605 (defcustom org-agenda-skip-unavailable-files nil
3606 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3607 A nil value means to remove them, after a query, from the list."
3608 :group 'org-agenda
3609 :type 'boolean)
3611 (defcustom org-calendar-to-agenda-key [?c]
3612 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3613 The command `org-calendar-goto-agenda' will be bound to this key. The
3614 default is the character `c' because then `c' can be used to switch back and
3615 forth between agenda and calendar."
3616 :group 'org-agenda
3617 :type 'sexp)
3619 (defcustom org-calendar-insert-diary-entry-key [?i]
3620 "The key to be installed in `calendar-mode-map' for adding diary entries.
3621 This option is irrelevant until `org-agenda-diary-file' has been configured
3622 to point to an Org-mode file. When that is the case, the command
3623 `org-agenda-diary-entry' will be bound to the key given here, by default
3624 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3625 if you want to continue doing this, you need to change this to a different
3626 key."
3627 :group 'org-agenda
3628 :type 'sexp)
3630 (defcustom org-agenda-diary-file 'diary-file
3631 "File to which to add new entries with the `i' key in agenda and calendar.
3632 When this is the symbol `diary-file', the functionality in the Emacs
3633 calendar will be used to add entries to the `diary-file'. But when this
3634 points to a file, `org-agenda-diary-entry' will be used instead."
3635 :group 'org-agenda
3636 :type '(choice
3637 (const :tag "The standard Emacs diary file" diary-file)
3638 (file :tag "Special Org file diary entries")))
3640 (eval-after-load "calendar"
3641 '(progn
3642 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3643 'org-calendar-goto-agenda)
3644 (add-hook 'calendar-mode-hook
3645 (lambda ()
3646 (unless (eq org-agenda-diary-file 'diary-file)
3647 (define-key calendar-mode-map
3648 org-calendar-insert-diary-entry-key
3649 'org-agenda-diary-entry))))))
3651 (defgroup org-latex nil
3652 "Options for embedding LaTeX code into Org-mode."
3653 :tag "Org LaTeX"
3654 :group 'org)
3656 (defcustom org-format-latex-options
3657 '(:foreground default :background default :scale 1.0
3658 :html-foreground "Black" :html-background "Transparent"
3659 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3660 "Options for creating images from LaTeX fragments.
3661 This is a property list with the following properties:
3662 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3663 `default' means use the foreground of the default face.
3664 `auto' means use the foreground from the text face.
3665 :background the background color, or \"Transparent\".
3666 `default' means use the background of the default face.
3667 `auto' means use the background from the text face.
3668 :scale a scaling factor for the size of the images, to get more pixels
3669 :html-foreground, :html-background, :html-scale
3670 the same numbers for HTML export.
3671 :matchers a list indicating which matchers should be used to
3672 find LaTeX fragments. Valid members of this list are:
3673 \"begin\" find environments
3674 \"$1\" find single characters surrounded by $.$
3675 \"$\" find math expressions surrounded by $...$
3676 \"$$\" find math expressions surrounded by $$....$$
3677 \"\\(\" find math expressions surrounded by \\(...\\)
3678 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3679 :group 'org-latex
3680 :type 'plist)
3682 (defcustom org-format-latex-signal-error t
3683 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3684 When nil, just push out a message."
3685 :group 'org-latex
3686 :version "24.1"
3687 :type 'boolean)
3689 (defcustom org-latex-to-mathml-jar-file nil
3690 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3691 Use this to specify additional executable file say a jar file.
3693 When using MathToWeb as the converter, specify the full-path to
3694 your mathtoweb.jar file."
3695 :group 'org-latex
3696 :version "24.1"
3697 :type '(choice
3698 (const :tag "None" nil)
3699 (file :tag "JAR file" :must-match t)))
3701 (defcustom org-latex-to-mathml-convert-command nil
3702 "Command to convert LaTeX fragments to MathML.
3703 Replace format-specifiers in the command as noted below and use
3704 `shell-command' to convert LaTeX to MathML.
3705 %j: Executable file in fully expanded form as specified by
3706 `org-latex-to-mathml-jar-file'.
3707 %I: Input LaTeX file in fully expanded form
3708 %o: Output MathML file
3709 This command is used by `org-create-math-formula'.
3711 When using MathToWeb as the converter, set this to
3712 \"java -jar %j -unicode -force -df %o %I\"."
3713 :group 'org-latex
3714 :version "24.1"
3715 :type '(choice
3716 (const :tag "None" nil)
3717 (string :tag "\nShell command")))
3719 (defcustom org-latex-create-formula-image-program 'dvipng
3720 "Program to convert LaTeX fragments with.
3722 dvipng Process the LaTeX fragments to dvi file, then convert
3723 dvi files to png files using dvipng.
3724 This will also include processing of non-math environments.
3725 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3726 to convert pdf files to png files"
3727 :group 'org-latex
3728 :version "24.1"
3729 :type '(choice
3730 (const :tag "dvipng" dvipng)
3731 (const :tag "imagemagick" imagemagick)))
3733 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3734 "Path to store latex preview images.
3735 A relative path here creates many directories relative to the
3736 processed org files paths. An absolute path puts all preview
3737 images at the same place."
3738 :group 'org-latex
3739 :version "24.3"
3740 :type 'string)
3742 (defun org-format-latex-mathml-available-p ()
3743 "Return t if `org-latex-to-mathml-convert-command' is usable."
3744 (save-match-data
3745 (when (and (boundp 'org-latex-to-mathml-convert-command)
3746 org-latex-to-mathml-convert-command)
3747 (let ((executable (car (split-string
3748 org-latex-to-mathml-convert-command))))
3749 (when (executable-find executable)
3750 (if (string-match
3751 "%j" org-latex-to-mathml-convert-command)
3752 (file-readable-p org-latex-to-mathml-jar-file)
3753 t))))))
3755 (defcustom org-format-latex-header "\\documentclass{article}
3756 \\usepackage[usenames]{color}
3757 \\usepackage{amsmath}
3758 \\usepackage[mathscr]{eucal}
3759 \\pagestyle{empty} % do not remove
3760 \[PACKAGES]
3761 \[DEFAULT-PACKAGES]
3762 % The settings below are copied from fullpage.sty
3763 \\setlength{\\textwidth}{\\paperwidth}
3764 \\addtolength{\\textwidth}{-3cm}
3765 \\setlength{\\oddsidemargin}{1.5cm}
3766 \\addtolength{\\oddsidemargin}{-2.54cm}
3767 \\setlength{\\evensidemargin}{\\oddsidemargin}
3768 \\setlength{\\textheight}{\\paperheight}
3769 \\addtolength{\\textheight}{-\\headheight}
3770 \\addtolength{\\textheight}{-\\headsep}
3771 \\addtolength{\\textheight}{-\\footskip}
3772 \\addtolength{\\textheight}{-3cm}
3773 \\setlength{\\topmargin}{1.5cm}
3774 \\addtolength{\\topmargin}{-2.54cm}"
3775 "The document header used for processing LaTeX fragments.
3776 It is imperative that this header make sure that no page number
3777 appears on the page. The package defined in the variables
3778 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3779 will either replace the placeholder \"[PACKAGES]\" in this
3780 header, or they will be appended."
3781 :group 'org-latex
3782 :type 'string)
3784 (defun org-set-packages-alist (var val)
3785 "Set the packages alist and make sure it has 3 elements per entry."
3786 (set var (mapcar (lambda (x)
3787 (if (and (consp x) (= (length x) 2))
3788 (list (car x) (nth 1 x) t)
3790 val)))
3792 (defun org-get-packages-alist (var)
3793 "Get the packages alist and make sure it has 3 elements per entry."
3794 (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 (default-value var)))
3800 (defcustom org-latex-default-packages-alist
3801 '(("AUTO" "inputenc" t)
3802 ("T1" "fontenc" t)
3803 ("" "fixltx2e" nil)
3804 ("" "graphicx" t)
3805 ("" "longtable" nil)
3806 ("" "float" nil)
3807 ("" "wrapfig" nil)
3808 ("normalem" "ulem" t)
3809 ("" "textcomp" t)
3810 ("" "marvosym" t)
3811 ("" "wasysym" t)
3812 ("" "latexsym" t)
3813 ("" "amssymb" t)
3814 ("" "amstext" nil)
3815 ("" "hyperref" nil)
3816 "\\tolerance=1000")
3817 "Alist of default packages to be inserted in the header.
3819 Change this only if one of the packages here causes an
3820 incompatibility with another package you are using.
3822 The packages in this list are needed by one part or another of
3823 Org mode to function properly:
3825 - inputenc, fontenc: for basic font and character selection
3826 - amstext: for subscript and superscript
3827 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3828 symbols used for interpreting the entities in `org-entities'.
3829 You can skip some of these packages if you don't use any of the
3830 symbols in it.
3831 - ulem: for underline and strike-through
3832 - graphicx: for including images
3833 - float, wrapfig: for figure placement
3834 - longtable: for long tables
3835 - hyperref: for cross references
3837 Therefore you should not modify this variable unless you know
3838 what you are doing. The one reason to change it anyway is that
3839 you might be loading some other package that conflicts with one
3840 of the default packages. Each cell is of the format
3841 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3842 the package also needs to be included when compiling LaTeX
3843 snippets into images for inclusion into non-LaTeX output."
3844 :group 'org-latex
3845 :group 'org-export-latex
3846 :set 'org-set-packages-alist
3847 :get 'org-get-packages-alist
3848 :version "24.1"
3849 :type '(repeat
3850 (choice
3851 (list :tag "options/package pair"
3852 (string :tag "options")
3853 (string :tag "package")
3854 (boolean :tag "Snippet"))
3855 (string :tag "A line of LaTeX"))))
3857 (defcustom org-latex-packages-alist nil
3858 "Alist of packages to be inserted in every LaTeX header.
3860 These will be inserted after `org-latex-default-packages-alist'.
3861 Each cell is of the format:
3863 \(\"options\" \"package\" snippet-flag)
3865 SNIPPET-FLAG, when t, indicates that this package is also needed
3866 when turning LaTeX snippets into images for inclusion into
3867 non-LaTeX output.
3869 Make sure that you only list packages here which:
3871 - you want in every file
3872 - do not conflict with the setup in `org-format-latex-header'.
3873 - do not conflict with the default packages in
3874 `org-latex-default-packages-alist'."
3875 :group 'org-latex
3876 :group 'org-export-latex
3877 :set 'org-set-packages-alist
3878 :get 'org-get-packages-alist
3879 :type '(repeat
3880 (choice
3881 (list :tag "options/package pair"
3882 (string :tag "options")
3883 (string :tag "package")
3884 (boolean :tag "Snippet"))
3885 (string :tag "A line of LaTeX"))))
3887 (defgroup org-appearance nil
3888 "Settings for Org-mode appearance."
3889 :tag "Org Appearance"
3890 :group 'org)
3892 (defcustom org-level-color-stars-only nil
3893 "Non-nil means fontify only the stars in each headline.
3894 When nil, the entire headline is fontified.
3895 Changing it requires restart of `font-lock-mode' to become effective
3896 also in regions already fontified."
3897 :group 'org-appearance
3898 :type 'boolean)
3900 (defcustom org-hide-leading-stars nil
3901 "Non-nil means hide the first N-1 stars in a headline.
3902 This works by using the face `org-hide' for these stars. This
3903 face is white for a light background, and black for a dark
3904 background. You may have to customize the face `org-hide' to
3905 make this work.
3906 Changing it requires restart of `font-lock-mode' to become effective
3907 also in regions already fontified.
3908 You may also set this on a per-file basis by adding one of the following
3909 lines to the buffer:
3911 #+STARTUP: hidestars
3912 #+STARTUP: showstars"
3913 :group 'org-appearance
3914 :type 'boolean)
3916 (defcustom org-hidden-keywords nil
3917 "List of symbols corresponding to keywords to be hidden the org buffer.
3918 For example, a value '(title) for this list will make the document's title
3919 appear in the buffer without the initial #+TITLE: keyword."
3920 :group 'org-appearance
3921 :version "24.1"
3922 :type '(set (const :tag "#+AUTHOR" author)
3923 (const :tag "#+DATE" date)
3924 (const :tag "#+EMAIL" email)
3925 (const :tag "#+TITLE" title)))
3927 (defcustom org-custom-properties nil
3928 "List of properties (as strings) with a special meaning.
3929 The default use of these custom properties is to let the user
3930 hide them with `org-toggle-custom-properties-visibility'."
3931 :group 'org-properties
3932 :group 'org-appearance
3933 :version "24.3"
3934 :type '(repeat (string :tag "Property Name")))
3936 (defcustom org-fontify-done-headline nil
3937 "Non-nil means change the face of a headline if it is marked DONE.
3938 Normally, only the TODO/DONE keyword indicates the state of a headline.
3939 When this is non-nil, the headline after the keyword is set to the
3940 `org-headline-done' as an additional indication."
3941 :group 'org-appearance
3942 :type 'boolean)
3944 (defcustom org-fontify-emphasized-text t
3945 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3946 Changing this variable requires a restart of Emacs to take effect."
3947 :group 'org-appearance
3948 :type 'boolean)
3950 (defcustom org-fontify-whole-heading-line nil
3951 "Non-nil means fontify the whole line for headings.
3952 This is useful when setting a background color for the
3953 org-level-* faces."
3954 :group 'org-appearance
3955 :type 'boolean)
3957 (defcustom org-highlight-latex-and-related nil
3958 "Non-nil means highlight LaTeX related syntax in the buffer.
3959 When non nil, the value should be a list containing any of the
3960 following symbols:
3961 `latex' Highlight LaTeX snippets and environments.
3962 `script' Highlight subscript and superscript.
3963 `entities' Highlight entities."
3964 :group 'org-appearance
3965 :version "24.4"
3966 :package-version '(Org . "8.0")
3967 :type '(choice
3968 (const :tag "No highlighting" nil)
3969 (set :greedy t :tag "Highlight"
3970 (const :tag "LaTeX snippets and environments" latex)
3971 (const :tag "Subscript and superscript" script)
3972 (const :tag "Entities" entities))))
3974 (defcustom org-hide-emphasis-markers nil
3975 "Non-nil mean font-lock should hide the emphasis marker characters."
3976 :group 'org-appearance
3977 :type 'boolean)
3979 (defcustom org-pretty-entities nil
3980 "Non-nil means show entities as UTF8 characters.
3981 When nil, the \\name form remains in the buffer."
3982 :group 'org-appearance
3983 :version "24.1"
3984 :type 'boolean)
3986 (defcustom org-pretty-entities-include-sub-superscripts t
3987 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3988 :group 'org-appearance
3989 :version "24.1"
3990 :type 'boolean)
3992 (defvar org-emph-re nil
3993 "Regular expression for matching emphasis.
3994 After a match, the match groups contain these elements:
3995 0 The match of the full regular expression, including the characters
3996 before and after the proper match
3997 1 The character before the proper match, or empty at beginning of line
3998 2 The proper match, including the leading and trailing markers
3999 3 The leading marker like * or /, indicating the type of highlighting
4000 4 The text between the emphasis markers, not including the markers
4001 5 The character after the match, empty at the end of a line")
4002 (defvar org-verbatim-re nil
4003 "Regular expression for matching verbatim text.")
4004 (defvar org-emphasis-regexp-components) ; defined just below
4005 (defvar org-emphasis-alist) ; defined just below
4006 (defun org-set-emph-re (var val)
4007 "Set variable and compute the emphasis regular expression."
4008 (set var val)
4009 (when (and (boundp 'org-emphasis-alist)
4010 (boundp 'org-emphasis-regexp-components)
4011 org-emphasis-alist org-emphasis-regexp-components)
4012 (let* ((e org-emphasis-regexp-components)
4013 (pre (car e))
4014 (post (nth 1 e))
4015 (border (nth 2 e))
4016 (body (nth 3 e))
4017 (nl (nth 4 e))
4018 (body1 (concat body "*?"))
4019 (markers (mapconcat 'car org-emphasis-alist ""))
4020 (vmarkers (mapconcat
4021 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4022 org-emphasis-alist "")))
4023 ;; make sure special characters appear at the right position in the class
4024 (if (string-match "\\^" markers)
4025 (setq markers (concat (replace-match "" t t markers) "^")))
4026 (if (string-match "-" markers)
4027 (setq markers (concat (replace-match "" t t markers) "-")))
4028 (if (string-match "\\^" vmarkers)
4029 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4030 (if (string-match "-" vmarkers)
4031 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4032 (if (> nl 0)
4033 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4034 (int-to-string nl) "\\}")))
4035 ;; Make the regexp
4036 (setq org-emph-re
4037 (concat "\\([" pre "]\\|^\\)"
4038 "\\("
4039 "\\([" markers "]\\)"
4040 "\\("
4041 "[^" border "]\\|"
4042 "[^" border "]"
4043 body1
4044 "[^" border "]"
4045 "\\)"
4046 "\\3\\)"
4047 "\\([" post "]\\|$\\)"))
4048 (setq org-verbatim-re
4049 (concat "\\([" pre "]\\|^\\)"
4050 "\\("
4051 "\\([" vmarkers "]\\)"
4052 "\\("
4053 "[^" border "]\\|"
4054 "[^" border "]"
4055 body1
4056 "[^" border "]"
4057 "\\)"
4058 "\\3\\)"
4059 "\\([" post "]\\|$\\)")))))
4061 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4062 ;; set this option proved cumbersome. See this message/thread:
4063 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4064 (defvar org-emphasis-regexp-components
4065 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4066 "Components used to build the regular expression for emphasis.
4067 This is a list with five entries. Terminology: In an emphasis string
4068 like \" *strong word* \", we call the initial space PREMATCH, the final
4069 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4070 and \"trong wor\" is the body. The different components in this variable
4071 specify what is allowed/forbidden in each part:
4073 pre Chars allowed as prematch. Beginning of line will be allowed too.
4074 post Chars allowed as postmatch. End of line will be allowed too.
4075 border The chars *forbidden* as border characters.
4076 body-regexp A regexp like \".\" to match a body character. Don't use
4077 non-shy groups here, and don't allow newline here.
4078 newline The maximum number of newlines allowed in an emphasis exp.
4080 You need to reload Org or to restart Emacs after customizing this.")
4082 (defcustom org-emphasis-alist
4083 `(("*" bold)
4084 ("/" italic)
4085 ("_" underline)
4086 ("=" org-code verbatim)
4087 ("~" org-verbatim verbatim)
4088 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4089 "Alist of characters and faces to emphasize text.
4090 Text starting and ending with a special character will be emphasized,
4091 for example *bold*, _underlined_ and /italic/. This variable sets the
4092 marker characters and the face to be used by font-lock for highlighting
4093 in Org-mode Emacs buffers.
4095 You need to reload Org or to restart Emacs after customizing this."
4096 :group 'org-appearance
4097 :set 'org-set-emph-re
4098 :version "24.4"
4099 :package-version '(Org . "8.0")
4100 :type '(repeat
4101 (list
4102 (string :tag "Marker character")
4103 (choice
4104 (face :tag "Font-lock-face")
4105 (plist :tag "Face property list"))
4106 (option (const verbatim)))))
4108 (defvar org-protecting-blocks
4109 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4110 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4111 This is needed for font-lock setup.")
4113 ;;; Miscellaneous options
4115 (defgroup org-completion nil
4116 "Completion in Org-mode."
4117 :tag "Org Completion"
4118 :group 'org)
4120 (defcustom org-completion-use-ido nil
4121 "Non-nil means use ido completion wherever possible.
4122 Note that `ido-mode' must be active for this variable to be relevant.
4123 If you decide to turn this variable on, you might well want to turn off
4124 `org-outline-path-complete-in-steps'.
4125 See also `org-completion-use-iswitchb'."
4126 :group 'org-completion
4127 :type 'boolean)
4129 (defcustom org-completion-use-iswitchb nil
4130 "Non-nil means use iswitchb completion wherever possible.
4131 Note that `iswitchb-mode' must be active for this variable to be relevant.
4132 If you decide to turn this variable on, you might well want to turn off
4133 `org-outline-path-complete-in-steps'.
4134 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4135 :group 'org-completion
4136 :type 'boolean)
4138 (defcustom org-completion-fallback-command 'hippie-expand
4139 "The expansion command called by \\[pcomplete] in normal context.
4140 Normal means, no org-mode-specific context."
4141 :group 'org-completion
4142 :type 'function)
4144 ;;; Functions and variables from their packages
4145 ;; Declared here to avoid compiler warnings
4147 ;; XEmacs only
4148 (defvar outline-mode-menu-heading)
4149 (defvar outline-mode-menu-show)
4150 (defvar outline-mode-menu-hide)
4151 (defvar zmacs-regions) ; XEmacs regions
4153 ;; Emacs only
4154 (defvar mark-active)
4156 ;; Various packages
4157 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4158 (declare-function calendar-forward-day "cal-move" (arg))
4159 (declare-function calendar-goto-date "cal-move" (date))
4160 (declare-function calendar-goto-today "cal-move" ())
4161 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4162 (defvar calc-embedded-close-formula)
4163 (defvar calc-embedded-open-formula)
4164 (declare-function cdlatex-tab "ext:cdlatex" ())
4165 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4166 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4167 (defvar font-lock-unfontify-region-function)
4168 (declare-function iswitchb-read-buffer "iswitchb"
4169 (prompt &optional default require-match start matches-set))
4170 (defvar iswitchb-temp-buflist)
4171 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4172 (defvar org-agenda-tags-todo-honor-ignore-options)
4173 (declare-function org-agenda-skip "org-agenda" ())
4174 (declare-function
4175 org-agenda-format-item "org-agenda"
4176 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4177 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4178 (declare-function org-agenda-change-all-lines "org-agenda"
4179 (newhead hdmarker &optional fixface just-this))
4180 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4181 (declare-function org-agenda-maybe-redo "org-agenda" ())
4182 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4183 (beg end))
4184 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4185 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4186 "org-agenda" (&optional end))
4187 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4188 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4189 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4190 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4191 (declare-function org-indent-mode "org-indent" (&optional arg))
4192 (declare-function parse-time-string "parse-time" (string))
4193 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4194 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4195 (defvar remember-data-file)
4196 (defvar texmathp-why)
4197 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4198 (declare-function table--at-cell-p "table" (position &optional object at-column))
4200 (defvar org-latex-regexps)
4202 ;;; Autoload and prepare some org modules
4204 ;; Some table stuff that needs to be defined here, because it is used
4205 ;; by the functions setting up org-mode or checking for table context.
4207 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4208 "Detect an org-type or table-type table.")
4209 (defconst org-table-line-regexp "^[ \t]*|"
4210 "Detect an org-type table line.")
4211 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4212 "Detect an org-type table line.")
4213 (defconst org-table-hline-regexp "^[ \t]*|-"
4214 "Detect an org-type table hline.")
4215 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4216 "Detect a table-type table hline.")
4217 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4218 "Detect the first line outside a table when searching from within it.
4219 This works for both table types.")
4221 ;; Autoload the functions in org-table.el that are needed by functions here.
4223 (eval-and-compile
4224 (org-autoload "org-table"
4225 '(org-table-begin org-table-blank-field org-table-end)))
4227 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4228 "Detect a #+TBLFM line.")
4230 ;;;###autoload
4231 (defun turn-on-orgtbl ()
4232 "Unconditionally turn on `orgtbl-mode'."
4233 (require 'org-table)
4234 (orgtbl-mode 1))
4236 (defun org-at-table-p (&optional table-type)
4237 "Return t if the cursor is inside an org-type table.
4238 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4239 (if org-enable-table-editor
4240 (save-excursion
4241 (beginning-of-line 1)
4242 (looking-at (if table-type org-table-any-line-regexp
4243 org-table-line-regexp)))
4244 nil))
4245 (defsubst org-table-p () (org-at-table-p))
4247 (defun org-at-table.el-p ()
4248 "Return t if and only if we are at a table.el table."
4249 (and (org-at-table-p 'any)
4250 (save-excursion
4251 (goto-char (org-table-begin 'any))
4252 (looking-at org-table1-hline-regexp))))
4254 (defun org-table-recognize-table.el ()
4255 "If there is a table.el table nearby, recognize it and move into it."
4256 (if org-table-tab-recognizes-table.el
4257 (if (org-at-table.el-p)
4258 (progn
4259 (beginning-of-line 1)
4260 (if (looking-at org-table-dataline-regexp)
4262 (if (looking-at org-table1-hline-regexp)
4263 (progn
4264 (beginning-of-line 2)
4265 (if (looking-at org-table-any-border-regexp)
4266 (beginning-of-line -1)))))
4267 (if (re-search-forward "|" (org-table-end t) t)
4268 (progn
4269 (require 'table)
4270 (if (table--at-cell-p (point))
4272 (message "recognizing table.el table...")
4273 (table-recognize-table)
4274 (message "recognizing table.el table...done")))
4275 (error "This should not happen"))
4277 nil)
4278 nil))
4280 (defun org-at-table-hline-p ()
4281 "Return t if the cursor is inside a hline in a table."
4282 (if org-enable-table-editor
4283 (save-excursion
4284 (beginning-of-line 1)
4285 (looking-at org-table-hline-regexp))
4286 nil))
4288 (defvar org-table-clean-did-remove-column nil)
4289 (defun org-table-map-tables (function &optional quietly)
4290 "Apply FUNCTION to the start of all tables in the buffer."
4291 (save-excursion
4292 (save-restriction
4293 (widen)
4294 (goto-char (point-min))
4295 (while (re-search-forward org-table-any-line-regexp nil t)
4296 (unless quietly
4297 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4298 (beginning-of-line 1)
4299 (when (and (looking-at org-table-line-regexp)
4300 ;; Exclude tables in src/example/verbatim/clocktable blocks
4301 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4302 (save-excursion (funcall function))
4303 (or (looking-at org-table-line-regexp)
4304 (forward-char 1)))
4305 (re-search-forward org-table-any-border-regexp nil 1))))
4306 (unless quietly (message "Mapping tables: done")))
4308 ;; Declare and autoload functions from ox.el and al.
4310 (declare-function org-export-get-environment "ox"
4311 (&optional backend subtreep ext-plist))
4312 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4314 ;; Declare and autoload functions from org-agenda.el
4316 (eval-and-compile
4317 (org-autoload "org-agenda"
4318 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4320 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4321 (declare-function org-clock-update-mode-line "org-clock" ())
4322 (declare-function org-resolve-clocks "org-clock"
4323 (&optional also-non-dangling-p prompt last-valid))
4325 (defun org-at-TBLFM-p (&optional pos)
4326 "Return t when point (or POS) is in #+TBLFM line."
4327 (save-excursion
4328 (let ((pos pos)))
4329 (goto-char (or pos (point)))
4330 (beginning-of-line 1)
4331 (looking-at org-TBLFM-regexp)))
4333 (defvar org-clock-start-time)
4334 (defvar org-clock-marker (make-marker)
4335 "Marker recording the last clock-in.")
4336 (defvar org-clock-hd-marker (make-marker)
4337 "Marker recording the last clock-in, but the headline position.")
4338 (defvar org-clock-heading ""
4339 "The heading of the current clock entry.")
4340 (defun org-clock-is-active ()
4341 "Return the buffer where the clock is currently running.
4342 Return nil if no clock is running."
4343 (marker-buffer org-clock-marker))
4345 (eval-and-compile
4346 (org-autoload "org-clock" '(org-clock-remove-overlays
4347 org-clock-update-time-maybe
4348 org-clocktable-shift)))
4350 (defun org-check-running-clock ()
4351 "Check if the current buffer contains the running clock.
4352 If yes, offer to stop it and to save the buffer with the changes."
4353 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4354 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4355 (buffer-name))))
4356 (org-clock-out)
4357 (when (y-or-n-p "Save changed buffer?")
4358 (save-buffer))))
4360 (defun org-clocktable-try-shift (dir n)
4361 "Check if this line starts a clock table, if yes, shift the time block."
4362 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4363 (org-clocktable-shift dir n)))
4365 ;;;###autoload
4366 (defun org-clock-persistence-insinuate ()
4367 "Set up hooks for clock persistence."
4368 (require 'org-clock)
4369 (add-hook 'org-mode-hook 'org-clock-load)
4370 (add-hook 'kill-emacs-hook 'org-clock-save))
4372 ;; Define the variable already here, to make sure we have it.
4373 (defvar org-indent-mode nil
4374 "Non-nil if Org-Indent mode is enabled.
4375 Use the command `org-indent-mode' to change this variable.")
4377 ;; Autoload archiving code
4378 ;; The stuff that is needed for cycling and tags has to be defined here.
4380 (defgroup org-archive nil
4381 "Options concerning archiving in Org-mode."
4382 :tag "Org Archive"
4383 :group 'org-structure)
4385 (defcustom org-archive-location "%s_archive::"
4386 "The location where subtrees should be archived.
4388 The value of this variable is a string, consisting of two parts,
4389 separated by a double-colon. The first part is a filename and
4390 the second part is a headline.
4392 When the filename is omitted, archiving happens in the same file.
4393 %s in the filename will be replaced by the current file
4394 name (without the directory part). Archiving to a different file
4395 is useful to keep archived entries from contributing to the
4396 Org-mode Agenda.
4398 The archived entries will be filed as subtrees of the specified
4399 headline. When the headline is omitted, the subtrees are simply
4400 filed away at the end of the file, as top-level entries. Also in
4401 the heading you can use %s to represent the file name, this can be
4402 useful when using the same archive for a number of different files.
4404 Here are a few examples:
4405 \"%s_archive::\"
4406 If the current file is Projects.org, archive in file
4407 Projects.org_archive, as top-level trees. This is the default.
4409 \"::* Archived Tasks\"
4410 Archive in the current file, under the top-level headline
4411 \"* Archived Tasks\".
4413 \"~/org/archive.org::\"
4414 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4416 \"~/org/archive.org::* From %s\"
4417 Archive in file ~/org/archive.org (absolute path), under headlines
4418 \"From FILENAME\" where file name is the current file name.
4420 \"~/org/datetree.org::datetree/* Finished Tasks\"
4421 The \"datetree/\" string is special, signifying to archive
4422 items to the datetree. Items are placed in either the CLOSED
4423 date of the item, or the current date if there is no CLOSED date.
4424 The heading will be a subentry to the current date. There doesn't
4425 need to be a heading, but there always needs to be a slash after
4426 datetree. For example, to store archived items directly in the
4427 datetree, use \"~/org/datetree.org::datetree/\".
4429 \"basement::** Finished Tasks\"
4430 Archive in file ./basement (relative path), as level 3 trees
4431 below the level 2 heading \"** Finished Tasks\".
4433 You may set this option on a per-file basis by adding to the buffer a
4434 line like
4436 #+ARCHIVE: basement::** Finished Tasks
4438 You may also define it locally for a subtree by setting an ARCHIVE property
4439 in the entry. If such a property is found in an entry, or anywhere up
4440 the hierarchy, it will be used."
4441 :group 'org-archive
4442 :type 'string)
4444 (defcustom org-archive-tag "ARCHIVE"
4445 "The tag that marks a subtree as archived.
4446 An archived subtree does not open during visibility cycling, and does
4447 not contribute to the agenda listings.
4448 After changing this, font-lock must be restarted in the relevant buffers to
4449 get the proper fontification."
4450 :group 'org-archive
4451 :group 'org-keywords
4452 :type 'string)
4454 (defcustom org-agenda-skip-archived-trees t
4455 "Non-nil means the agenda will skip any items located in archived trees.
4456 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4457 variable is no longer recommended, you should leave it at the value t.
4458 Instead, use the key `v' to cycle the archives-mode in the agenda."
4459 :group 'org-archive
4460 :group 'org-agenda-skip
4461 :type 'boolean)
4463 (defcustom org-columns-skip-archived-trees t
4464 "Non-nil means ignore archived trees when creating column view."
4465 :group 'org-archive
4466 :group 'org-properties
4467 :type 'boolean)
4469 (defcustom org-cycle-open-archived-trees nil
4470 "Non-nil means `org-cycle' will open archived trees.
4471 An archived tree is a tree marked with the tag ARCHIVE.
4472 When nil, archived trees will stay folded. You can still open them with
4473 normal outline commands like `show-all', but not with the cycling commands."
4474 :group 'org-archive
4475 :group 'org-cycle
4476 :type 'boolean)
4478 (defcustom org-sparse-tree-open-archived-trees nil
4479 "Non-nil means sparse tree construction shows matches in archived trees.
4480 When nil, matches in these trees are highlighted, but the trees are kept in
4481 collapsed state."
4482 :group 'org-archive
4483 :group 'org-sparse-trees
4484 :type 'boolean)
4486 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4487 "The default date type when building a sparse tree.
4488 When this is nil, a date is a scheduled or a deadline timestamp.
4489 Otherwise, these types are allowed:
4491 all: all timestamps
4492 active: only active timestamps (<...>)
4493 inactive: only inactive timestamps (<...)
4494 scheduled: only scheduled timestamps
4495 deadline: only deadline timestamps"
4496 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4497 (const :tag "All timestamps" all)
4498 (const :tag "Only active timestamps" active)
4499 (const :tag "Only inactive timestamps" inactive)
4500 (const :tag "Only scheduled timestamps" scheduled)
4501 (const :tag "Only deadline timestamps" deadline)
4502 (const :tag "Only closed timestamps" closed))
4503 :version "24.3"
4504 :group 'org-sparse-trees)
4506 (defun org-cycle-hide-archived-subtrees (state)
4507 "Re-hide all archived subtrees after a visibility state change."
4508 (when (and (not org-cycle-open-archived-trees)
4509 (not (memq state '(overview folded))))
4510 (save-excursion
4511 (let* ((globalp (memq state '(contents all)))
4512 (beg (if globalp (point-min) (point)))
4513 (end (if globalp (point-max) (org-end-of-subtree t))))
4514 (org-hide-archived-subtrees beg end)
4515 (goto-char beg)
4516 (if (looking-at (concat ".*:" org-archive-tag ":"))
4517 (message "%s" (substitute-command-keys
4518 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4520 (defun org-force-cycle-archived ()
4521 "Cycle subtree even if it is archived."
4522 (interactive)
4523 (setq this-command 'org-cycle)
4524 (let ((org-cycle-open-archived-trees t))
4525 (call-interactively 'org-cycle)))
4527 (defun org-hide-archived-subtrees (beg end)
4528 "Re-hide all archived subtrees after a visibility state change."
4529 (save-excursion
4530 (let* ((re (concat ":" org-archive-tag ":")))
4531 (goto-char beg)
4532 (while (re-search-forward re end t)
4533 (when (org-at-heading-p)
4534 (org-flag-subtree t)
4535 (org-end-of-subtree t))))))
4537 (declare-function outline-end-of-heading "outline" ())
4538 (declare-function outline-flag-region "outline" (from to flag))
4539 (defun org-flag-subtree (flag)
4540 (save-excursion
4541 (org-back-to-heading t)
4542 (outline-end-of-heading)
4543 (outline-flag-region (point)
4544 (progn (org-end-of-subtree t) (point))
4545 flag)))
4547 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4549 (eval-and-compile
4550 (org-autoload "org-archive"
4551 '(org-add-archive-files)))
4553 ;; Autoload Column View Code
4555 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4556 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4557 (declare-function org-columns-compute "org-colview" (property))
4559 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4560 '(org-columns-number-to-string
4561 org-columns-get-format-and-top-level
4562 org-columns-compute
4563 org-columns-remove-overlays))
4565 ;; Autoload ID code
4567 (declare-function org-id-store-link "org-id")
4568 (declare-function org-id-locations-load "org-id")
4569 (declare-function org-id-locations-save "org-id")
4570 (defvar org-id-track-globally)
4571 (org-autoload "org-id"
4572 '(org-id-new
4573 org-id-copy
4574 org-id-get-with-outline-path-completion
4575 org-id-get-with-outline-drilling))
4577 ;;; Variables for pre-computed regular expressions, all buffer local
4579 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4580 "Matches first line of a hidden block.")
4581 (make-variable-buffer-local 'org-drawer-regexp)
4582 (defvar org-todo-regexp nil
4583 "Matches any of the TODO state keywords.")
4584 (make-variable-buffer-local 'org-todo-regexp)
4585 (defvar org-not-done-regexp nil
4586 "Matches any of the TODO state keywords except the last one.")
4587 (make-variable-buffer-local 'org-not-done-regexp)
4588 (defvar org-not-done-heading-regexp nil
4589 "Matches a TODO headline that is not done.")
4590 (make-variable-buffer-local 'org-not-done-regexp)
4591 (defvar org-todo-line-regexp nil
4592 "Matches a headline and puts TODO state into group 2 if present.")
4593 (make-variable-buffer-local 'org-todo-line-regexp)
4594 (defvar org-complex-heading-regexp nil
4595 "Matches a headline and puts everything into groups:
4596 group 1: the stars
4597 group 2: The todo keyword, maybe
4598 group 3: Priority cookie
4599 group 4: True headline
4600 group 5: Tags")
4601 (make-variable-buffer-local 'org-complex-heading-regexp)
4602 (defvar org-complex-heading-regexp-format nil
4603 "Printf format to make regexp to match an exact headline.
4604 This regexp will match the headline of any node which has the
4605 exact headline text that is put into the format, but may have any
4606 TODO state, priority and tags.")
4607 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4608 (defvar org-todo-line-tags-regexp nil
4609 "Matches a headline and puts TODO state into group 2 if present.
4610 Also put tags into group 4 if tags are present.")
4611 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4612 (defvar org-ds-keyword-length 12
4613 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4614 (make-variable-buffer-local 'org-ds-keyword-length)
4615 (defvar org-deadline-regexp nil
4616 "Matches the DEADLINE keyword.")
4617 (make-variable-buffer-local 'org-deadline-regexp)
4618 (defvar org-deadline-time-regexp nil
4619 "Matches the DEADLINE keyword together with a time stamp.")
4620 (make-variable-buffer-local 'org-deadline-time-regexp)
4621 (defvar org-deadline-time-hour-regexp nil
4622 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4623 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4624 (defvar org-deadline-line-regexp nil
4625 "Matches the DEADLINE keyword and the rest of the line.")
4626 (make-variable-buffer-local 'org-deadline-line-regexp)
4627 (defvar org-scheduled-regexp nil
4628 "Matches the SCHEDULED keyword.")
4629 (make-variable-buffer-local 'org-scheduled-regexp)
4630 (defvar org-scheduled-time-regexp nil
4631 "Matches the SCHEDULED keyword together with a time stamp.")
4632 (make-variable-buffer-local 'org-scheduled-time-regexp)
4633 (defvar org-scheduled-time-hour-regexp nil
4634 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4635 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4636 (defvar org-closed-time-regexp nil
4637 "Matches the CLOSED keyword together with a time stamp.")
4638 (make-variable-buffer-local 'org-closed-time-regexp)
4640 (defvar org-keyword-time-regexp nil
4641 "Matches any of the 4 keywords, together with the time stamp.")
4642 (make-variable-buffer-local 'org-keyword-time-regexp)
4643 (defvar org-keyword-time-not-clock-regexp nil
4644 "Matches any of the 3 keywords, together with the time stamp.")
4645 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4646 (defvar org-maybe-keyword-time-regexp nil
4647 "Matches a timestamp, possibly preceded by a keyword.")
4648 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4649 (defvar org-all-time-keywords nil
4650 "List of time keywords.")
4651 (make-variable-buffer-local 'org-all-time-keywords)
4653 (defconst org-plain-time-of-day-regexp
4654 (concat
4655 "\\(\\<[012]?[0-9]"
4656 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4657 "\\(--?"
4658 "\\(\\<[012]?[0-9]"
4659 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4660 "\\)?")
4661 "Regular expression to match a plain time or time range.
4662 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4663 groups carry important information:
4664 0 the full match
4665 1 the first time, range or not
4666 8 the second time, if it is a range.")
4668 (defconst org-plain-time-extension-regexp
4669 (concat
4670 "\\(\\<[012]?[0-9]"
4671 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4672 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4673 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4674 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4675 groups carry important information:
4676 0 the full match
4677 7 hours of duration
4678 9 minutes of duration")
4680 (defconst org-stamp-time-of-day-regexp
4681 (concat
4682 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4683 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4684 "\\(--?"
4685 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4686 "Regular expression to match a timestamp time or time range.
4687 After a match, the following groups carry important information:
4688 0 the full match
4689 1 date plus weekday, for back referencing to make sure both times are on the same day
4690 2 the first time, range or not
4691 4 the second time, if it is a range.")
4693 (defconst org-startup-options
4694 '(("fold" org-startup-folded t)
4695 ("overview" org-startup-folded t)
4696 ("nofold" org-startup-folded nil)
4697 ("showall" org-startup-folded nil)
4698 ("showeverything" org-startup-folded showeverything)
4699 ("content" org-startup-folded content)
4700 ("indent" org-startup-indented t)
4701 ("noindent" org-startup-indented nil)
4702 ("hidestars" org-hide-leading-stars t)
4703 ("showstars" org-hide-leading-stars nil)
4704 ("odd" org-odd-levels-only t)
4705 ("oddeven" org-odd-levels-only nil)
4706 ("align" org-startup-align-all-tables t)
4707 ("noalign" org-startup-align-all-tables nil)
4708 ("inlineimages" org-startup-with-inline-images t)
4709 ("noinlineimages" org-startup-with-inline-images nil)
4710 ("latexpreview" org-startup-with-latex-preview t)
4711 ("nolatexpreview" org-startup-with-latex-preview nil)
4712 ("customtime" org-display-custom-times t)
4713 ("logdone" org-log-done time)
4714 ("lognotedone" org-log-done note)
4715 ("nologdone" org-log-done nil)
4716 ("lognoteclock-out" org-log-note-clock-out t)
4717 ("nolognoteclock-out" org-log-note-clock-out nil)
4718 ("logrepeat" org-log-repeat state)
4719 ("lognoterepeat" org-log-repeat note)
4720 ("logdrawer" org-log-into-drawer t)
4721 ("nologdrawer" org-log-into-drawer nil)
4722 ("logstatesreversed" org-log-states-order-reversed t)
4723 ("nologstatesreversed" org-log-states-order-reversed nil)
4724 ("nologrepeat" org-log-repeat nil)
4725 ("logreschedule" org-log-reschedule time)
4726 ("lognotereschedule" org-log-reschedule note)
4727 ("nologreschedule" org-log-reschedule nil)
4728 ("logredeadline" org-log-redeadline time)
4729 ("lognoteredeadline" org-log-redeadline note)
4730 ("nologredeadline" org-log-redeadline nil)
4731 ("logrefile" org-log-refile time)
4732 ("lognoterefile" org-log-refile note)
4733 ("nologrefile" org-log-refile nil)
4734 ("fninline" org-footnote-define-inline t)
4735 ("nofninline" org-footnote-define-inline nil)
4736 ("fnlocal" org-footnote-section nil)
4737 ("fnauto" org-footnote-auto-label t)
4738 ("fnprompt" org-footnote-auto-label nil)
4739 ("fnconfirm" org-footnote-auto-label confirm)
4740 ("fnplain" org-footnote-auto-label plain)
4741 ("fnadjust" org-footnote-auto-adjust t)
4742 ("nofnadjust" org-footnote-auto-adjust nil)
4743 ("constcgs" constants-unit-system cgs)
4744 ("constSI" constants-unit-system SI)
4745 ("noptag" org-tag-persistent-alist nil)
4746 ("hideblocks" org-hide-block-startup t)
4747 ("nohideblocks" org-hide-block-startup nil)
4748 ("beamer" org-startup-with-beamer-mode t)
4749 ("entitiespretty" org-pretty-entities t)
4750 ("entitiesplain" org-pretty-entities nil))
4751 "Variable associated with STARTUP options for org-mode.
4752 Each element is a list of three items: the startup options (as written
4753 in the #+STARTUP line), the corresponding variable, and the value to set
4754 this variable to if the option is found. An optional forth element PUSH
4755 means to push this value onto the list in the variable.")
4757 (defun org-update-property-plist (key val props)
4758 "Update PROPS with KEY and VAL."
4759 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4760 (key (if appending (substring key 0 (- (length key) 1)) key))
4761 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4762 (previous (cdr (assoc key props))))
4763 (if appending
4764 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4765 (cons (cons key val) remainder))))
4767 (defconst org-block-regexp
4768 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4769 "Regular expression for hiding blocks.")
4770 (defconst org-heading-keyword-regexp-format
4771 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4772 "Printf format for a regexp matching a headline with some keyword.
4773 This regexp will match the headline of any node which has the
4774 exact keyword that is put into the format. The keyword isn't in
4775 any group by default, but the stars and the body are.")
4776 (defconst org-heading-keyword-maybe-regexp-format
4777 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4778 "Printf format for a regexp matching a headline, possibly with some keyword.
4779 This regexp can match any headline with the specified keyword, or
4780 without a keyword. The keyword isn't in any group by default,
4781 but the stars and the body are.")
4783 (defcustom org-group-tags t
4784 "When non-nil (the default), use group tags.
4785 This can be turned on/off through `org-toggle-tags-groups'."
4786 :group 'org-tags
4787 :group 'org-startup
4788 :type 'boolean)
4790 (defun org-toggle-tags-groups ()
4791 "Toggle support for group tags.
4792 Support for group tags is controlled by the option
4793 `org-group-tags', which is non-nil by default."
4794 (interactive)
4795 (setq org-group-tags (not org-group-tags))
4796 (cond ((and (derived-mode-p 'org-agenda-mode)
4797 org-group-tags)
4798 (org-agenda-redo))
4799 ((derived-mode-p 'org-mode)
4800 (let ((org-inhibit-startup t)) (org-mode))))
4801 (message "Groups tags support has been turned %s"
4802 (if org-group-tags "on" "off")))
4804 (defun org-set-regexps-and-options-for-tags ()
4805 "Precompute variables used for tags."
4806 (when (derived-mode-p 'org-mode)
4807 (org-set-local 'org-file-tags nil)
4808 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4809 (splitre "[ \t]+")
4810 (start 0)
4811 tags ftags key value)
4812 (save-excursion
4813 (save-restriction
4814 (widen)
4815 (goto-char (point-min))
4816 (while (re-search-forward re nil t)
4817 (setq key (upcase (org-match-string-no-properties 1))
4818 value (org-match-string-no-properties 2))
4819 (if (stringp value) (setq value (org-trim value)))
4820 (cond
4821 ((equal key "TAGS")
4822 (setq tags (append tags (if tags '("\\n") nil)
4823 (org-split-string value splitre))))
4824 ((equal key "FILETAGS")
4825 (when (string-match "\\S-" value)
4826 (setq ftags
4827 (append
4828 ftags
4829 (apply 'append
4830 (mapcar (lambda (x) (org-split-string x ":"))
4831 (org-split-string value)))))))))))
4832 ;; Process the file tags.
4833 (and ftags (org-set-local 'org-file-tags
4834 (mapcar 'org-add-prop-inherited ftags)))
4835 (org-set-local 'org-tag-groups-alist nil)
4836 ;; Process the tags.
4837 (when (and (not tags) org-tag-alist)
4838 (setq tags
4839 (mapcar
4840 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4841 ((eq (car tg) :endgroup) "}")
4842 ((eq (car tg) :grouptags) ":")
4843 (t (concat (car tg)
4844 (if (characterp (cdr tg))
4845 (format "(%s)" (char-to-string (cdr tg))) "")))))
4846 org-tag-alist)))
4847 (let (e tgs g)
4848 (while (setq e (pop tags))
4849 (cond
4850 ((equal e "{")
4851 (progn (push '(:startgroup) tgs)
4852 (when (equal (nth 1 tags) ":")
4853 (push (list (replace-regexp-in-string
4854 "(.+)$" "" (nth 0 tags)))
4855 org-tag-groups-alist)
4856 (setq g 0))))
4857 ((equal e ":") (push '(:grouptags) tgs))
4858 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4859 ((equal e "\\n") (push '(:newline) tgs))
4860 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4861 (push (cons (match-string 1 e)
4862 (string-to-char (match-string 2 e))) tgs)
4863 (if (and g (> g 0))
4864 (setcar org-tag-groups-alist
4865 (append (car org-tag-groups-alist)
4866 (list (match-string 1 e)))))
4867 (if g (setq g (1+ g))))
4868 (t (push (list e) tgs)
4869 (if (and g (> g 0))
4870 (setcar org-tag-groups-alist
4871 (append (car org-tag-groups-alist) (list e))))
4872 (if g (setq g (1+ g))))))
4873 (org-set-local 'org-tag-alist nil)
4874 (while (setq e (pop tgs))
4875 (or (and (stringp (car e))
4876 (assoc (car e) org-tag-alist))
4877 (push e org-tag-alist)))
4878 ;; Return a list with tag variables
4879 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4881 (defvar org-ota nil)
4882 (defun org-set-regexps-and-options ()
4883 "Precompute regular expressions used in the current buffer."
4884 (when (derived-mode-p 'org-mode)
4885 (org-set-local 'org-todo-kwd-alist nil)
4886 (org-set-local 'org-todo-key-alist nil)
4887 (org-set-local 'org-todo-key-trigger nil)
4888 (org-set-local 'org-todo-keywords-1 nil)
4889 (org-set-local 'org-done-keywords nil)
4890 (org-set-local 'org-todo-heads nil)
4891 (org-set-local 'org-todo-sets nil)
4892 (org-set-local 'org-todo-log-states nil)
4893 (org-set-local 'org-file-properties nil)
4894 (let ((re (org-make-options-regexp
4895 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4896 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4897 "SETUPFILE" "OPTIONS")
4898 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4899 (splitre "[ \t]+")
4900 (scripts org-use-sub-superscripts)
4901 kwds kws0 kwsa key log value cat arch const links hw dws
4902 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4903 (start 0))
4904 (save-excursion
4905 (save-restriction
4906 (widen)
4907 (goto-char (point-min))
4908 (while
4909 (or (and
4910 ext-setup-or-nil
4911 (not org-ota)
4912 (let (ret)
4913 (with-temp-buffer
4914 (insert ext-setup-or-nil)
4915 (let ((major-mode 'org-mode) org-ota)
4916 (setq ret (save-match-data
4917 (org-set-regexps-and-options-for-tags)))))
4918 ;; Append setupfile tags to existing tags
4919 (setq org-ota t)
4920 (setq org-file-tags
4921 (delq nil (append org-file-tags (nth 0 ret)))
4922 org-tag-alist
4923 (delq nil (append org-tag-alist (nth 1 ret)))
4924 org-tag-groups-alist
4925 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4926 (and ext-setup-or-nil
4927 (string-match re ext-setup-or-nil start)
4928 (setq start (match-end 0)))
4929 (and (setq ext-setup-or-nil nil start 0)
4930 (re-search-forward re nil t)))
4931 (setq key (upcase (match-string 1 ext-setup-or-nil))
4932 value (org-match-string-no-properties 2 ext-setup-or-nil))
4933 (if (stringp value) (setq value (org-trim value)))
4934 (cond
4935 ((equal key "CATEGORY")
4936 (setq cat value))
4937 ((member key '("SEQ_TODO" "TODO"))
4938 (push (cons 'sequence (org-split-string value splitre)) kwds))
4939 ((equal key "TYP_TODO")
4940 (push (cons 'type (org-split-string value splitre)) kwds))
4941 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4942 ;; general TODO-like setup
4943 (push (cons (intern (downcase (match-string 1 key)))
4944 (org-split-string value splitre)) kwds))
4945 ((equal key "COLUMNS")
4946 (org-set-local 'org-columns-default-format value))
4947 ((equal key "LINK")
4948 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4949 (push (cons (match-string 1 value)
4950 (org-trim (match-string 2 value)))
4951 links)))
4952 ((equal key "PRIORITIES")
4953 (setq prio (org-split-string value " +")))
4954 ((equal key "PROPERTY")
4955 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4956 (setq props (org-update-property-plist (match-string 1 value)
4957 (match-string 2 value)
4958 props))))
4959 ((equal key "DRAWERS")
4960 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4961 ((equal key "CONSTANTS")
4962 (org-table-set-constants))
4963 ((equal key "STARTUP")
4964 (let ((opts (org-split-string value splitre))
4965 l var val)
4966 (while (setq l (pop opts))
4967 (when (setq l (assoc l org-startup-options))
4968 (setq var (nth 1 l) val (nth 2 l))
4969 (if (not (nth 3 l))
4970 (set (make-local-variable var) val)
4971 (if (not (listp (symbol-value var)))
4972 (set (make-local-variable var) nil))
4973 (set (make-local-variable var) (symbol-value var))
4974 (add-to-list var val))))))
4975 ((equal key "ARCHIVE")
4976 (setq arch value)
4977 (remove-text-properties 0 (length arch)
4978 '(face t fontified t) arch))
4979 ((equal key "OPTIONS")
4980 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4981 (setq scripts (read (match-string 2 value)))))
4982 ((and (equal key "SETUPFILE")
4983 ;; Prevent checking in Gnus messages
4984 (not buffer-read-only))
4985 (setq setup-contents (org-file-contents
4986 (expand-file-name
4987 (org-remove-double-quotes value))
4988 'noerror))
4989 (if (not ext-setup-or-nil)
4990 (setq ext-setup-or-nil setup-contents start 0)
4991 (setq ext-setup-or-nil
4992 (concat (substring ext-setup-or-nil 0 start)
4993 "\n" setup-contents "\n"
4994 (substring ext-setup-or-nil start)))))))
4995 ;; search for property blocks
4996 (goto-char (point-min))
4997 (while (re-search-forward org-block-regexp nil t)
4998 (when (equal "PROPERTY" (upcase (match-string 1)))
4999 (setq value (replace-regexp-in-string
5000 "[\n\r]" " " (match-string 4)))
5001 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5002 (setq props (org-update-property-plist (match-string 1 value)
5003 (match-string 2 value)
5004 props)))))))
5005 (org-set-local 'org-use-sub-superscripts scripts)
5006 (when cat
5007 (org-set-local 'org-category (intern cat))
5008 (push (cons "CATEGORY" cat) props))
5009 (when prio
5010 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5011 (setq prio (mapcar 'string-to-char prio))
5012 (org-set-local 'org-highest-priority (nth 0 prio))
5013 (org-set-local 'org-lowest-priority (nth 1 prio))
5014 (org-set-local 'org-default-priority (nth 2 prio)))
5015 (and props (org-set-local 'org-file-properties (nreverse props)))
5016 (and drawers (org-set-local 'org-drawers drawers))
5017 (and arch (org-set-local 'org-archive-location arch))
5018 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5019 ;; Process the TODO keywords
5020 (unless kwds
5021 ;; Use the global values as if they had been given locally.
5022 (setq kwds (default-value 'org-todo-keywords))
5023 (if (stringp (car kwds))
5024 (setq kwds (list (cons org-todo-interpretation
5025 (default-value 'org-todo-keywords)))))
5026 (setq kwds (reverse kwds)))
5027 (setq kwds (nreverse kwds))
5028 (let (inter kws kw)
5029 (while (setq kws (pop kwds))
5030 (let ((kws (or
5031 (run-hook-with-args-until-success
5032 'org-todo-setup-filter-hook kws)
5033 kws)))
5034 (setq inter (pop kws) sep (member "|" kws)
5035 kws0 (delete "|" (copy-sequence kws))
5036 kwsa nil
5037 kws1 (mapcar
5038 (lambda (x)
5039 ;; 1 2
5040 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5041 (progn
5042 (setq kw (match-string 1 x)
5043 key (and (match-end 2) (match-string 2 x))
5044 log (org-extract-log-state-settings x))
5045 (push (cons kw (and key (string-to-char key))) kwsa)
5046 (and log (push log org-todo-log-states))
5048 (error "Invalid TODO keyword %s" x)))
5049 kws0)
5050 kwsa (if kwsa (append '((:startgroup))
5051 (nreverse kwsa)
5052 '((:endgroup))))
5053 hw (car kws1)
5054 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5055 tail (list inter hw (car dws) (org-last dws))))
5056 (add-to-list 'org-todo-heads hw 'append)
5057 (push kws1 org-todo-sets)
5058 (setq org-done-keywords (append org-done-keywords dws nil))
5059 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5060 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5061 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5062 (setq org-todo-sets (nreverse org-todo-sets)
5063 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5064 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5065 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5066 ;; Compute the regular expressions and other local variables.
5067 ;; Using `org-outline-regexp-bol' would complicate them much,
5068 ;; because of the fixed white space at the end of that string.
5069 (if (not org-done-keywords)
5070 (setq org-done-keywords (and org-todo-keywords-1
5071 (list (org-last org-todo-keywords-1)))))
5072 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5073 (length org-scheduled-string)
5074 (length org-clock-string)
5075 (length org-closed-string)))
5076 org-drawer-regexp
5077 (concat "^[ \t]*:\\("
5078 (mapconcat 'regexp-quote org-drawers "\\|")
5079 "\\):[ \t]*$")
5080 org-not-done-keywords
5081 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5082 org-todo-regexp
5083 (concat "\\("
5084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5085 "\\)")
5086 org-not-done-regexp
5087 (concat "\\("
5088 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5089 "\\)")
5090 org-not-done-heading-regexp
5091 (format org-heading-keyword-regexp-format org-not-done-regexp)
5092 org-todo-line-regexp
5093 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5094 org-complex-heading-regexp
5095 (concat "^\\(\\*+\\)"
5096 "\\(?: +" org-todo-regexp "\\)?"
5097 "\\(?: +\\(\\[#.\\]\\)\\)?"
5098 "\\(?: +\\(.*?\\)\\)??"
5099 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5100 "[ \t]*$")
5101 org-complex-heading-regexp-format
5102 (concat "^\\(\\*+\\)"
5103 "\\(?: +" org-todo-regexp "\\)?"
5104 "\\(?: +\\(\\[#.\\]\\)\\)?"
5105 "\\(?: +"
5106 ;; Stats cookies can be stuck to body.
5107 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5108 "\\(%s\\)"
5109 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5110 "\\)"
5111 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5112 "[ \t]*$")
5113 org-todo-line-tags-regexp
5114 (concat "^\\(\\*+\\)"
5115 "\\(?: +" org-todo-regexp "\\)?"
5116 "\\(?: +\\(.*?\\)\\)??"
5117 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5118 "[ \t]*$")
5119 org-deadline-regexp (concat "\\<" org-deadline-string)
5120 org-deadline-time-regexp
5121 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5122 org-deadline-time-hour-regexp
5123 (concat "\\<" org-deadline-string
5124 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5125 org-deadline-line-regexp
5126 (concat "\\<\\(" org-deadline-string "\\).*")
5127 org-scheduled-regexp
5128 (concat "\\<" org-scheduled-string)
5129 org-scheduled-time-regexp
5130 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5131 org-scheduled-time-hour-regexp
5132 (concat "\\<" org-scheduled-string
5133 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5134 org-closed-time-regexp
5135 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5136 org-keyword-time-regexp
5137 (concat "\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\|" org-clock-string "\\)"
5141 " *[[<]\\([^]>]+\\)[]>]")
5142 org-keyword-time-not-clock-regexp
5143 (concat "\\<\\(" org-scheduled-string
5144 "\\|" org-deadline-string
5145 "\\|" org-closed-string
5146 "\\)"
5147 " *[[<]\\([^]>]+\\)[]>]")
5148 org-maybe-keyword-time-regexp
5149 (concat "\\(\\<\\(" org-scheduled-string
5150 "\\|" org-deadline-string
5151 "\\|" org-closed-string
5152 "\\|" org-clock-string "\\)\\)?"
5153 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5154 org-all-time-keywords
5155 (mapcar (lambda (w) (substring w 0 -1))
5156 (list org-scheduled-string org-deadline-string
5157 org-clock-string org-closed-string)))
5158 (setq org-ota nil)
5159 (org-compute-latex-and-related-regexp))))
5161 (defun org-file-contents (file &optional noerror)
5162 "Return the contents of FILE, as a string."
5163 (if (or (not file)
5164 (not (file-readable-p file)))
5165 (if noerror
5166 (message "Cannot read file \"%s\"" file)
5167 (error "Cannot read file \"%s\"" file))
5168 (with-temp-buffer
5169 (insert-file-contents file)
5170 (buffer-string))))
5172 (defun org-extract-log-state-settings (x)
5173 "Extract the log state setting from a TODO keyword string.
5174 This will extract info from a string like \"WAIT(w@/!)\"."
5175 (let (kw key log1 log2)
5176 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5177 (setq kw (match-string 1 x)
5178 key (and (match-end 2) (match-string 2 x))
5179 log1 (and (match-end 3) (match-string 3 x))
5180 log2 (and (match-end 4) (match-string 4 x)))
5181 (and (or log1 log2)
5182 (list kw
5183 (and log1 (if (equal log1 "!") 'time 'note))
5184 (and log2 (if (equal log2 "!") 'time 'note)))))))
5186 (defun org-remove-keyword-keys (list)
5187 "Remove a pair of parenthesis at the end of each string in LIST."
5188 (mapcar (lambda (x)
5189 (if (string-match "(.*)$" x)
5190 (substring x 0 (match-beginning 0))
5192 list))
5194 (defun org-assign-fast-keys (alist)
5195 "Assign fast keys to a keyword-key alist.
5196 Respect keys that are already there."
5197 (let (new e (alt ?0))
5198 (while (setq e (pop alist))
5199 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5200 (cdr e)) ;; Key already assigned.
5201 (push e new)
5202 (let ((clist (string-to-list (downcase (car e))))
5203 (used (append new alist)))
5204 (when (= (car clist) ?@)
5205 (pop clist))
5206 (while (and clist (rassoc (car clist) used))
5207 (pop clist))
5208 (unless clist
5209 (while (rassoc alt used)
5210 (incf alt)))
5211 (push (cons (car e) (or (car clist) alt)) new))))
5212 (nreverse new)))
5214 ;;; Some variables used in various places
5216 (defvar org-window-configuration nil
5217 "Used in various places to store a window configuration.")
5218 (defvar org-selected-window nil
5219 "Used in various places to store a window configuration.")
5220 (defvar org-finish-function nil
5221 "Function to be called when `C-c C-c' is used.
5222 This is for getting out of special buffers like capture.")
5225 ;; FIXME: Occasionally check by commenting these, to make sure
5226 ;; no other functions uses these, forgetting to let-bind them.
5227 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5228 (defvar org-last-state)
5229 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5231 ;; Defined somewhere in this file, but used before definition.
5232 (defvar org-entities) ;; defined in org-entities.el
5233 (defvar org-struct-menu)
5234 (defvar org-org-menu)
5235 (defvar org-tbl-menu)
5237 ;;;; Define the Org-mode
5239 ;; We use a before-change function to check if a table might need
5240 ;; an update.
5241 (defvar org-table-may-need-update t
5242 "Indicates that a table might need an update.
5243 This variable is set by `org-before-change-function'.
5244 `org-table-align' sets it back to nil.")
5245 (defun org-before-change-function (beg end)
5246 "Every change indicates that a table might need an update."
5247 (setq org-table-may-need-update t))
5248 (defvar org-mode-map)
5249 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5250 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5251 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5252 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5253 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5254 (defvar org-table-buffer-is-an nil)
5256 (defvar bidi-paragraph-direction)
5257 (defvar buffer-face-mode-face)
5259 (require 'outline)
5260 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5261 (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"))
5262 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5264 ;; Other stuff we need.
5265 (require 'time-date)
5266 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5267 (require 'easymenu)
5268 (require 'overlay)
5270 ;; (require 'org-macs) moved higher up in the file before it is first used
5271 (require 'org-entities)
5272 ;; (require 'org-compat) moved higher up in the file before it is first used
5273 (require 'org-faces)
5274 (require 'org-list)
5275 (require 'org-pcomplete)
5276 (require 'org-src)
5277 (require 'org-footnote)
5278 (require 'org-macro)
5280 ;; babel
5281 (require 'ob)
5283 ;;;###autoload
5284 (define-derived-mode org-mode outline-mode "Org"
5285 "Outline-based notes management and organizer, alias
5286 \"Carsten's outline-mode for keeping track of everything.\"
5288 Org-mode develops organizational tasks around a NOTES file which
5289 contains information about projects as plain text. Org-mode is
5290 implemented on top of outline-mode, which is ideal to keep the content
5291 of large files well structured. It supports ToDo items, deadlines and
5292 time stamps, which magically appear in the diary listing of the Emacs
5293 calendar. Tables are easily created with a built-in table editor.
5294 Plain text URL-like links connect to websites, emails (VM), Usenet
5295 messages (Gnus), BBDB entries, and any files related to the project.
5296 For printing and sharing of notes, an Org-mode file (or a part of it)
5297 can be exported as a structured ASCII or HTML file.
5299 The following commands are available:
5301 \\{org-mode-map}"
5303 ;; Get rid of Outline menus, they are not needed
5304 ;; Need to do this here because define-derived-mode sets up
5305 ;; the keymap so late. Still, it is a waste to call this each time
5306 ;; we switch another buffer into org-mode.
5307 (if (featurep 'xemacs)
5308 (when (boundp 'outline-mode-menu-heading)
5309 ;; Assume this is Greg's port, it uses easymenu
5310 (easy-menu-remove outline-mode-menu-heading)
5311 (easy-menu-remove outline-mode-menu-show)
5312 (easy-menu-remove outline-mode-menu-hide))
5313 (define-key org-mode-map [menu-bar headings] 'undefined)
5314 (define-key org-mode-map [menu-bar hide] 'undefined)
5315 (define-key org-mode-map [menu-bar show] 'undefined))
5317 (org-load-modules-maybe)
5318 (easy-menu-add org-org-menu)
5319 (easy-menu-add org-tbl-menu)
5320 (org-install-agenda-files-menu)
5321 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5322 (add-to-invisibility-spec '(org-cwidth))
5323 (add-to-invisibility-spec '(org-hide-block . t))
5324 (when (featurep 'xemacs)
5325 (org-set-local 'line-move-ignore-invisible t))
5326 (org-set-local 'outline-regexp org-outline-regexp)
5327 (org-set-local 'outline-level 'org-outline-level)
5328 (setq bidi-paragraph-direction 'left-to-right)
5329 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5330 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5331 (when (and org-ellipsis
5332 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5333 (fboundp 'make-glyph-code))
5334 (unless org-display-table
5335 (setq org-display-table (make-display-table)))
5336 (set-display-table-slot
5337 org-display-table 4
5338 (vconcat (mapcar
5339 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5340 org-ellipsis)))
5341 (if (stringp org-ellipsis) org-ellipsis "..."))))
5342 (setq buffer-display-table org-display-table))
5343 (org-set-regexps-and-options-for-tags)
5344 (org-set-regexps-and-options)
5345 (org-set-font-lock-defaults)
5346 (when (and org-tag-faces (not org-tags-special-faces-re))
5347 ;; tag faces set outside customize.... force initialization.
5348 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5349 ;; Calc embedded
5350 (org-set-local 'calc-embedded-open-mode "# ")
5351 ;; Modify a few syntax entries
5352 (modify-syntax-entry ?@ "w")
5353 (modify-syntax-entry ?\" "\"")
5354 (if org-startup-truncated (setq truncate-lines t))
5355 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5356 (org-set-local 'font-lock-unfontify-region-function
5357 'org-unfontify-region)
5358 ;; Activate before-change-function
5359 (org-set-local 'org-table-may-need-update t)
5360 (org-add-hook 'before-change-functions 'org-before-change-function nil
5361 'local)
5362 ;; Check for running clock before killing a buffer
5363 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5364 ;; Initialize macros templates.
5365 (org-macro-initialize-templates)
5366 ;; Initialize radio targets.
5367 (org-update-radio-target-regexp)
5368 ;; Indentation.
5369 (org-set-local 'indent-line-function 'org-indent-line)
5370 (org-set-local 'indent-region-function 'org-indent-region)
5371 ;; Filling and auto-filling.
5372 (org-setup-filling)
5373 ;; Comments.
5374 (org-setup-comments-handling)
5375 ;; Beginning/end of defun
5376 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5377 (org-set-local 'end-of-defun-function 'org-forward-element)
5378 ;; Next error for sparse trees
5379 (org-set-local 'next-error-function 'org-occur-next-match)
5380 ;; Make sure dependence stuff works reliably, even for users who set it
5381 ;; too late :-(
5382 (if org-enforce-todo-dependencies
5383 (add-hook 'org-blocker-hook
5384 'org-block-todo-from-children-or-siblings-or-parent)
5385 (remove-hook 'org-blocker-hook
5386 'org-block-todo-from-children-or-siblings-or-parent))
5387 (if org-enforce-todo-checkbox-dependencies
5388 (add-hook 'org-blocker-hook
5389 'org-block-todo-from-checkboxes)
5390 (remove-hook 'org-blocker-hook
5391 'org-block-todo-from-checkboxes))
5393 ;; Align options lines
5394 (org-set-local
5395 'align-mode-rules-list
5396 '((org-in-buffer-settings
5397 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5398 (modes . '(org-mode)))))
5400 ;; Imenu
5401 (org-set-local 'imenu-create-index-function
5402 'org-imenu-get-tree)
5404 ;; Make isearch reveal context
5405 (if (or (featurep 'xemacs)
5406 (not (boundp 'outline-isearch-open-invisible-function)))
5407 ;; Emacs 21 and XEmacs make use of the hook
5408 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5409 ;; Emacs 22 deals with this through a special variable
5410 (org-set-local 'outline-isearch-open-invisible-function
5411 (lambda (&rest ignore) (org-show-context 'isearch)))
5412 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5414 ;; Setup the pcomplete hooks
5415 (set (make-local-variable 'pcomplete-command-completion-function)
5416 'org-pcomplete-initial)
5417 (set (make-local-variable 'pcomplete-command-name-function)
5418 'org-command-at-point)
5419 (set (make-local-variable 'pcomplete-default-completion-function)
5420 'ignore)
5421 (set (make-local-variable 'pcomplete-parse-arguments-function)
5422 'org-parse-arguments)
5423 (set (make-local-variable 'pcomplete-termination-string) "")
5424 (when (>= emacs-major-version 23)
5425 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5427 ;; If empty file that did not turn on org-mode automatically, make it to.
5428 (if (and org-insert-mode-line-in-empty-file
5429 (org-called-interactively-p 'any)
5430 (= (point-min) (point-max)))
5431 (insert "# -*- mode: org -*-\n\n"))
5432 (unless org-inhibit-startup
5433 (org-unmodified
5434 (and org-startup-with-beamer-mode (org-beamer-mode))
5435 (when org-startup-align-all-tables
5436 (org-table-map-tables 'org-table-align 'quietly))
5437 (when org-startup-with-inline-images
5438 (org-display-inline-images))
5439 (when org-startup-with-latex-preview
5440 (org-preview-latex-fragment))
5441 (unless org-inhibit-startup-visibility-stuff
5442 (org-set-startup-visibility))))
5443 ;; Try to set org-hide correctly
5444 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5446 ;; Update `customize-package-emacs-version-alist'
5447 (add-to-list 'customize-package-emacs-version-alist
5448 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5449 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5450 ("8.0" . "24.4")))
5452 (defvar org-mode-transpose-word-syntax-table
5453 (let ((st (make-syntax-table)))
5454 (mapc (lambda(c) (modify-syntax-entry
5455 (string-to-char (car c)) "w p" st))
5456 org-emphasis-alist)
5457 st))
5459 (when (fboundp 'abbrev-table-put)
5460 (abbrev-table-put org-mode-abbrev-table
5461 :parents (list text-mode-abbrev-table)))
5463 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5465 (defsubst org-fix-ellipsis-at-bol ()
5466 (save-excursion (goto-char (window-start)) (recenter 0)))
5468 (defun org-find-invisible-foreground ()
5469 (let ((candidates (remove
5470 "unspecified-bg"
5471 (nconc
5472 (list (face-background 'default)
5473 (face-background 'org-default))
5474 (mapcar
5475 (lambda (alist)
5476 (when (boundp alist)
5477 (cdr (assoc 'background-color (symbol-value alist)))))
5478 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5479 (list (face-foreground 'org-hide))))))
5480 (car (remove nil candidates))))
5482 (defun org-current-time (&optional rounding-minutes past)
5483 "Current time, possibly rounded to ROUNDING-MINUTES.
5484 When ROUNDING-MINUTES is not an integer, fall back on the car of
5485 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5486 the rounding returns a past time."
5487 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5488 (car org-time-stamp-rounding-minutes)))
5489 (time (decode-time)) res)
5490 (if (< r 1)
5491 (current-time)
5492 (setq res
5493 (apply 'encode-time
5494 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5495 (nthcdr 2 time))))
5496 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5497 (seconds-to-time (- (org-float-time res) (* r 60)))
5498 res))))
5500 (defun org-today ()
5501 "Return today date, considering `org-extend-today-until'."
5502 (time-to-days
5503 (time-subtract (current-time)
5504 (list 0 (* 3600 org-extend-today-until) 0))))
5506 ;;;; Font-Lock stuff, including the activators
5508 (defvar org-mouse-map (make-sparse-keymap))
5509 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5510 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5511 (when org-mouse-1-follows-link
5512 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5513 (when org-tab-follows-link
5514 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5515 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5517 (require 'font-lock)
5519 (defconst org-non-link-chars "]\t\n\r<>")
5520 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5521 "shell" "elisp" "doi" "message"))
5522 (defvar org-link-types-re nil
5523 "Matches a link that has a url-like prefix like \"http:\"")
5524 (defvar org-link-re-with-space nil
5525 "Matches a link with spaces, optional angular brackets around it.")
5526 (defvar org-link-re-with-space2 nil
5527 "Matches a link with spaces, optional angular brackets around it.")
5528 (defvar org-link-re-with-space3 nil
5529 "Matches a link with spaces, only for internal part in bracket links.")
5530 (defvar org-angle-link-re nil
5531 "Matches link with angular brackets, spaces are allowed.")
5532 (defvar org-plain-link-re nil
5533 "Matches plain link, without spaces.")
5534 (defvar org-bracket-link-regexp nil
5535 "Matches a link in double brackets.")
5536 (defvar org-bracket-link-analytic-regexp nil
5537 "Regular expression used to analyze links.
5538 Here is what the match groups contain after a match:
5539 1: http:
5540 2: http
5541 3: path
5542 4: [desc]
5543 5: desc")
5544 (defvar org-bracket-link-analytic-regexp++ nil
5545 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5546 (defvar org-any-link-re nil
5547 "Regular expression matching any link.")
5549 (defconst org-match-sexp-depth 3
5550 "Number of stacked braces for sub/superscript matching.")
5552 (defun org-create-multibrace-regexp (left right n)
5553 "Create a regular expression which will match a balanced sexp.
5554 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5555 as single character strings.
5556 The regexp returned will match the entire expression including the
5557 delimiters. It will also define a single group which contains the
5558 match except for the outermost delimiters. The maximum depth of
5559 stacked delimiters is N. Escaping delimiters is not possible."
5560 (let* ((nothing (concat "[^" left right "]*?"))
5561 (or "\\|")
5562 (re nothing)
5563 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5564 (while (> n 1)
5565 (setq n (1- n)
5566 re (concat re or next)
5567 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5568 (concat left "\\(" re "\\)" right)))
5570 (defvar org-match-substring-regexp
5571 (concat
5572 "\\(\\S-\\)\\([_^]\\)\\("
5573 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5574 "\\|"
5575 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5576 "\\|"
5577 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5578 "The regular expression matching a sub- or superscript.")
5580 (defvar org-match-substring-with-braces-regexp
5581 (concat
5582 "\\(\\S-\\)\\([_^]\\)\\("
5583 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5584 "\\)")
5585 "The regular expression matching a sub- or superscript, forcing braces.")
5587 (defun org-make-link-regexps ()
5588 "Update the link regular expressions.
5589 This should be called after the variable `org-link-types' has changed."
5590 (setq org-link-types-re
5591 (concat
5592 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5593 org-link-re-with-space
5594 (concat
5595 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5596 "\\([^" org-non-link-chars " ]"
5597 "[^" org-non-link-chars "]*"
5598 "[^" org-non-link-chars " ]\\)>?")
5599 org-link-re-with-space2
5600 (concat
5601 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5602 "\\([^" org-non-link-chars " ]"
5603 "[^\t\n\r]*"
5604 "[^" org-non-link-chars " ]\\)>?")
5605 org-link-re-with-space3
5606 (concat
5607 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5608 "\\([^" org-non-link-chars " ]"
5609 "[^\t\n\r]*\\)")
5610 org-angle-link-re
5611 (concat
5612 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5613 "\\([^" org-non-link-chars " ]"
5614 "[^" org-non-link-chars "]*"
5615 "\\)>")
5616 org-plain-link-re
5617 (concat
5618 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5619 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5620 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5621 org-bracket-link-regexp
5622 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5623 org-bracket-link-analytic-regexp
5624 (concat
5625 "\\[\\["
5626 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5627 "\\([^]]+\\)"
5628 "\\]"
5629 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5630 "\\]")
5631 org-bracket-link-analytic-regexp++
5632 (concat
5633 "\\[\\["
5634 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5635 "\\([^]]+\\)"
5636 "\\]"
5637 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5638 "\\]")
5639 org-any-link-re
5640 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5641 org-angle-link-re "\\)\\|\\("
5642 org-plain-link-re "\\)")))
5644 (org-make-link-regexps)
5646 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5647 "Regular expression for fast time stamp matching.")
5648 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5649 "Regular expression for fast time stamp matching.")
5650 (defconst org-ts-regexp0
5651 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5652 "Regular expression matching time strings for analysis.
5653 This one does not require the space after the date, so it can be used
5654 on a string that terminates immediately after the date.")
5655 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5656 "Regular expression matching time strings for analysis.")
5657 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5658 "Regular expression matching time stamps, with groups.")
5659 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5660 "Regular expression matching time stamps (also [..]), with groups.")
5661 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5662 "Regular expression matching a time stamp range.")
5663 (defconst org-tr-regexp-both
5664 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5665 "Regular expression matching a time stamp range.")
5666 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5667 org-ts-regexp "\\)?")
5668 "Regular expression matching a time stamp or time stamp range.")
5669 (defconst org-tsr-regexp-both
5670 (concat org-ts-regexp-both "\\(--?-?"
5671 org-ts-regexp-both "\\)?")
5672 "Regular expression matching a time stamp or time stamp range.
5673 The time stamps may be either active or inactive.")
5675 (defvar org-emph-face nil)
5677 (defun org-do-emphasis-faces (limit)
5678 "Run through the buffer and add overlays to emphasized strings."
5679 (let (rtn a)
5680 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5681 (if (not (= (char-after (match-beginning 3))
5682 (char-after (match-beginning 4))))
5683 (progn
5684 (setq rtn t)
5685 (setq a (assoc (match-string 3) org-emphasis-alist))
5686 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5687 'face
5688 (nth 1 a))
5689 (and (nth 4 a)
5690 (org-remove-flyspell-overlays-in
5691 (match-beginning 0) (match-end 0)))
5692 (add-text-properties (match-beginning 2) (match-end 2)
5693 '(font-lock-multiline t org-emphasis t))
5694 (when org-hide-emphasis-markers
5695 (add-text-properties (match-end 4) (match-beginning 5)
5696 '(invisible org-link))
5697 (add-text-properties (match-beginning 3) (match-end 3)
5698 '(invisible org-link)))))
5699 (backward-char 1))
5700 rtn))
5702 (defun org-emphasize (&optional char)
5703 "Insert or change an emphasis, i.e. a font like bold or italic.
5704 If there is an active region, change that region to a new emphasis.
5705 If there is no region, just insert the marker characters and position
5706 the cursor between them.
5707 CHAR should be the marker character. If it is a space, it means to
5708 remove the emphasis of the selected region.
5709 If CHAR is not given (for example in an interactive call) it will be
5710 prompted for."
5711 (interactive)
5712 (let ((erc org-emphasis-regexp-components)
5713 (prompt "")
5714 (string "") beg end move c s)
5715 (if (org-region-active-p)
5716 (setq beg (region-beginning) end (region-end)
5717 string (buffer-substring beg end))
5718 (setq move t))
5720 (unless char
5721 (message "Emphasis marker or tag: [%s]"
5722 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5723 (setq char (read-char-exclusive)))
5724 (if (equal char ?\ )
5725 (setq s "" move nil)
5726 (unless (assoc (char-to-string char) org-emphasis-alist)
5727 (user-error "No such emphasis marker: \"%c\"" char))
5728 (setq s (char-to-string char)))
5729 (while (and (> (length string) 1)
5730 (equal (substring string 0 1) (substring string -1))
5731 (assoc (substring string 0 1) org-emphasis-alist))
5732 (setq string (substring string 1 -1)))
5733 (setq string (concat s string s))
5734 (if beg (delete-region beg end))
5735 (unless (or (bolp)
5736 (string-match (concat "[" (nth 0 erc) "\n]")
5737 (char-to-string (char-before (point)))))
5738 (insert " "))
5739 (unless (or (eobp)
5740 (string-match (concat "[" (nth 1 erc) "\n]")
5741 (char-to-string (char-after (point)))))
5742 (insert " ") (backward-char 1))
5743 (insert string)
5744 (and move (backward-char 1))))
5746 (defconst org-nonsticky-props
5747 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5749 (defsubst org-rear-nonsticky-at (pos)
5750 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5752 (defun org-activate-plain-links (limit)
5753 "Run through the buffer and add overlays to links."
5754 (let (f hl)
5755 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5756 (not (org-in-src-block-p)))
5757 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5758 (setq f (get-text-property (match-beginning 0) 'face))
5759 (setq hl (org-match-string-no-properties 0))
5760 (if (or (eq f 'org-tag)
5761 (and (listp f) (memq 'org-tag f)))
5763 (add-text-properties (match-beginning 0) (match-end 0)
5764 (list 'mouse-face 'highlight
5765 'face 'org-link
5766 'htmlize-link `(:uri ,hl)
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 0)))
5769 t)))
5771 (defun org-activate-code (limit)
5772 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5773 (progn
5774 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5775 (remove-text-properties (match-beginning 0) (match-end 0)
5776 '(display t invisible t intangible t))
5777 t)))
5779 (defcustom org-src-fontify-natively nil
5780 "When non-nil, fontify code in code blocks."
5781 :type 'boolean
5782 :version "24.1"
5783 :group 'org-appearance
5784 :group 'org-babel)
5786 (defcustom org-allow-promoting-top-level-subtree nil
5787 "When non-nil, allow promoting a top level subtree.
5788 The leading star of the top level headline will be replaced
5789 by a #."
5790 :type 'boolean
5791 :version "24.1"
5792 :group 'org-appearance)
5794 (defun org-fontify-meta-lines-and-blocks (limit)
5795 (condition-case nil
5796 (org-fontify-meta-lines-and-blocks-1 limit)
5797 (error (message "org-mode fontification error"))))
5799 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5800 "Fontify #+ lines and blocks."
5801 (let ((case-fold-search t))
5802 (if (re-search-forward
5803 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5804 limit t)
5805 (let ((beg (match-beginning 0))
5806 (block-start (match-end 0))
5807 (block-end nil)
5808 (lang (match-string 7))
5809 (beg1 (line-beginning-position 2))
5810 (dc1 (downcase (match-string 2)))
5811 (dc3 (downcase (match-string 3)))
5812 end end1 quoting block-type ovl)
5813 (cond
5814 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5815 ;; a single line of backend-specific content
5816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5817 (remove-text-properties (match-beginning 0) (match-end 0)
5818 '(display t invisible t intangible t))
5819 (add-text-properties (match-beginning 1) (match-end 3)
5820 '(font-lock-fontified t face org-meta-line))
5821 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5822 '(font-lock-fontified t face org-block))
5823 ; for backend-specific code
5825 ((and (match-end 4) (equal dc3 "+begin"))
5826 ;; Truly a block
5827 (setq block-type (downcase (match-string 5))
5828 quoting (member block-type org-protecting-blocks))
5829 (when (re-search-forward
5830 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5831 nil t) ;; on purpose, we look further than LIMIT
5832 (setq end (min (point-max) (match-end 0))
5833 end1 (min (point-max) (1- (match-beginning 0))))
5834 (setq block-end (match-beginning 0))
5835 (when quoting
5836 (remove-text-properties beg end
5837 '(display t invisible t intangible t)))
5838 (add-text-properties
5839 beg end
5840 '(font-lock-fontified t font-lock-multiline t))
5841 (add-text-properties beg beg1 '(face org-meta-line))
5842 (add-text-properties end1 (min (point-max) (1+ end))
5843 '(face org-meta-line)) ; for end_src
5844 (cond
5845 ((and lang (not (string= lang "")) org-src-fontify-natively)
5846 (org-src-font-lock-fontify-block lang block-start block-end)
5847 ;; remove old background overlays
5848 (mapc (lambda (ov)
5849 (if (eq (overlay-get ov 'face) 'org-block-background)
5850 (delete-overlay ov)))
5851 (overlays-at (/ (+ beg1 block-end) 2)))
5852 ;; add a background overlay
5853 (setq ovl (make-overlay beg1 block-end))
5854 (overlay-put ovl 'face 'org-block-background)
5855 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5856 (quoting
5857 (add-text-properties beg1 (min (point-max) (1+ end1))
5858 '(face org-block))) ; end of source block
5859 ((not org-fontify-quote-and-verse-blocks))
5860 ((string= block-type "quote")
5861 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5862 ((string= block-type "verse")
5863 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5864 (add-text-properties beg beg1 '(face org-block-begin-line))
5865 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5866 '(face org-block-end-line))
5868 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5869 (add-text-properties
5870 beg (match-end 3)
5871 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5872 '(font-lock-fontified t invisible t)
5873 '(font-lock-fontified t face org-document-info-keyword)))
5874 (add-text-properties
5875 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5876 (if (string-equal dc1 "+title:")
5877 '(font-lock-fontified t face org-document-title)
5878 '(font-lock-fontified t face org-document-info))))
5879 ((or (equal dc1 "+results")
5880 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5881 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5882 "+call:" "+header:" "+headers:" "+name:"))
5883 (and (match-end 4) (equal dc3 "+attr")))
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face org-meta-line))
5888 ((member dc3 '(" " ""))
5889 (add-text-properties
5890 beg (match-end 0)
5891 '(font-lock-fontified t face font-lock-comment-face)))
5892 ((not (member (char-after beg) '(?\ ?\t)))
5893 ;; just any other in-buffer setting, but not indented
5894 (add-text-properties
5895 beg (match-end 0)
5896 '(font-lock-fontified t face org-meta-line))
5898 (t nil))))))
5900 (defun org-activate-angle-links (limit)
5901 "Run through the buffer and add overlays to links."
5902 (if (and (re-search-forward org-angle-link-re limit t)
5903 (not (org-in-src-block-p)))
5904 (progn
5905 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5906 (add-text-properties (match-beginning 0) (match-end 0)
5907 (list 'mouse-face 'highlight
5908 'keymap org-mouse-map))
5909 (org-rear-nonsticky-at (match-end 0))
5910 t)))
5912 (defun org-activate-footnote-links (limit)
5913 "Run through the buffer and add overlays to footnotes."
5914 (let ((fn (org-footnote-next-reference-or-definition limit)))
5915 (when fn
5916 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5917 (org-remove-flyspell-overlays-in beg end)
5918 (add-text-properties beg end
5919 (list 'mouse-face 'highlight
5920 'keymap org-mouse-map
5921 'help-echo
5922 (if (= (point-at-bol) beg)
5923 "Footnote definition"
5924 "Footnote reference")
5925 'font-lock-fontified t
5926 'font-lock-multiline t
5927 'face 'org-footnote))))))
5929 (defun org-activate-bracket-links (limit)
5930 "Run through the buffer and add overlays to bracketed links."
5931 (if (and (re-search-forward org-bracket-link-regexp limit t)
5932 (not (org-in-src-block-p)))
5933 (let* ((hl (org-match-string-no-properties 1))
5934 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5935 (ip (org-maybe-intangible
5936 (list 'invisible 'org-link
5937 'keymap org-mouse-map 'mouse-face 'highlight
5938 'font-lock-multiline t 'help-echo help
5939 'htmlize-link `(:uri ,hl))))
5940 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5941 'font-lock-multiline t 'help-echo help
5942 'htmlize-link `(:uri ,hl))))
5943 ;; We need to remove the invisible property here. Table narrowing
5944 ;; may have made some of this invisible.
5945 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5946 (remove-text-properties (match-beginning 0) (match-end 0)
5947 '(invisible nil))
5948 (if (match-end 3)
5949 (progn
5950 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5951 (org-rear-nonsticky-at (match-beginning 3))
5952 (add-text-properties (match-beginning 3) (match-end 3) vp)
5953 (org-rear-nonsticky-at (match-end 3))
5954 (add-text-properties (match-end 3) (match-end 0) ip)
5955 (org-rear-nonsticky-at (match-end 0)))
5956 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5957 (org-rear-nonsticky-at (match-beginning 1))
5958 (add-text-properties (match-beginning 1) (match-end 1) vp)
5959 (org-rear-nonsticky-at (match-end 1))
5960 (add-text-properties (match-end 1) (match-end 0) ip)
5961 (org-rear-nonsticky-at (match-end 0)))
5962 t)))
5964 (defun org-activate-dates (limit)
5965 "Run through the buffer and add overlays to dates."
5966 (if (and (re-search-forward org-tsr-regexp-both limit t)
5967 (not (equal (char-before (match-beginning 0)) 91)))
5968 (progn
5969 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5970 (add-text-properties (match-beginning 0) (match-end 0)
5971 (list 'mouse-face 'highlight
5972 'keymap org-mouse-map))
5973 (org-rear-nonsticky-at (match-end 0))
5974 (when org-display-custom-times
5975 (if (match-end 3)
5976 (org-display-custom-time (match-beginning 3) (match-end 3)))
5977 (org-display-custom-time (match-beginning 1) (match-end 1)))
5978 t)))
5980 (defvar org-target-link-regexp nil
5981 "Regular expression matching radio targets in plain text.")
5982 (make-variable-buffer-local 'org-target-link-regexp)
5983 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5984 "Regular expression matching a link target.")
5985 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5986 "Regular expression matching a radio target.")
5987 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5988 "Regular expression matching any target.")
5990 (defun org-activate-target-links (limit)
5991 "Run through the buffer and add overlays to target matches."
5992 (when org-target-link-regexp
5993 (let ((case-fold-search t))
5994 (if (re-search-forward org-target-link-regexp limit t)
5995 (progn
5996 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5997 (add-text-properties (match-beginning 0) (match-end 0)
5998 (list 'mouse-face 'highlight
5999 'keymap org-mouse-map
6000 'help-echo "Radio target link"
6001 'org-linked-text t))
6002 (org-rear-nonsticky-at (match-end 0))
6003 t)))))
6005 (defun org-update-radio-target-regexp ()
6006 "Find all radio targets in this file and update the regular expression."
6007 (interactive)
6008 (when (memq 'radio org-activate-links)
6009 (setq org-target-link-regexp
6010 (org-make-target-link-regexp (org-all-targets 'radio)))
6011 (org-restart-font-lock)))
6013 (defun org-hide-wide-columns (limit)
6014 (let (s e)
6015 (setq s (text-property-any (point) (or limit (point-max))
6016 'org-cwidth t))
6017 (when s
6018 (setq e (next-single-property-change s 'org-cwidth))
6019 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6020 (goto-char e)
6021 t)))
6023 (defvar org-latex-and-related-regexp nil
6024 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6025 (defvar org-match-substring-regexp)
6026 (defvar org-match-substring-with-braces-regexp)
6028 (defun org-compute-latex-and-related-regexp ()
6029 "Compute regular expression for LaTeX, entities and sub/superscript.
6030 Result depends on variable `org-highlight-latex-and-related'."
6031 (org-set-local
6032 'org-latex-and-related-regexp
6033 (let* ((re-sub
6034 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6035 ((eq org-use-sub-superscripts '{})
6036 (list org-match-substring-with-braces-regexp))
6037 (org-use-sub-superscripts (list org-match-substring-regexp))))
6038 (re-latex
6039 (when (memq 'latex org-highlight-latex-and-related)
6040 (let ((matchers (plist-get org-format-latex-options :matchers)))
6041 (delq nil
6042 (mapcar (lambda (x)
6043 (and (member (car x) matchers) (nth 1 x)))
6044 org-latex-regexps)))))
6045 (re-entities
6046 (when (memq 'entities org-highlight-latex-and-related)
6047 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6048 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6050 (defun org-do-latex-and-related (limit)
6051 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6052 LIMIT bounds the search for syntax to highlight. Stop at first
6053 highlighted object, if any. Return t if some highlighting was
6054 done, nil otherwise."
6055 (when (org-string-nw-p org-latex-and-related-regexp)
6056 (catch 'found
6057 (while (re-search-forward org-latex-and-related-regexp limit t)
6058 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6059 'face))
6060 '(org-code org-verbatim underline))
6061 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6062 '(?_ ?^))
6064 0)))
6065 (font-lock-prepend-text-property
6066 (+ offset (match-beginning 0)) (match-end 0)
6067 'face 'org-latex-and-related)
6068 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6069 '(font-lock-multiline t)))
6070 (throw 'found t)))
6071 nil)))
6073 (defun org-restart-font-lock ()
6074 "Restart `font-lock-mode', to force refontification."
6075 (when (and (boundp 'font-lock-mode) font-lock-mode)
6076 (font-lock-mode -1)
6077 (font-lock-mode 1)))
6079 (defun org-all-targets (&optional radio)
6080 "Return a list of all targets in this file.
6081 When optional argument RADIO is non-nil, only find radio
6082 targets."
6083 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6084 (save-excursion
6085 (goto-char (point-min))
6086 (while (re-search-forward re nil t)
6087 ;; Make sure point is really within the object.
6088 (backward-char)
6089 (let ((obj (org-element-context)))
6090 (when (memq (org-element-type obj) '(radio-target target))
6091 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6092 rtn)))
6094 (defun org-make-target-link-regexp (targets)
6095 "Make regular expression matching all strings in TARGETS.
6096 The regular expression finds the targets also if there is a line break
6097 between words."
6098 (and targets
6099 (concat
6100 "\\<\\("
6101 (mapconcat
6102 (lambda (x)
6103 (setq x (regexp-quote x))
6104 (while (string-match " +" x)
6105 (setq x (replace-match "\\s-+" t t x)))
6107 targets
6108 "\\|")
6109 "\\)\\>")))
6111 (defun org-activate-tags (limit)
6112 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6113 (progn
6114 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6115 (add-text-properties (match-beginning 1) (match-end 1)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map))
6118 (org-rear-nonsticky-at (match-end 1))
6119 t)))
6121 (defun org-outline-level ()
6122 "Compute the outline level of the heading at point.
6123 If this is called at a normal headline, the level is the number of stars.
6124 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6125 (save-excursion
6126 (if (not (condition-case nil
6127 (org-back-to-heading t)
6128 (error nil)))
6130 (looking-at org-outline-regexp)
6131 (1- (- (match-end 0) (match-beginning 0))))))
6133 (defvar org-font-lock-keywords nil)
6135 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6136 "Regular expression matching a property line.")
6138 (defvar org-font-lock-hook nil
6139 "Functions to be called for special font lock stuff.")
6141 (defvar org-font-lock-set-keywords-hook nil
6142 "Functions that can manipulate `org-font-lock-extra-keywords'.
6143 This is called after `org-font-lock-extra-keywords' is defined, but before
6144 it is installed to be used by font lock. This can be useful if something
6145 needs to be inserted at a specific position in the font-lock sequence.")
6147 (defun org-font-lock-hook (limit)
6148 "Run `org-font-lock-hook' within LIMIT."
6149 (run-hook-with-args 'org-font-lock-hook limit))
6151 (defun org-set-font-lock-defaults ()
6152 "Set font lock defaults for the current buffer."
6153 (let* ((em org-fontify-emphasized-text)
6154 (lk org-activate-links)
6155 (org-font-lock-extra-keywords
6156 (list
6157 ;; Call the hook
6158 '(org-font-lock-hook)
6159 ;; Headlines
6160 `(,(if org-fontify-whole-heading-line
6161 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6162 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6163 (1 (org-get-level-face 1))
6164 (2 (org-get-level-face 2))
6165 (3 (org-get-level-face 3)))
6166 ;; Table lines
6167 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6168 (1 'org-table t))
6169 ;; Table internals
6170 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6171 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6172 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6173 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6174 ;; Drawers
6175 (list org-drawer-regexp '(0 'org-special-keyword t))
6176 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6177 ;; Properties
6178 (list org-property-re
6179 '(1 'org-special-keyword t)
6180 '(3 'org-property-value t))
6181 ;; Links
6182 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6183 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6184 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6185 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6186 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6187 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6188 (if (memq 'footnote lk) '(org-activate-footnote-links))
6189 ;; Targets.
6190 (list org-any-target-regexp '(0 'org-target t))
6191 ;; Diary sexps.
6192 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6193 ;; Macro
6194 '("{{{.+}}}" (0 'org-macro t))
6195 '(org-hide-wide-columns (0 nil append))
6196 ;; TODO keyword
6197 (list (format org-heading-keyword-regexp-format
6198 org-todo-regexp)
6199 '(2 (org-get-todo-face 2) t))
6200 ;; DONE
6201 (if org-fontify-done-headline
6202 (list (format org-heading-keyword-regexp-format
6203 (concat
6204 "\\(?:"
6205 (mapconcat 'regexp-quote org-done-keywords "\\|")
6206 "\\)"))
6207 '(2 'org-headline-done t))
6208 nil)
6209 ;; Priorities
6210 '(org-font-lock-add-priority-faces)
6211 ;; Tags
6212 '(org-font-lock-add-tag-faces)
6213 ;; Tags groups
6214 (if (and org-group-tags org-tag-groups-alist)
6215 (list (concat org-outline-regexp-bol ".+\\(:"
6216 (regexp-opt (mapcar 'car org-tag-groups-alist))
6217 ":\\).*$")
6218 '(1 'org-tag-group prepend)))
6219 ;; Special keywords
6220 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6221 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6222 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6223 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6224 ;; Emphasis
6225 (if em
6226 (if (featurep 'xemacs)
6227 '(org-do-emphasis-faces (0 nil append))
6228 '(org-do-emphasis-faces)))
6229 ;; Checkboxes
6230 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6231 1 'org-checkbox prepend)
6232 (if (cdr (assq 'checkbox org-list-automatic-rules))
6233 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6234 (0 (org-get-checkbox-statistics-face) t)))
6235 ;; Description list items
6236 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6237 1 'org-list-dt prepend)
6238 ;; ARCHIVEd headings
6239 (list (concat
6240 org-outline-regexp-bol
6241 "\\(.*:" org-archive-tag ":.*\\)")
6242 '(1 'org-archived prepend))
6243 ;; Specials
6244 '(org-do-latex-and-related)
6245 '(org-fontify-entities)
6246 '(org-raise-scripts)
6247 ;; Code
6248 '(org-activate-code (1 'org-code t))
6249 ;; COMMENT
6250 (list (format org-heading-keyword-regexp-format
6251 (concat "\\("
6252 org-comment-string "\\|" org-quote-string
6253 "\\)"))
6254 '(2 'org-special-keyword t))
6255 ;; Blocks and meta lines
6256 '(org-fontify-meta-lines-and-blocks))))
6257 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6258 (run-hooks 'org-font-lock-set-keywords-hook)
6259 ;; Now set the full font-lock-keywords
6260 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6261 (org-set-local 'font-lock-defaults
6262 '(org-font-lock-keywords t nil nil backward-paragraph))
6263 (kill-local-variable 'font-lock-keywords) nil))
6265 (defun org-toggle-pretty-entities ()
6266 "Toggle the composition display of entities as UTF8 characters."
6267 (interactive)
6268 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6269 (org-restart-font-lock)
6270 (if org-pretty-entities
6271 (message "Entities are now displayed as UTF8 characters")
6272 (save-restriction
6273 (widen)
6274 (org-decompose-region (point-min) (point-max))
6275 (message "Entities are now displayed as plain text"))))
6277 (defvar org-custom-properties-overlays nil
6278 "List of overlays used for custom properties.")
6279 (make-variable-buffer-local 'org-custom-properties-overlays)
6281 (defun org-toggle-custom-properties-visibility ()
6282 "Display or hide properties in `org-custom-properties'."
6283 (interactive)
6284 (if org-custom-properties-overlays
6285 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6286 (setq org-custom-properties-overlays nil))
6287 (unless (not org-custom-properties)
6288 (save-excursion
6289 (save-restriction
6290 (widen)
6291 (goto-char (point-min))
6292 (while (re-search-forward org-property-re nil t)
6293 (mapc (lambda(p)
6294 (when (equal p (substring (match-string 1) 1 -1))
6295 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6296 (overlay-put o 'invisible t)
6297 (overlay-put o 'org-custom-property t)
6298 (push o org-custom-properties-overlays))))
6299 org-custom-properties)))))))
6301 (defun org-fontify-entities (limit)
6302 "Find an entity to fontify."
6303 (let (ee)
6304 (when org-pretty-entities
6305 (catch 'match
6306 (while (re-search-forward
6307 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6308 limit t)
6309 (if (and (not (org-in-indented-comment-line))
6310 (setq ee (org-entity-get (match-string 1)))
6311 (= (length (nth 6 ee)) 1))
6312 (let*
6313 ((end (if (equal (match-string 2) "{}")
6314 (match-end 2)
6315 (match-end 1))))
6316 (add-text-properties
6317 (match-beginning 0) end
6318 (list 'font-lock-fontified t))
6319 (compose-region (match-beginning 0) end
6320 (nth 6 ee) nil)
6321 (backward-char 1)
6322 (throw 'match t))))
6323 nil))))
6325 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6326 "Fontify string S like in Org-mode."
6327 (with-temp-buffer
6328 (insert s)
6329 (let ((org-odd-levels-only odd-levels))
6330 (org-mode)
6331 (font-lock-fontify-buffer)
6332 (buffer-string))))
6334 (defvar org-m nil)
6335 (defvar org-l nil)
6336 (defvar org-f nil)
6337 (defun org-get-level-face (n)
6338 "Get the right face for match N in font-lock matching of headlines."
6339 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6340 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6341 (if org-cycle-level-faces
6342 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6343 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6344 (cond
6345 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6346 ((eq n 2) org-f)
6347 (t (if org-level-color-stars-only nil org-f))))
6350 (defun org-get-todo-face (kwd)
6351 "Get the right face for a TODO keyword KWD.
6352 If KWD is a number, get the corresponding match group."
6353 (if (numberp kwd) (setq kwd (match-string kwd)))
6354 (or (org-face-from-face-or-color
6355 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6356 (and (member kwd org-done-keywords) 'org-done)
6357 'org-todo))
6359 (defun org-face-from-face-or-color (context inherit face-or-color)
6360 "Create a face list that inherits INHERIT, but sets the foreground color.
6361 When FACE-OR-COLOR is not a string, just return it."
6362 (if (stringp face-or-color)
6363 (list :inherit inherit
6364 (cdr (assoc context org-faces-easy-properties))
6365 face-or-color)
6366 face-or-color))
6368 (defun org-font-lock-add-tag-faces (limit)
6369 "Add the special tag faces."
6370 (when (and org-tag-faces org-tags-special-faces-re)
6371 (while (re-search-forward org-tags-special-faces-re limit t)
6372 (add-text-properties (match-beginning 1) (match-end 1)
6373 (list 'face (org-get-tag-face 1)
6374 'font-lock-fontified t))
6375 (backward-char 1))))
6377 (defun org-font-lock-add-priority-faces (limit)
6378 "Add the special priority faces."
6379 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6380 (when (save-match-data (org-at-heading-p))
6381 (add-text-properties
6382 (match-beginning 0) (match-end 0)
6383 (list 'face (or (org-face-from-face-or-color
6384 'priority 'org-priority
6385 (cdr (assoc (char-after (match-beginning 1))
6386 org-priority-faces)))
6387 'org-priority)
6388 'font-lock-fontified t)))))
6390 (defun org-get-tag-face (kwd)
6391 "Get the right face for a TODO keyword KWD.
6392 If KWD is a number, get the corresponding match group."
6393 (if (numberp kwd) (setq kwd (match-string kwd)))
6394 (or (org-face-from-face-or-color
6395 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6396 'org-tag))
6398 (defun org-unfontify-region (beg end &optional maybe_loudly)
6399 "Remove fontification and activation overlays from links."
6400 (font-lock-default-unfontify-region beg end)
6401 (let* ((buffer-undo-list t)
6402 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6403 (inhibit-modification-hooks t)
6404 deactivate-mark buffer-file-name buffer-file-truename)
6405 (org-decompose-region beg end)
6406 (remove-text-properties beg end
6407 '(mouse-face t keymap t org-linked-text t
6408 invisible t intangible t
6409 org-no-flyspell t org-emphasis t))
6410 (org-remove-font-lock-display-properties beg end)))
6412 (defconst org-script-display '(((raise -0.3) (height 0.7))
6413 ((raise 0.3) (height 0.7))
6414 ((raise -0.5))
6415 ((raise 0.5)))
6416 "Display properties for showing superscripts and subscripts.")
6418 (defun org-remove-font-lock-display-properties (beg end)
6419 "Remove specific display properties that have been added by font lock.
6420 The will remove the raise properties that are used to show superscripts
6421 and subscripts."
6422 (let (next prop)
6423 (while (< beg end)
6424 (setq next (next-single-property-change beg 'display nil end)
6425 prop (get-text-property beg 'display))
6426 (if (member prop org-script-display)
6427 (put-text-property beg next 'display nil))
6428 (setq beg next))))
6430 (defun org-raise-scripts (limit)
6431 "Add raise properties to sub/superscripts."
6432 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6433 (if (re-search-forward
6434 (if (eq org-use-sub-superscripts t)
6435 org-match-substring-regexp
6436 org-match-substring-with-braces-regexp)
6437 limit t)
6438 (let* ((pos (point)) table-p comment-p
6439 (mpos (match-beginning 3))
6440 (emph-p (get-text-property mpos 'org-emphasis))
6441 (link-p (get-text-property mpos 'mouse-face))
6442 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6443 (goto-char (point-at-bol))
6444 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6445 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6446 (goto-char pos)
6447 ;; Handle a_b^c
6448 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6449 (if (or comment-p emph-p link-p keyw-p)
6451 (put-text-property (match-beginning 3) (match-end 0)
6452 'display
6453 (if (equal (char-after (match-beginning 2)) ?^)
6454 (nth (if table-p 3 1) org-script-display)
6455 (nth (if table-p 2 0) org-script-display)))
6456 (add-text-properties (match-beginning 2) (match-end 2)
6457 (list 'invisible t
6458 'org-dwidth t 'org-dwidth-n 1))
6459 (if (and (eq (char-after (match-beginning 3)) ?{)
6460 (eq (char-before (match-end 3)) ?}))
6461 (progn
6462 (add-text-properties
6463 (match-beginning 3) (1+ (match-beginning 3))
6464 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6465 (add-text-properties
6466 (1- (match-end 3)) (match-end 3)
6467 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6468 t)))))
6470 ;;;; Visibility cycling, including org-goto and indirect buffer
6472 ;;; Cycling
6474 (defvar org-cycle-global-status nil)
6475 (make-variable-buffer-local 'org-cycle-global-status)
6476 (put 'org-cycle-global-status 'org-state t)
6477 (defvar org-cycle-subtree-status nil)
6478 (make-variable-buffer-local 'org-cycle-subtree-status)
6479 (put 'org-cycle-subtree-status 'org-state t)
6481 (defvar org-inlinetask-min-level)
6483 ;;;###autoload
6484 (defun org-cycle (&optional arg)
6485 "TAB-action and visibility cycling for Org-mode.
6487 This is the command invoked in Org-mode by the TAB key. Its main purpose
6488 is outline visibility cycling, but it also invokes other actions
6489 in special contexts.
6491 - When this function is called with a prefix argument, rotate the entire
6492 buffer through 3 states (global cycling)
6493 1. OVERVIEW: Show only top-level headlines.
6494 2. CONTENTS: Show all headlines of all levels, but no body text.
6495 3. SHOW ALL: Show everything.
6496 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6497 determined by the variable `org-startup-folded', and by any VISIBILITY
6498 properties in the buffer.
6499 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6500 including any drawers.
6502 - When inside a table, re-align the table and move to the next field.
6504 - When point is at the beginning of a headline, rotate the subtree started
6505 by this line through 3 different states (local cycling)
6506 1. FOLDED: Only the main headline is shown.
6507 2. CHILDREN: The main headline and the direct children are shown.
6508 From this state, you can move to one of the children
6509 and zoom in further.
6510 3. SUBTREE: Show the entire subtree, including body text.
6511 If there is no subtree, switch directly from CHILDREN to FOLDED.
6513 - When point is at the beginning of an empty headline and the variable
6514 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6515 of the headline by demoting and promoting it to likely levels. This
6516 speeds up creation document structure by pressing TAB once or several
6517 times right after creating a new headline.
6519 - When there is a numeric prefix, go up to a heading with level ARG, do
6520 a `show-subtree' and return to the previous cursor position. If ARG
6521 is negative, go up that many levels.
6523 - When point is not at the beginning of a headline, execute the global
6524 binding for TAB, which is re-indenting the line. See the option
6525 `org-cycle-emulate-tab' for details.
6527 - Special case: if point is at the beginning of the buffer and there is
6528 no headline in line 1, this function will act as if called with prefix arg
6529 (C-u TAB, same as S-TAB) also when called without prefix arg.
6530 But only if also the variable `org-cycle-global-at-bob' is t."
6531 (interactive "P")
6532 (org-load-modules-maybe)
6533 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6534 (and org-cycle-level-after-item/entry-creation
6535 (or (org-cycle-level)
6536 (org-cycle-item-indentation))))
6537 (let* (message-log-max ; Don't populate the *Messages* buffer
6538 (limit-level
6539 (or org-cycle-max-level
6540 (and (boundp 'org-inlinetask-min-level)
6541 org-inlinetask-min-level
6542 (1- org-inlinetask-min-level))))
6543 (nstars (and limit-level
6544 (if org-odd-levels-only
6545 (and limit-level (1- (* limit-level 2)))
6546 limit-level)))
6547 (org-outline-regexp
6548 (if (not (derived-mode-p 'org-mode))
6549 outline-regexp
6550 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6551 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6552 (not (looking-at org-outline-regexp))))
6553 (org-cycle-hook
6554 (if bob-special
6555 (delq 'org-optimize-window-after-visibility-change
6556 (copy-sequence org-cycle-hook))
6557 org-cycle-hook))
6558 (pos (point)))
6560 (if (or bob-special (equal arg '(4)))
6561 ;; special case: use global cycling
6562 (setq arg t))
6564 (cond
6566 ((equal arg '(16))
6567 (setq last-command 'dummy)
6568 (org-set-startup-visibility)
6569 (message "Startup visibility, plus VISIBILITY properties"))
6571 ((equal arg '(64))
6572 (show-all)
6573 (message "Entire buffer visible, including drawers"))
6575 ;; Table: enter it or move to the next field.
6576 ((org-at-table-p 'any)
6577 (if (org-at-table.el-p)
6578 (message "Use C-c ' to edit table.el tables")
6579 (if arg (org-table-edit-field t)
6580 (org-table-justify-field-maybe)
6581 (call-interactively 'org-table-next-field))))
6583 ((run-hook-with-args-until-success
6584 'org-tab-after-check-for-table-hook))
6586 ;; Global cycling: delegate to `org-cycle-internal-global'.
6587 ((eq arg t) (org-cycle-internal-global))
6589 ;; Drawers: delegate to `org-flag-drawer'.
6590 ((and org-drawers org-drawer-regexp
6591 (save-excursion
6592 (beginning-of-line 1)
6593 (looking-at org-drawer-regexp)))
6594 (org-flag-drawer ; toggle block visibility
6595 (not (get-char-property (match-end 0) 'invisible))))
6597 ;; Show-subtree, ARG levels up from here.
6598 ((integerp arg)
6599 (save-excursion
6600 (org-back-to-heading)
6601 (outline-up-heading (if (< arg 0) (- arg)
6602 (- (funcall outline-level) arg)))
6603 (org-show-subtree)))
6605 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6606 ((and (featurep 'org-inlinetask)
6607 (org-inlinetask-at-task-p)
6608 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6609 (org-inlinetask-toggle-visibility))
6611 ((org-try-cdlatex-tab))
6613 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6614 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6615 (save-excursion (beginning-of-line 1)
6616 (looking-at org-outline-regexp)))
6617 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6618 (org-cycle-internal-local))
6620 ;; From there: TAB emulation and template completion.
6621 (buffer-read-only (org-back-to-heading))
6623 ((run-hook-with-args-until-success
6624 'org-tab-after-check-for-cycling-hook))
6626 ((org-try-structure-completion))
6628 ((run-hook-with-args-until-success
6629 'org-tab-before-tab-emulation-hook))
6631 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6632 (or (not (bolp))
6633 (not (looking-at org-outline-regexp))))
6634 (call-interactively (global-key-binding "\t")))
6636 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6637 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6638 (or (and (eq org-cycle-emulate-tab 'white)
6639 (= (match-end 0) (point-at-eol)))
6640 (and (eq org-cycle-emulate-tab 'whitestart)
6641 (>= (match-end 0) pos))))
6643 (eq org-cycle-emulate-tab t))
6644 (call-interactively (global-key-binding "\t")))
6646 (t (save-excursion
6647 (org-back-to-heading)
6648 (org-cycle)))))))
6650 (defun org-cycle-internal-global ()
6651 "Do the global cycling action."
6652 ;; Hack to avoid display of messages for .org attachments in Gnus
6653 (let (message-log-max ; Don't populate the *Messages* buffer
6654 (ga (string-match "\\*fontification" (buffer-name))))
6655 (cond
6656 ((and (eq last-command this-command)
6657 (eq org-cycle-global-status 'overview))
6658 ;; We just created the overview - now do table of contents
6659 ;; This can be slow in very large buffers, so indicate action
6660 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6661 (unless ga (message "CONTENTS..."))
6662 (org-content)
6663 (unless ga (message "CONTENTS...done"))
6664 (setq org-cycle-global-status 'contents)
6665 (run-hook-with-args 'org-cycle-hook 'contents))
6667 ((and (eq last-command this-command)
6668 (eq org-cycle-global-status 'contents))
6669 ;; We just showed the table of contents - now show everything
6670 (run-hook-with-args 'org-pre-cycle-hook 'all)
6671 (show-all)
6672 (unless ga (message "SHOW ALL"))
6673 (setq org-cycle-global-status 'all)
6674 (run-hook-with-args 'org-cycle-hook 'all))
6677 ;; Default action: go to overview
6678 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6679 (org-overview)
6680 (unless ga (message "OVERVIEW"))
6681 (setq org-cycle-global-status 'overview)
6682 (run-hook-with-args 'org-cycle-hook 'overview)))))
6684 (defun org-cycle-internal-local ()
6685 "Do the local cycling action."
6686 (let (message-log-max ; Don't populate the *Messages* buffer
6687 (goal-column 0) eoh eol eos has-children children-skipped struct)
6688 ;; First, determine end of headline (EOH), end of subtree or item
6689 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6690 (save-excursion
6691 (if (org-at-item-p)
6692 (progn
6693 (beginning-of-line)
6694 (setq struct (org-list-struct))
6695 (setq eoh (point-at-eol))
6696 (setq eos (org-list-get-item-end-before-blank (point) struct))
6697 (setq has-children (org-list-has-child-p (point) struct)))
6698 (org-back-to-heading)
6699 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6700 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6701 (setq has-children
6702 (or (save-excursion
6703 (let ((level (funcall outline-level)))
6704 (outline-next-heading)
6705 (and (org-at-heading-p t)
6706 (> (funcall outline-level) level))))
6707 (save-excursion
6708 (org-list-search-forward (org-item-beginning-re) eos t)))))
6709 ;; Determine end invisible part of buffer (EOL)
6710 (beginning-of-line 2)
6711 ;; XEmacs doesn't have `next-single-char-property-change'
6712 (if (featurep 'xemacs)
6713 (while (and (not (eobp)) ;; this is like `next-line'
6714 (get-char-property (1- (point)) 'invisible))
6715 (beginning-of-line 2))
6716 (while (and (not (eobp)) ;; this is like `next-line'
6717 (get-char-property (1- (point)) 'invisible))
6718 (goto-char (next-single-char-property-change (point) 'invisible))
6719 (and (eolp) (beginning-of-line 2))))
6720 (setq eol (point)))
6721 ;; Find out what to do next and set `this-command'
6722 (cond
6723 ((= eos eoh)
6724 ;; Nothing is hidden behind this heading
6725 (unless (org-before-first-heading-p)
6726 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6727 (message "EMPTY ENTRY")
6728 (setq org-cycle-subtree-status nil)
6729 (save-excursion
6730 (goto-char eos)
6731 (outline-next-heading)
6732 (if (outline-invisible-p) (org-flag-heading nil))))
6733 ((and (or (>= eol eos)
6734 (not (string-match "\\S-" (buffer-substring eol eos))))
6735 (or has-children
6736 (not (setq children-skipped
6737 org-cycle-skip-children-state-if-no-children))))
6738 ;; Entire subtree is hidden in one line: children view
6739 (unless (org-before-first-heading-p)
6740 (run-hook-with-args 'org-pre-cycle-hook 'children))
6741 (if (org-at-item-p)
6742 (org-list-set-item-visibility (point-at-bol) struct 'children)
6743 (org-show-entry)
6744 (org-with-limited-levels (show-children))
6745 ;; FIXME: This slows down the func way too much.
6746 ;; How keep drawers hidden in subtree anyway?
6747 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6748 ;; (org-cycle-hide-drawers 'subtree))
6750 ;; Fold every list in subtree to top-level items.
6751 (when (eq org-cycle-include-plain-lists 'integrate)
6752 (save-excursion
6753 (org-back-to-heading)
6754 (while (org-list-search-forward (org-item-beginning-re) eos t)
6755 (beginning-of-line 1)
6756 (let* ((struct (org-list-struct))
6757 (prevs (org-list-prevs-alist struct))
6758 (end (org-list-get-bottom-point struct)))
6759 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6760 (org-list-get-all-items (point) struct prevs))
6761 (goto-char (if (< end eos) end eos)))))))
6762 (message "CHILDREN")
6763 (save-excursion
6764 (goto-char eos)
6765 (outline-next-heading)
6766 (if (outline-invisible-p) (org-flag-heading nil)))
6767 (setq org-cycle-subtree-status 'children)
6768 (unless (org-before-first-heading-p)
6769 (run-hook-with-args 'org-cycle-hook 'children)))
6770 ((or children-skipped
6771 (and (eq last-command this-command)
6772 (eq org-cycle-subtree-status 'children)))
6773 ;; We just showed the children, or no children are there,
6774 ;; now show everything.
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6777 (outline-flag-region eoh eos nil)
6778 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6779 (setq org-cycle-subtree-status 'subtree)
6780 (unless (org-before-first-heading-p)
6781 (run-hook-with-args 'org-cycle-hook 'subtree)))
6783 ;; Default action: hide the subtree.
6784 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6785 (outline-flag-region eoh eos t)
6786 (message "FOLDED")
6787 (setq org-cycle-subtree-status 'folded)
6788 (unless (org-before-first-heading-p)
6789 (run-hook-with-args 'org-cycle-hook 'folded))))))
6791 ;;;###autoload
6792 (defun org-global-cycle (&optional arg)
6793 "Cycle the global visibility. For details see `org-cycle'.
6794 With \\[universal-argument] prefix arg, switch to startup visibility.
6795 With a numeric prefix, show all headlines up to that level."
6796 (interactive "P")
6797 (let ((org-cycle-include-plain-lists
6798 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6799 (cond
6800 ((integerp arg)
6801 (show-all)
6802 (hide-sublevels arg)
6803 (setq org-cycle-global-status 'contents))
6804 ((equal arg '(4))
6805 (org-set-startup-visibility)
6806 (message "Startup visibility, plus VISIBILITY properties."))
6808 (org-cycle '(4))))))
6810 (defun org-set-startup-visibility ()
6811 "Set the visibility required by startup options and properties."
6812 (cond
6813 ((eq org-startup-folded t)
6814 (org-cycle '(4)))
6815 ((eq org-startup-folded 'content)
6816 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6817 (org-cycle '(4)) (org-cycle '(4)))))
6818 (unless (eq org-startup-folded 'showeverything)
6819 (if org-hide-block-startup (org-hide-block-all))
6820 (org-set-visibility-according-to-property 'no-cleanup)
6821 (org-cycle-hide-archived-subtrees 'all)
6822 (org-cycle-hide-drawers 'all)
6823 (org-cycle-show-empty-lines t)))
6825 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6826 "Switch subtree visibilities according to :VISIBILITY: property."
6827 (interactive)
6828 (let (org-show-entry-below state)
6829 (save-excursion
6830 (goto-char (point-min))
6831 (while (re-search-forward
6832 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6833 nil t)
6834 (setq state (match-string 1))
6835 (save-excursion
6836 (org-back-to-heading t)
6837 (hide-subtree)
6838 (org-reveal)
6839 (cond
6840 ((equal state '("fold" "folded"))
6841 (hide-subtree))
6842 ((equal state "children")
6843 (org-show-hidden-entry)
6844 (show-children))
6845 ((equal state "content")
6846 (save-excursion
6847 (save-restriction
6848 (org-narrow-to-subtree)
6849 (org-content))))
6850 ((member state '("all" "showall"))
6851 (show-subtree)))))
6852 (unless no-cleanup
6853 (org-cycle-hide-archived-subtrees 'all)
6854 (org-cycle-hide-drawers 'all)
6855 (org-cycle-show-empty-lines 'all)))))
6857 ;; This function uses outline-regexp instead of the more fundamental
6858 ;; org-outline-regexp so that org-cycle-global works outside of Org
6859 ;; buffers, where outline-regexp is needed.
6860 (defun org-overview ()
6861 "Switch to overview mode, showing only top-level headlines.
6862 Really, this shows all headlines with level equal or greater than the level
6863 of the first headline in the buffer. This is important, because if the
6864 first headline is not level one, then (hide-sublevels 1) gives confusing
6865 results."
6866 (interactive)
6867 (let ((l (org-current-line))
6868 (level (save-excursion
6869 (goto-char (point-min))
6870 (if (re-search-forward (concat "^" outline-regexp) nil t)
6871 (progn
6872 (goto-char (match-beginning 0))
6873 (funcall outline-level))))))
6874 (and level (hide-sublevels level))
6875 (recenter '(4))
6876 (org-goto-line l)))
6878 (defun org-content (&optional arg)
6879 "Show all headlines in the buffer, like a table of contents.
6880 With numerical argument N, show content up to level N."
6881 (interactive "P")
6882 (save-excursion
6883 ;; Visit all headings and show their offspring
6884 (and (integerp arg) (org-overview))
6885 (goto-char (point-max))
6886 (catch 'exit
6887 (while (and (progn (condition-case nil
6888 (outline-previous-visible-heading 1)
6889 (error (goto-char (point-min))))
6891 (looking-at org-outline-regexp))
6892 (if (integerp arg)
6893 (show-children (1- arg))
6894 (show-branches))
6895 (if (bobp) (throw 'exit nil))))))
6898 (defun org-optimize-window-after-visibility-change (state)
6899 "Adjust the window after a change in outline visibility.
6900 This function is the default value of the hook `org-cycle-hook'."
6901 (when (get-buffer-window (current-buffer))
6902 (cond
6903 ((eq state 'content) nil)
6904 ((eq state 'all) nil)
6905 ((eq state 'folded) nil)
6906 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6907 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6909 (defun org-remove-empty-overlays-at (pos)
6910 "Remove outline overlays that do not contain non-white stuff."
6911 (mapc
6912 (lambda (o)
6913 (and (eq 'outline (overlay-get o 'invisible))
6914 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6915 (overlay-end o))))
6916 (delete-overlay o)))
6917 (overlays-at pos)))
6919 (defun org-clean-visibility-after-subtree-move ()
6920 "Fix visibility issues after moving a subtree."
6921 ;; First, find a reasonable region to look at:
6922 ;; Start two siblings above, end three below
6923 (let* ((beg (save-excursion
6924 (and (org-get-last-sibling)
6925 (org-get-last-sibling))
6926 (point)))
6927 (end (save-excursion
6928 (and (org-get-next-sibling)
6929 (org-get-next-sibling)
6930 (org-get-next-sibling))
6931 (if (org-at-heading-p)
6932 (point-at-eol)
6933 (point))))
6934 (level (looking-at "\\*+"))
6935 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6936 (save-excursion
6937 (save-restriction
6938 (narrow-to-region beg end)
6939 (when re
6940 ;; Properly fold already folded siblings
6941 (goto-char (point-min))
6942 (while (re-search-forward re nil t)
6943 (if (and (not (outline-invisible-p))
6944 (save-excursion
6945 (goto-char (point-at-eol)) (outline-invisible-p)))
6946 (hide-entry))))
6947 (org-cycle-show-empty-lines 'overview)
6948 (org-cycle-hide-drawers 'overview)))))
6950 (defun org-cycle-show-empty-lines (state)
6951 "Show empty lines above all visible headlines.
6952 The region to be covered depends on STATE when called through
6953 `org-cycle-hook'. Lisp program can use t for STATE to get the
6954 entire buffer covered. Note that an empty line is only shown if there
6955 are at least `org-cycle-separator-lines' empty lines before the headline."
6956 (when (not (= org-cycle-separator-lines 0))
6957 (save-excursion
6958 (let* ((n (abs org-cycle-separator-lines))
6959 (re (cond
6960 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6961 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6962 (t (let ((ns (number-to-string (- n 2))))
6963 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6964 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6965 beg end b e)
6966 (cond
6967 ((memq state '(overview contents t))
6968 (setq beg (point-min) end (point-max)))
6969 ((memq state '(children folded))
6970 (setq beg (point) end (progn (org-end-of-subtree t t)
6971 (beginning-of-line 2)
6972 (point)))))
6973 (when beg
6974 (goto-char beg)
6975 (while (re-search-forward re end t)
6976 (unless (get-char-property (match-end 1) 'invisible)
6977 (setq e (match-end 1))
6978 (if (< org-cycle-separator-lines 0)
6979 (setq b (save-excursion
6980 (goto-char (match-beginning 0))
6981 (org-back-over-empty-lines)
6982 (if (save-excursion
6983 (goto-char (max (point-min) (1- (point))))
6984 (org-at-heading-p))
6985 (1- (point))
6986 (point))))
6987 (setq b (match-beginning 1)))
6988 (outline-flag-region b e nil)))))))
6989 ;; Never hide empty lines at the end of the file.
6990 (save-excursion
6991 (goto-char (point-max))
6992 (outline-previous-heading)
6993 (outline-end-of-heading)
6994 (if (and (looking-at "[ \t\n]+")
6995 (= (match-end 0) (point-max)))
6996 (outline-flag-region (point) (match-end 0) nil))))
6998 (defun org-show-empty-lines-in-parent ()
6999 "Move to the parent and re-show empty lines before visible headlines."
7000 (save-excursion
7001 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7002 (org-cycle-show-empty-lines context))))
7004 (defun org-files-list ()
7005 "Return `org-agenda-files' list, plus all open org-mode files.
7006 This is useful for operations that need to scan all of a user's
7007 open and agenda-wise Org files."
7008 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7009 (dolist (buf (buffer-list))
7010 (with-current-buffer buf
7011 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7012 (let ((file (expand-file-name (buffer-file-name))))
7013 (unless (member file files)
7014 (push file files))))))
7015 files))
7017 (defsubst org-entry-beginning-position ()
7018 "Return the beginning position of the current entry."
7019 (save-excursion (outline-back-to-heading t) (point)))
7021 (defsubst org-entry-end-position ()
7022 "Return the end position of the current entry."
7023 (save-excursion (outline-next-heading) (point)))
7025 (defun org-cycle-hide-drawers (state)
7026 "Re-hide all drawers after a visibility state change."
7027 (when (and (derived-mode-p 'org-mode)
7028 (not (memq state '(overview folded contents))))
7029 (save-excursion
7030 (let* ((globalp (memq state '(contents all)))
7031 (beg (if globalp (point-min) (point)))
7032 (end (if globalp (point-max)
7033 (if (eq state 'children)
7034 (save-excursion (outline-next-heading) (point))
7035 (org-end-of-subtree t)))))
7036 (goto-char beg)
7037 (while (re-search-forward org-drawer-regexp end t)
7038 (org-flag-drawer t))))))
7040 (defun org-cycle-hide-inline-tasks (state)
7041 "Re-hide inline task when switching to 'contents visibility state."
7042 (when (and (eq state 'contents)
7043 (boundp 'org-inlinetask-min-level)
7044 org-inlinetask-min-level)
7045 (hide-sublevels (1- org-inlinetask-min-level))))
7047 (defun org-flag-drawer (flag)
7048 "When FLAG is non-nil, hide the drawer we are within.
7049 Otherwise make it visible."
7050 (save-excursion
7051 (beginning-of-line 1)
7052 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7053 (let ((b (match-end 0)))
7054 (if (re-search-forward
7055 "^[ \t]*:END:"
7056 (save-excursion (outline-next-heading) (point)) t)
7057 (outline-flag-region b (point-at-eol) flag)
7058 (user-error ":END: line missing at position %s" b))))))
7060 (defun org-subtree-end-visible-p ()
7061 "Is the end of the current subtree visible?"
7062 (pos-visible-in-window-p
7063 (save-excursion (org-end-of-subtree t) (point))))
7065 (defun org-first-headline-recenter (&optional N)
7066 "Move cursor to the first headline and recenter the headline.
7067 Optional argument N means put the headline into the Nth line of the window."
7068 (goto-char (point-min))
7069 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7070 (beginning-of-line)
7071 (recenter (prefix-numeric-value N))))
7073 ;;; Saving and restoring visibility
7075 (defun org-outline-overlay-data (&optional use-markers)
7076 "Return a list of the locations of all outline overlays.
7077 These are overlays with the `invisible' property value `outline'.
7078 The return value is a list of cons cells, with start and stop
7079 positions for each overlay.
7080 If USE-MARKERS is set, return the positions as markers."
7081 (let (beg end)
7082 (save-excursion
7083 (save-restriction
7084 (widen)
7085 (delq nil
7086 (mapcar (lambda (o)
7087 (when (eq (overlay-get o 'invisible) 'outline)
7088 (setq beg (overlay-start o)
7089 end (overlay-end o))
7090 (and beg end (> end beg)
7091 (if use-markers
7092 (cons (move-marker (make-marker) beg)
7093 (move-marker (make-marker) end))
7094 (cons beg end)))))
7095 (overlays-in (point-min) (point-max))))))))
7097 (defun org-set-outline-overlay-data (data)
7098 "Create visibility overlays for all positions in DATA.
7099 DATA should have been made by `org-outline-overlay-data'."
7100 (let (o)
7101 (save-excursion
7102 (save-restriction
7103 (widen)
7104 (show-all)
7105 (mapc (lambda (c)
7106 (outline-flag-region (car c) (cdr c) t))
7107 data)))))
7109 ;;; Folding of blocks
7111 (defvar org-hide-block-overlays nil
7112 "Overlays hiding blocks.")
7113 (make-variable-buffer-local 'org-hide-block-overlays)
7115 (defun org-block-map (function &optional start end)
7116 "Call FUNCTION at the head of all source blocks in the current buffer.
7117 Optional arguments START and END can be used to limit the range."
7118 (let ((start (or start (point-min)))
7119 (end (or end (point-max))))
7120 (save-excursion
7121 (goto-char start)
7122 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7123 (save-excursion
7124 (save-match-data
7125 (goto-char (match-beginning 0))
7126 (funcall function)))))))
7128 (defun org-hide-block-toggle-all ()
7129 "Toggle the visibility of all blocks in the current buffer."
7130 (org-block-map #'org-hide-block-toggle))
7132 (defun org-hide-block-all ()
7133 "Fold all blocks in the current buffer."
7134 (interactive)
7135 (org-show-block-all)
7136 (org-block-map #'org-hide-block-toggle-maybe))
7138 (defun org-show-block-all ()
7139 "Unfold all blocks in the current buffer."
7140 (interactive)
7141 (mapc 'delete-overlay org-hide-block-overlays)
7142 (setq org-hide-block-overlays nil))
7144 (defun org-hide-block-toggle-maybe ()
7145 "Toggle visibility of block at point."
7146 (interactive)
7147 (let ((case-fold-search t))
7148 (if (save-excursion
7149 (beginning-of-line 1)
7150 (looking-at org-block-regexp))
7151 (progn (org-hide-block-toggle)
7152 t) ;; to signal that we took action
7153 nil))) ;; to signal that we did not
7155 (defun org-hide-block-toggle (&optional force)
7156 "Toggle the visibility of the current block."
7157 (interactive)
7158 (save-excursion
7159 (beginning-of-line)
7160 (if (re-search-forward org-block-regexp nil t)
7161 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7162 (end (match-end 0)) ;; end of entire body
7164 (if (memq t (mapcar (lambda (overlay)
7165 (eq (overlay-get overlay 'invisible)
7166 'org-hide-block))
7167 (overlays-at start)))
7168 (if (or (not force) (eq force 'off))
7169 (mapc (lambda (ov)
7170 (when (member ov org-hide-block-overlays)
7171 (setq org-hide-block-overlays
7172 (delq ov org-hide-block-overlays)))
7173 (when (eq (overlay-get ov 'invisible)
7174 'org-hide-block)
7175 (delete-overlay ov)))
7176 (overlays-at start)))
7177 (setq ov (make-overlay start end))
7178 (overlay-put ov 'invisible 'org-hide-block)
7179 ;; make the block accessible to isearch
7180 (overlay-put
7181 ov 'isearch-open-invisible
7182 (lambda (ov)
7183 (when (member ov org-hide-block-overlays)
7184 (setq org-hide-block-overlays
7185 (delq ov org-hide-block-overlays)))
7186 (when (eq (overlay-get ov 'invisible)
7187 'org-hide-block)
7188 (delete-overlay ov))))
7189 (push ov org-hide-block-overlays)))
7190 (user-error "Not looking at a source block"))))
7192 ;; org-tab-after-check-for-cycling-hook
7193 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7194 ;; Remove overlays when changing major mode
7195 (add-hook 'org-mode-hook
7196 (lambda () (org-add-hook 'change-major-mode-hook
7197 'org-show-block-all 'append 'local)))
7199 ;;; Org-goto
7201 (defvar org-goto-window-configuration nil)
7202 (defvar org-goto-marker nil)
7203 (defvar org-goto-map)
7204 (defun org-goto-map ()
7205 "Set the keymap `org-goto'."
7206 (setq org-goto-map
7207 (let ((map (make-sparse-keymap)))
7208 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7209 mouse-drag-region universal-argument org-occur))
7210 cmd)
7211 (while (setq cmd (pop cmds))
7212 (substitute-key-definition cmd cmd map global-map)))
7213 (suppress-keymap map)
7214 (org-defkey map "\C-m" 'org-goto-ret)
7215 (org-defkey map [(return)] 'org-goto-ret)
7216 (org-defkey map [(left)] 'org-goto-left)
7217 (org-defkey map [(right)] 'org-goto-right)
7218 (org-defkey map [(control ?g)] 'org-goto-quit)
7219 (org-defkey map "\C-i" 'org-cycle)
7220 (org-defkey map [(tab)] 'org-cycle)
7221 (org-defkey map [(down)] 'outline-next-visible-heading)
7222 (org-defkey map [(up)] 'outline-previous-visible-heading)
7223 (if org-goto-auto-isearch
7224 (if (fboundp 'define-key-after)
7225 (define-key-after map [t] 'org-goto-local-auto-isearch)
7226 nil)
7227 (org-defkey map "q" 'org-goto-quit)
7228 (org-defkey map "n" 'outline-next-visible-heading)
7229 (org-defkey map "p" 'outline-previous-visible-heading)
7230 (org-defkey map "f" 'outline-forward-same-level)
7231 (org-defkey map "b" 'outline-backward-same-level)
7232 (org-defkey map "u" 'outline-up-heading))
7233 (org-defkey map "/" 'org-occur)
7234 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7235 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7236 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7237 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7238 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7239 map)))
7241 (defconst org-goto-help
7242 "Browse buffer copy, to find location or copy text.%s
7243 RET=jump to location C-g=quit and return to previous location
7244 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7246 (defvar org-goto-start-pos) ; dynamically scoped parameter
7248 (defun org-goto (&optional alternative-interface)
7249 "Look up a different location in the current file, keeping current visibility.
7251 When you want look-up or go to a different location in a
7252 document, the fastest way is often to fold the entire buffer and
7253 then dive into the tree. This method has the disadvantage, that
7254 the previous location will be folded, which may not be what you
7255 want.
7257 This command works around this by showing a copy of the current
7258 buffer in an indirect buffer, in overview mode. You can dive
7259 into the tree in that copy, use org-occur and incremental search
7260 to find a location. When pressing RET or `Q', the command
7261 returns to the original buffer in which the visibility is still
7262 unchanged. After RET it will also jump to the location selected
7263 in the indirect buffer and expose the headline hierarchy above.
7265 With a prefix argument, use the alternative interface: e.g. if
7266 `org-goto-interface' is 'outline use 'outline-path-completion."
7267 (interactive "P")
7268 (org-goto-map)
7269 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7270 (org-refile-use-outline-path t)
7271 (org-refile-target-verify-function nil)
7272 (interface
7273 (if (not alternative-interface)
7274 org-goto-interface
7275 (if (eq org-goto-interface 'outline)
7276 'outline-path-completion
7277 'outline)))
7278 (org-goto-start-pos (point))
7279 (selected-point
7280 (if (eq interface 'outline)
7281 (car (org-get-location (current-buffer) org-goto-help))
7282 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7283 (org-refile-check-position pa)
7284 (nth 3 pa)))))
7285 (if selected-point
7286 (progn
7287 (org-mark-ring-push org-goto-start-pos)
7288 (goto-char selected-point)
7289 (if (or (outline-invisible-p) (org-invisible-p2))
7290 (org-show-context 'org-goto)))
7291 (message "Quit"))))
7293 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7294 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7295 (defvar org-goto-local-auto-isearch-map) ; defined below
7297 (defun org-get-location (buf help)
7298 "Let the user select a location in the Org-mode buffer BUF.
7299 This function uses a recursive edit. It returns the selected position
7300 or nil."
7301 (org-no-popups
7302 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7303 (isearch-hide-immediately nil)
7304 (isearch-search-fun-function
7305 (lambda () 'org-goto-local-search-headings))
7306 (org-goto-selected-point org-goto-exit-command))
7307 (save-excursion
7308 (save-window-excursion
7309 (delete-other-windows)
7310 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7311 (org-pop-to-buffer-same-window
7312 (condition-case nil
7313 (make-indirect-buffer (current-buffer) "*org-goto*")
7314 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7315 (with-output-to-temp-buffer "*Org Help*"
7316 (princ (format help (if org-goto-auto-isearch
7317 " Just type for auto-isearch."
7318 " n/p/f/b/u to navigate, q to quit."))))
7319 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7320 (setq buffer-read-only nil)
7321 (let ((org-startup-truncated t)
7322 (org-startup-folded nil)
7323 (org-startup-align-all-tables nil))
7324 (org-mode)
7325 (org-overview))
7326 (setq buffer-read-only t)
7327 (if (and (boundp 'org-goto-start-pos)
7328 (integer-or-marker-p org-goto-start-pos))
7329 (let ((org-show-hierarchy-above t)
7330 (org-show-siblings t)
7331 (org-show-following-heading t))
7332 (goto-char org-goto-start-pos)
7333 (and (outline-invisible-p) (org-show-context)))
7334 (goto-char (point-min)))
7335 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7336 (message "Select location and press RET")
7337 (use-local-map org-goto-map)
7338 (recursive-edit)))
7339 (kill-buffer "*org-goto*")
7340 (cons org-goto-selected-point org-goto-exit-command))))
7342 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7343 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7344 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7345 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7347 (defun org-goto-local-search-headings (string bound noerror)
7348 "Search and make sure that any matches are in headlines."
7349 (catch 'return
7350 (while (if isearch-forward
7351 (search-forward string bound noerror)
7352 (search-backward string bound noerror))
7353 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7354 (and (member :headline context)
7355 (not (member :tags context))))
7356 (throw 'return (point))))))
7358 (defun org-goto-local-auto-isearch ()
7359 "Start isearch."
7360 (interactive)
7361 (goto-char (point-min))
7362 (let ((keys (this-command-keys)))
7363 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7364 (isearch-mode t)
7365 (isearch-process-search-char (string-to-char keys)))))
7367 (defun org-goto-ret (&optional arg)
7368 "Finish `org-goto' by going to the new location."
7369 (interactive "P")
7370 (setq org-goto-selected-point (point)
7371 org-goto-exit-command 'return)
7372 (throw 'exit nil))
7374 (defun org-goto-left ()
7375 "Finish `org-goto' by going to the new location."
7376 (interactive)
7377 (if (org-at-heading-p)
7378 (progn
7379 (beginning-of-line 1)
7380 (setq org-goto-selected-point (point)
7381 org-goto-exit-command 'left)
7382 (throw 'exit nil))
7383 (user-error "Not on a heading")))
7385 (defun org-goto-right ()
7386 "Finish `org-goto' by going to the new location."
7387 (interactive)
7388 (if (org-at-heading-p)
7389 (progn
7390 (setq org-goto-selected-point (point)
7391 org-goto-exit-command 'right)
7392 (throw 'exit nil))
7393 (user-error "Not on a heading")))
7395 (defun org-goto-quit ()
7396 "Finish `org-goto' without cursor motion."
7397 (interactive)
7398 (setq org-goto-selected-point nil)
7399 (setq org-goto-exit-command 'quit)
7400 (throw 'exit nil))
7402 ;;; Indirect buffer display of subtrees
7404 (defvar org-indirect-dedicated-frame nil
7405 "This is the frame being used for indirect tree display.")
7406 (defvar org-last-indirect-buffer nil)
7408 (defun org-tree-to-indirect-buffer (&optional arg)
7409 "Create indirect buffer and narrow it to current subtree.
7410 With a numerical prefix ARG, go up to this level and then take that tree.
7411 If ARG is negative, go up that many levels.
7413 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7414 indirect buffer previously made with this command, to avoid proliferation of
7415 indirect buffers. However, when you call the command with a \
7416 \\[universal-argument] prefix, or
7417 when `org-indirect-buffer-display' is `new-frame', the last buffer
7418 is kept so that you can work with several indirect buffers at the same time.
7419 If `org-indirect-buffer-display' is `dedicated-frame', the \
7420 \\[universal-argument] prefix also
7421 requests that a new frame be made for the new buffer, so that the dedicated
7422 frame is not changed."
7423 (interactive "P")
7424 (let ((cbuf (current-buffer))
7425 (cwin (selected-window))
7426 (pos (point))
7427 beg end level heading ibuf)
7428 (save-excursion
7429 (org-back-to-heading t)
7430 (when (numberp arg)
7431 (setq level (org-outline-level))
7432 (if (< arg 0) (setq arg (+ level arg)))
7433 (while (> (setq level (org-outline-level)) arg)
7434 (org-up-heading-safe)))
7435 (setq beg (point)
7436 heading (org-get-heading))
7437 (org-end-of-subtree t t)
7438 (if (org-at-heading-p) (backward-char 1))
7439 (setq end (point)))
7440 (if (and (buffer-live-p org-last-indirect-buffer)
7441 (not (eq org-indirect-buffer-display 'new-frame))
7442 (not arg))
7443 (kill-buffer org-last-indirect-buffer))
7444 (setq ibuf (org-get-indirect-buffer cbuf)
7445 org-last-indirect-buffer ibuf)
7446 (cond
7447 ((or (eq org-indirect-buffer-display 'new-frame)
7448 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7449 (select-frame (make-frame))
7450 (delete-other-windows)
7451 (org-pop-to-buffer-same-window ibuf)
7452 (org-set-frame-title heading))
7453 ((eq org-indirect-buffer-display 'dedicated-frame)
7454 (raise-frame
7455 (select-frame (or (and org-indirect-dedicated-frame
7456 (frame-live-p org-indirect-dedicated-frame)
7457 org-indirect-dedicated-frame)
7458 (setq org-indirect-dedicated-frame (make-frame)))))
7459 (delete-other-windows)
7460 (org-pop-to-buffer-same-window ibuf)
7461 (org-set-frame-title (concat "Indirect: " heading)))
7462 ((eq org-indirect-buffer-display 'current-window)
7463 (org-pop-to-buffer-same-window ibuf))
7464 ((eq org-indirect-buffer-display 'other-window)
7465 (pop-to-buffer ibuf))
7466 (t (error "Invalid value")))
7467 (if (featurep 'xemacs)
7468 (save-excursion (org-mode) (turn-on-font-lock)))
7469 (narrow-to-region beg end)
7470 (show-all)
7471 (goto-char pos)
7472 (run-hook-with-args 'org-cycle-hook 'all)
7473 (and (window-live-p cwin) (select-window cwin))))
7475 (defun org-get-indirect-buffer (&optional buffer)
7476 (setq buffer (or buffer (current-buffer)))
7477 (let ((n 1) (base (buffer-name buffer)) bname)
7478 (while (buffer-live-p
7479 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7480 (setq n (1+ n)))
7481 (condition-case nil
7482 (make-indirect-buffer buffer bname 'clone)
7483 (error (make-indirect-buffer buffer bname)))))
7485 (defun org-set-frame-title (title)
7486 "Set the title of the current frame to the string TITLE."
7487 ;; FIXME: how to name a single frame in XEmacs???
7488 (unless (featurep 'xemacs)
7489 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7491 ;;;; Structure editing
7493 ;;; Inserting headlines
7495 (defun org-previous-line-empty-p (&optional next)
7496 "Is the previous line a blank line?
7497 When NEXT is non-nil, check the next line instead."
7498 (save-excursion
7499 (and (not (bobp))
7500 (or (beginning-of-line (if next 2 0)) t)
7501 (save-match-data
7502 (looking-at "[ \t]*$")))))
7504 (defun org-insert-heading (&optional arg invisible-ok)
7505 "Insert a new heading or item with same depth at point.
7506 If point is in a plain list and ARG is nil, create a new list item.
7507 With one universal prefix argument, insert a heading even in lists.
7508 With two universal prefix arguments, insert the heading at the end
7509 of the parent subtree.
7511 If point is at the beginning of a headline, insert a sibling before
7512 the current headline. If point is not at the beginning, split the line
7513 and create a new headline with the text in the current line after point
7514 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7516 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7517 This is important for non-interactive uses of the command."
7518 (interactive "P")
7519 (if (org-called-interactively-p 'any) (org-reveal))
7520 (cond
7521 ((or (= (buffer-size) 0)
7522 (and (not (save-excursion
7523 (and (ignore-errors (org-back-to-heading invisible-ok))
7524 (org-at-heading-p))))
7525 (or arg (not (org-in-item-p)))))
7526 (insert
7527 (if (org-previous-line-empty-p) "" "\n")
7528 (if (org-in-src-block-p) ",* " "* "))
7529 (run-hooks 'org-insert-heading-hook))
7530 ((or arg
7531 (and (not (org-in-item-p)) org-insert-heading-respect-content)
7532 (not (org-insert-item
7533 (save-excursion
7534 (beginning-of-line)
7535 (looking-at org-list-full-item-re)
7536 (match-string 3)))))
7537 (let (begn endn)
7538 (when (org-buffer-narrowed-p)
7539 (setq begn (point-min) endn (point-max))
7540 (widen))
7541 (let* ((empty-line-p nil)
7542 (eops (equal arg '(16))) ; insert at end of parent subtree
7543 (org-insert-heading-respect-content
7544 (or (not (null arg)) org-insert-heading-respect-content))
7545 (level nil)
7546 (on-heading (org-at-heading-p))
7547 ;; Get a level to fall back on
7548 (fix-level
7549 (save-excursion
7550 (org-back-to-heading t)
7551 (looking-at org-outline-regexp)
7552 (make-string (1- (length (match-string 0))) ?*)))
7553 (on-empty-line
7554 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7555 (head (save-excursion
7556 (condition-case nil
7557 (progn
7558 (org-back-to-heading invisible-ok)
7559 (when (and (not on-heading)
7560 (featurep 'org-inlinetask)
7561 (integerp org-inlinetask-min-level)
7562 (>= (length (match-string 0))
7563 org-inlinetask-min-level))
7564 ;; Find a heading level before the inline task
7565 (while (and (setq level (org-up-heading-safe))
7566 (>= level org-inlinetask-min-level)))
7567 (if (org-at-heading-p)
7568 (org-back-to-heading invisible-ok)
7569 (error "This should not happen")))
7570 (unless (and (save-excursion
7571 (save-match-data
7572 (org-backward-heading-same-level 1 invisible-ok))
7573 (= (point) (match-beginning 0)))
7574 (not (org-previous-line-empty-p t)))
7575 (setq empty-line-p (org-previous-line-empty-p)))
7576 (match-string 0))
7577 (error (or fix-level "* ")))))
7578 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7579 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7580 pos hide-previous previous-pos)
7581 (if ;; At the beginning of a heading, open a new line for insertion
7582 (and (bolp) (org-at-heading-p)
7583 (not eops)
7584 (or (bobp)
7585 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7586 (open-line (if blank 2 1))
7587 (save-excursion
7588 (setq previous-pos (point-at-bol))
7589 (end-of-line)
7590 (setq hide-previous (outline-invisible-p)))
7591 (and org-insert-heading-respect-content
7592 (save-excursion
7593 (while (outline-invisible-p)
7594 (org-show-subtree)
7595 (org-up-heading-safe))))
7596 (let ((split
7597 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7598 (save-excursion
7599 (let ((p (point)))
7600 (goto-char (point-at-bol))
7601 (and (looking-at org-complex-heading-regexp)
7602 (match-beginning 4)
7603 (> p (match-beginning 4)))))))
7604 tags pos)
7605 (cond
7606 ;; Insert a new line, possibly at end of parent subtree
7607 ((and (not arg) (not on-heading) (not on-empty-line)
7608 (not (save-excursion
7609 (beginning-of-line 1)
7610 (or (looking-at org-list-full-item-re)
7611 ;; Don't convert :end: lines to headline
7612 (looking-at "^\\s-*:end:")
7613 (looking-at "^\\s-*#\\+end_?")))))
7614 (beginning-of-line 1))
7615 (org-insert-heading-respect-content
7616 (if (not eops)
7617 (progn
7618 (org-end-of-subtree nil t)
7619 (and (looking-at "^\\*") (backward-char 1))
7620 (while (and (not (bobp))
7621 ;; Don't delete spaces in empty headlines
7622 (not (looking-back org-outline-regexp))
7623 (member (char-before) '(?\ ?\t ?\n)))
7624 (backward-delete-char 1)))
7625 (let ((p (point)))
7626 (org-up-heading-safe)
7627 (if (= p (point))
7628 (goto-char (point-max))
7629 (org-end-of-subtree nil t))))
7630 (when (featurep 'org-inlinetask)
7631 (while (and (not (eobp))
7632 (looking-at "\\(\\*+\\)[ \t]+")
7633 (>= (length (match-string 1))
7634 org-inlinetask-min-level))
7635 (org-end-of-subtree nil t)))
7636 (or (bolp) (newline))
7637 (or (org-previous-line-empty-p)
7638 (and blank (newline)))
7639 (if (or empty-line-p eops) (open-line 1)))
7640 ;; Insert a headling containing text after point
7641 ((org-at-heading-p)
7642 (when hide-previous
7643 (show-children)
7644 (org-show-entry))
7645 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7646 (setq tags (and (match-end 2) (match-string 2)))
7647 (and (match-end 1)
7648 (delete-region (match-beginning 1) (match-end 1)))
7649 (setq pos (point-at-bol))
7650 (or split (end-of-line 1))
7651 (delete-horizontal-space)
7652 (if (string-match "\\`\\*+\\'"
7653 (buffer-substring (point-at-bol) (point)))
7654 (insert " "))
7655 (newline (if blank 2 1))
7656 (when tags
7657 (save-excursion
7658 (goto-char pos)
7659 (end-of-line 1)
7660 (insert " " tags)
7661 (org-set-tags nil 'align))))
7663 (or split (end-of-line 1))
7664 (newline (cond ((and blank (not on-empty-line)) 2)
7665 (blank 1)
7666 (on-empty-line 0) (t 1)))))))
7667 (insert head) (just-one-space)
7668 (setq pos (point))
7669 (end-of-line 1)
7670 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7671 (when (and org-insert-heading-respect-content hide-previous)
7672 (save-excursion
7673 (goto-char previous-pos)
7674 (hide-subtree)))
7675 (when (and begn endn)
7676 (narrow-to-region (min (point) begn) (max (point) endn)))
7677 (run-hooks 'org-insert-heading-hook))))))
7679 (defun org-get-heading (&optional no-tags no-todo)
7680 "Return the heading of the current entry, without the stars.
7681 When NO-TAGS is non-nil, don't include tags.
7682 When NO-TODO is non-nil, don't include TODO keywords."
7683 (save-excursion
7684 (org-back-to-heading t)
7685 (cond
7686 ((and no-tags no-todo)
7687 (looking-at org-complex-heading-regexp)
7688 (match-string 4))
7689 (no-tags
7690 (looking-at (concat org-outline-regexp
7691 "\\(.*?\\)"
7692 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7693 (match-string 1))
7694 (no-todo
7695 (looking-at org-todo-line-regexp)
7696 (match-string 3))
7697 (t (looking-at org-heading-regexp)
7698 (match-string 2)))))
7700 (defvar orgstruct-mode) ; defined below
7702 (defun org-heading-components ()
7703 "Return the components of the current heading.
7704 This is a list with the following elements:
7705 - the level as an integer
7706 - the reduced level, different if `org-odd-levels-only' is set.
7707 - the TODO keyword, or nil
7708 - the priority character, like ?A, or nil if no priority is given
7709 - the headline text itself, or the tags string if no headline text
7710 - the tags string, or nil."
7711 (save-excursion
7712 (org-back-to-heading t)
7713 (if (let (case-fold-search)
7714 (looking-at
7715 (if orgstruct-mode
7716 org-heading-regexp
7717 org-complex-heading-regexp)))
7718 (if orgstruct-mode
7719 (list (length (match-string 1))
7720 (org-reduced-level (length (match-string 1)))
7723 (match-string 2)
7724 nil)
7725 (list (length (match-string 1))
7726 (org-reduced-level (length (match-string 1)))
7727 (org-match-string-no-properties 2)
7728 (and (match-end 3) (aref (match-string 3) 2))
7729 (org-match-string-no-properties 4)
7730 (org-match-string-no-properties 5))))))
7732 (defun org-get-entry ()
7733 "Get the entry text, after heading, entire subtree."
7734 (save-excursion
7735 (org-back-to-heading t)
7736 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7738 (defun org-insert-heading-after-current ()
7739 "Insert a new heading with same level as current, after current subtree."
7740 (interactive)
7741 (org-back-to-heading)
7742 (org-insert-heading)
7743 (org-move-subtree-down)
7744 (end-of-line 1))
7746 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7747 "Insert heading with `org-insert-heading-respect-content' set to t."
7748 (interactive "P")
7749 (let ((org-insert-heading-respect-content t))
7750 (org-insert-heading arg invisible-ok)))
7752 (defun org-insert-todo-heading-respect-content (&optional force-state)
7753 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7754 (interactive "P")
7755 (let ((org-insert-heading-respect-content t))
7756 (org-insert-todo-heading force-state t)))
7758 (defun org-insert-todo-heading (arg &optional force-heading)
7759 "Insert a new heading with the same level and TODO state as current heading.
7760 If the heading has no TODO state, or if the state is DONE, use the first
7761 state (TODO by default). Also one prefix arg, force first state. With two
7762 prefix args, force inserting at the end of the parent subtree."
7763 (interactive "P")
7764 (when (or force-heading (not (org-insert-item 'checkbox)))
7765 (org-insert-heading (or (and (equal arg '(16)) '(16))
7766 force-heading))
7767 (save-excursion
7768 (org-back-to-heading)
7769 (outline-previous-heading)
7770 (looking-at org-todo-line-regexp))
7771 (let*
7772 ((new-mark-x
7773 (if (or arg
7774 (not (match-beginning 2))
7775 (member (match-string 2) org-done-keywords))
7776 (car org-todo-keywords-1)
7777 (match-string 2)))
7778 (new-mark
7780 (run-hook-with-args-until-success
7781 'org-todo-get-default-hook new-mark-x nil)
7782 new-mark-x)))
7783 (beginning-of-line 1)
7784 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7785 (if org-treat-insert-todo-heading-as-state-change
7786 (org-todo new-mark)
7787 (insert new-mark " "))))
7788 (when org-provide-todo-statistics
7789 (org-update-parent-todo-statistics))))
7791 (defun org-insert-subheading (arg)
7792 "Insert a new subheading and demote it.
7793 Works for outline headings and for plain lists alike."
7794 (interactive "P")
7795 (org-insert-heading arg)
7796 (cond
7797 ((org-at-heading-p) (org-do-demote))
7798 ((org-at-item-p) (org-indent-item))))
7800 (defun org-insert-todo-subheading (arg)
7801 "Insert a new subheading with TODO keyword or checkbox and demote it.
7802 Works for outline headings and for plain lists alike."
7803 (interactive "P")
7804 (org-insert-todo-heading arg)
7805 (cond
7806 ((org-at-heading-p) (org-do-demote))
7807 ((org-at-item-p) (org-indent-item))))
7809 ;;; Promotion and Demotion
7811 (defvar org-after-demote-entry-hook nil
7812 "Hook run after an entry has been demoted.
7813 The cursor will be at the beginning of the entry.
7814 When a subtree is being demoted, the hook will be called for each node.")
7816 (defvar org-after-promote-entry-hook nil
7817 "Hook run after an entry has been promoted.
7818 The cursor will be at the beginning of the entry.
7819 When a subtree is being promoted, the hook will be called for each node.")
7821 (defun org-promote-subtree ()
7822 "Promote the entire subtree.
7823 See also `org-promote'."
7824 (interactive)
7825 (save-excursion
7826 (org-with-limited-levels (org-map-tree 'org-promote)))
7827 (org-fix-position-after-promote))
7829 (defun org-demote-subtree ()
7830 "Demote the entire subtree. See `org-demote'.
7831 See also `org-promote'."
7832 (interactive)
7833 (save-excursion
7834 (org-with-limited-levels (org-map-tree 'org-demote)))
7835 (org-fix-position-after-promote))
7838 (defun org-do-promote ()
7839 "Promote the current heading higher up the tree.
7840 If the region is active in `transient-mark-mode', promote all headings
7841 in the region."
7842 (interactive)
7843 (save-excursion
7844 (if (org-region-active-p)
7845 (org-map-region 'org-promote (region-beginning) (region-end))
7846 (org-promote)))
7847 (org-fix-position-after-promote))
7849 (defun org-do-demote ()
7850 "Demote the current heading lower down the tree.
7851 If the region is active in `transient-mark-mode', demote all headings
7852 in the region."
7853 (interactive)
7854 (save-excursion
7855 (if (org-region-active-p)
7856 (org-map-region 'org-demote (region-beginning) (region-end))
7857 (org-demote)))
7858 (org-fix-position-after-promote))
7860 (defun org-fix-position-after-promote ()
7861 "Make sure that after pro/demotion cursor position is right."
7862 (let ((pos (point)))
7863 (when (save-excursion
7864 (beginning-of-line 1)
7865 (looking-at org-todo-line-regexp)
7866 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7867 (cond ((eobp) (insert " "))
7868 ((eolp) (insert " "))
7869 ((equal (char-after) ?\ ) (forward-char 1))))))
7871 (defun org-current-level ()
7872 "Return the level of the current entry, or nil if before the first headline.
7873 The level is the number of stars at the beginning of the headline."
7874 (save-excursion
7875 (org-with-limited-levels
7876 (if (ignore-errors (org-back-to-heading t))
7877 (funcall outline-level)))))
7879 (defun org-get-previous-line-level ()
7880 "Return the outline depth of the last headline before the current line.
7881 Returns 0 for the first headline in the buffer, and nil if before the
7882 first headline."
7883 (let ((current-level (org-current-level))
7884 (prev-level (when (> (line-number-at-pos) 1)
7885 (save-excursion
7886 (beginning-of-line 0)
7887 (org-current-level)))))
7888 (cond ((null current-level) nil) ; Before first headline
7889 ((null prev-level) 0) ; At first headline
7890 (prev-level))))
7892 (defun org-reduced-level (l)
7893 "Compute the effective level of a heading.
7894 This takes into account the setting of `org-odd-levels-only'."
7895 (cond
7896 ((zerop l) 0)
7897 (org-odd-levels-only (1+ (floor (/ l 2))))
7898 (t l)))
7900 (defun org-level-increment ()
7901 "Return the number of stars that will be added or removed at a
7902 time to headlines when structure editing, based on the value of
7903 `org-odd-levels-only'."
7904 (if org-odd-levels-only 2 1))
7906 (defun org-get-valid-level (level &optional change)
7907 "Rectify a level change under the influence of `org-odd-levels-only'
7908 LEVEL is a current level, CHANGE is by how much the level should be
7909 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7910 even level numbers will become the next higher odd number."
7911 (if org-odd-levels-only
7912 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7913 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7914 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7915 (max 1 (+ level (or change 0)))))
7917 (if (boundp 'define-obsolete-function-alias)
7918 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7919 (define-obsolete-function-alias 'org-get-legal-level
7920 'org-get-valid-level)
7921 (define-obsolete-function-alias 'org-get-legal-level
7922 'org-get-valid-level "23.1")))
7924 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7925 ;; ̀org-with-limited-levels'
7926 (defun org-promote ()
7927 "Promote the current heading higher up the tree.
7928 If the region is active in `transient-mark-mode', promote all headings
7929 in the region."
7930 (org-back-to-heading t)
7931 (let* ((level (save-match-data (funcall outline-level)))
7932 (after-change-functions (remove 'flyspell-after-change-function
7933 after-change-functions))
7934 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7935 (diff (abs (- level (length up-head) -1))))
7936 (cond ((and (= level 1) org-called-with-limited-levels
7937 org-allow-promoting-top-level-subtree)
7938 (replace-match "# " nil t))
7939 ((= level 1)
7940 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7941 (t (replace-match up-head nil t)))
7942 ;; Fixup tag positioning
7943 (unless (= level 1)
7944 (and org-auto-align-tags (org-set-tags nil t))
7945 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7946 (run-hooks 'org-after-promote-entry-hook)))
7948 (defun org-demote ()
7949 "Demote the current heading lower down the tree.
7950 If the region is active in `transient-mark-mode', demote all headings
7951 in the region."
7952 (org-back-to-heading t)
7953 (let* ((level (save-match-data (funcall outline-level)))
7954 (after-change-functions (remove 'flyspell-after-change-function
7955 after-change-functions))
7956 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7957 (diff (abs (- level (length down-head) -1))))
7958 (replace-match down-head nil t)
7959 ;; Fixup tag positioning
7960 (and org-auto-align-tags (org-set-tags nil t))
7961 (if org-adapt-indentation (org-fixup-indentation diff))
7962 (run-hooks 'org-after-demote-entry-hook)))
7964 (defun org-cycle-level ()
7965 "Cycle the level of an empty headline through possible states.
7966 This goes first to child, then to parent, level, then up the hierarchy.
7967 After top level, it switches back to sibling level."
7968 (interactive)
7969 (let ((org-adapt-indentation nil))
7970 (when (org-point-at-end-of-empty-headline)
7971 (setq this-command 'org-cycle-level) ; Only needed for caching
7972 (let ((cur-level (org-current-level))
7973 (prev-level (org-get-previous-line-level)))
7974 (cond
7975 ;; If first headline in file, promote to top-level.
7976 ((= prev-level 0)
7977 (loop repeat (/ (- cur-level 1) (org-level-increment))
7978 do (org-do-promote)))
7979 ;; If same level as prev, demote one.
7980 ((= prev-level cur-level)
7981 (org-do-demote))
7982 ;; If parent is top-level, promote to top level if not already.
7983 ((= prev-level 1)
7984 (loop repeat (/ (- cur-level 1) (org-level-increment))
7985 do (org-do-promote)))
7986 ;; If top-level, return to prev-level.
7987 ((= cur-level 1)
7988 (loop repeat (/ (- prev-level 1) (org-level-increment))
7989 do (org-do-demote)))
7990 ;; If less than prev-level, promote one.
7991 ((< cur-level prev-level)
7992 (org-do-promote))
7993 ;; If deeper than prev-level, promote until higher than
7994 ;; prev-level.
7995 ((> cur-level prev-level)
7996 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7997 do (org-do-promote))))
7998 t))))
8000 (defun org-map-tree (fun)
8001 "Call FUN for every heading underneath the current one."
8002 (org-back-to-heading)
8003 (let ((level (funcall outline-level)))
8004 (save-excursion
8005 (funcall fun)
8006 (while (and (progn
8007 (outline-next-heading)
8008 (> (funcall outline-level) level))
8009 (not (eobp)))
8010 (funcall fun)))))
8012 (defun org-map-region (fun beg end)
8013 "Call FUN for every heading between BEG and END."
8014 (let ((org-ignore-region t))
8015 (save-excursion
8016 (setq end (copy-marker end))
8017 (goto-char beg)
8018 (if (and (re-search-forward org-outline-regexp-bol nil t)
8019 (< (point) end))
8020 (funcall fun))
8021 (while (and (progn
8022 (outline-next-heading)
8023 (< (point) end))
8024 (not (eobp)))
8025 (funcall fun)))))
8027 (defvar org-property-end-re) ; silence byte-compiler
8028 (defun org-fixup-indentation (diff)
8029 "Change the indentation in the current entry by DIFF.
8030 However, if any line in the current entry has no indentation, or if it
8031 would end up with no indentation after the change, nothing at all is done."
8032 (save-excursion
8033 (let ((end (save-excursion (outline-next-heading)
8034 (point-marker)))
8035 (prohibit (if (> diff 0)
8036 "^\\S-"
8037 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8038 col)
8039 (unless (save-excursion (end-of-line 1)
8040 (re-search-forward prohibit end t))
8041 (while (and (< (point) end)
8042 (re-search-forward "^[ \t]+" end t))
8043 (goto-char (match-end 0))
8044 (setq col (current-column))
8045 (if (< diff 0) (replace-match ""))
8046 (org-indent-to-column (+ diff col))))
8047 (move-marker end nil))))
8049 (defun org-convert-to-odd-levels ()
8050 "Convert an org-mode file with all levels allowed to one with odd levels.
8051 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8052 level 5 etc."
8053 (interactive)
8054 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8055 (let ((outline-level 'org-outline-level)
8056 (org-odd-levels-only nil) n)
8057 (save-excursion
8058 (goto-char (point-min))
8059 (while (re-search-forward "^\\*\\*+ " nil t)
8060 (setq n (- (length (match-string 0)) 2))
8061 (while (>= (setq n (1- n)) 0)
8062 (org-demote))
8063 (end-of-line 1))))))
8065 (defun org-convert-to-oddeven-levels ()
8066 "Convert an org-mode file with only odd levels to one with odd/even levels.
8067 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8068 file contains a section with an even level, conversion would
8069 destroy the structure of the file. An error is signaled in this
8070 case."
8071 (interactive)
8072 (goto-char (point-min))
8073 ;; First check if there are no even levels
8074 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8075 (org-show-context t)
8076 (error "Not all levels are odd in this file. Conversion not possible"))
8077 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8078 (let ((outline-regexp org-outline-regexp)
8079 (outline-level 'org-outline-level)
8080 (org-odd-levels-only nil) n)
8081 (save-excursion
8082 (goto-char (point-min))
8083 (while (re-search-forward "^\\*\\*+ " nil t)
8084 (setq n (/ (1- (length (match-string 0))) 2))
8085 (while (>= (setq n (1- n)) 0)
8086 (org-promote))
8087 (end-of-line 1))))))
8089 (defun org-tr-level (n)
8090 "Make N odd if required."
8091 (if org-odd-levels-only (1+ (/ n 2)) n))
8093 ;;; Vertical tree motion, cutting and pasting of subtrees
8095 (defun org-move-subtree-up (&optional arg)
8096 "Move the current subtree up past ARG headlines of the same level."
8097 (interactive "p")
8098 (org-move-subtree-down (- (prefix-numeric-value arg))))
8100 (defun org-move-subtree-down (&optional arg)
8101 "Move the current subtree down past ARG headlines of the same level."
8102 (interactive "p")
8103 (setq arg (prefix-numeric-value arg))
8104 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8105 'org-get-last-sibling))
8106 (ins-point (make-marker))
8107 (cnt (abs arg))
8108 (col (current-column))
8109 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8110 ;; Select the tree
8111 (org-back-to-heading)
8112 (setq beg0 (point))
8113 (save-excursion
8114 (setq ne-beg (org-back-over-empty-lines))
8115 (setq beg (point)))
8116 (save-match-data
8117 (save-excursion (outline-end-of-heading)
8118 (setq folded (outline-invisible-p)))
8119 (outline-end-of-subtree))
8120 (outline-next-heading)
8121 (setq ne-end (org-back-over-empty-lines))
8122 (setq end (point))
8123 (goto-char beg0)
8124 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8125 ;; include less whitespace
8126 (save-excursion
8127 (goto-char beg)
8128 (forward-line (- ne-beg ne-end))
8129 (setq beg (point))))
8130 ;; Find insertion point, with error handling
8131 (while (> cnt 0)
8132 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8133 (progn (goto-char beg0)
8134 (user-error "Cannot move past superior level or buffer limit")))
8135 (setq cnt (1- cnt)))
8136 (if (> arg 0)
8137 ;; Moving forward - still need to move over subtree
8138 (progn (org-end-of-subtree t t)
8139 (save-excursion
8140 (org-back-over-empty-lines)
8141 (or (bolp) (newline)))))
8142 (setq ne-ins (org-back-over-empty-lines))
8143 (move-marker ins-point (point))
8144 (setq txt (buffer-substring beg end))
8145 (org-save-markers-in-region beg end)
8146 (delete-region beg end)
8147 (org-remove-empty-overlays-at beg)
8148 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8149 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8150 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8151 (let ((bbb (point)))
8152 (insert-before-markers txt)
8153 (org-reinstall-markers-in-region bbb)
8154 (move-marker ins-point bbb))
8155 (or (bolp) (insert "\n"))
8156 (setq ins-end (point))
8157 (goto-char ins-point)
8158 (org-skip-whitespace)
8159 (when (and (< arg 0)
8160 (org-first-sibling-p)
8161 (> ne-ins ne-beg))
8162 ;; Move whitespace back to beginning
8163 (save-excursion
8164 (goto-char ins-end)
8165 (let ((kill-whole-line t))
8166 (kill-line (- ne-ins ne-beg)) (point)))
8167 (insert (make-string (- ne-ins ne-beg) ?\n)))
8168 (move-marker ins-point nil)
8169 (if folded
8170 (hide-subtree)
8171 (org-show-entry)
8172 (show-children)
8173 (org-cycle-hide-drawers 'children))
8174 (org-clean-visibility-after-subtree-move)
8175 ;; move back to the initial column we were at
8176 (move-to-column col)))
8178 (defvar org-subtree-clip ""
8179 "Clipboard for cut and paste of subtrees.
8180 This is actually only a copy of the kill, because we use the normal kill
8181 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8183 (defvar org-subtree-clip-folded nil
8184 "Was the last copied subtree folded?
8185 This is used to fold the tree back after pasting.")
8187 (defun org-cut-subtree (&optional n)
8188 "Cut the current subtree into the clipboard.
8189 With prefix arg N, cut this many sequential subtrees.
8190 This is a short-hand for marking the subtree and then cutting it."
8191 (interactive "p")
8192 (org-copy-subtree n 'cut))
8194 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8195 "Copy the current subtree it in the clipboard.
8196 With prefix arg N, copy this many sequential subtrees.
8197 This is a short-hand for marking the subtree and then copying it.
8198 If CUT is non-nil, actually cut the subtree.
8199 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8200 of some markers in the region, even if CUT is non-nil. This is
8201 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8202 (interactive "p")
8203 (let (beg end folded (beg0 (point)))
8204 (if (org-called-interactively-p 'any)
8205 (org-back-to-heading nil) ; take what looks like a subtree
8206 (org-back-to-heading t)) ; take what is really there
8207 (setq beg (point))
8208 (skip-chars-forward " \t\r\n")
8209 (save-match-data
8210 (if nosubtrees
8211 (outline-next-heading)
8212 (save-excursion (outline-end-of-heading)
8213 (setq folded (outline-invisible-p)))
8214 (condition-case nil
8215 (org-forward-heading-same-level (1- n) t)
8216 (error nil))
8217 (org-end-of-subtree t t)))
8218 (setq end (point))
8219 (goto-char beg0)
8220 (when (> end beg)
8221 (setq org-subtree-clip-folded folded)
8222 (when (or cut force-store-markers)
8223 (org-save-markers-in-region beg end))
8224 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8225 (setq org-subtree-clip (current-kill 0))
8226 (message "%s: Subtree(s) with %d characters"
8227 (if cut "Cut" "Copied")
8228 (length org-subtree-clip)))))
8230 (defun org-paste-subtree (&optional level tree for-yank)
8231 "Paste the clipboard as a subtree, with modification of headline level.
8232 The entire subtree is promoted or demoted in order to match a new headline
8233 level.
8235 If the cursor is at the beginning of a headline, the same level as
8236 that headline is used to paste the tree.
8238 If not, the new level is derived from the *visible* headings
8239 before and after the insertion point, and taken to be the inferior headline
8240 level of the two. So if the previous visible heading is level 3 and the
8241 next is level 4 (or vice versa), level 4 will be used for insertion.
8242 This makes sure that the subtree remains an independent subtree and does
8243 not swallow low level entries.
8245 You can also force a different level, either by using a numeric prefix
8246 argument, or by inserting the heading marker by hand. For example, if the
8247 cursor is after \"*****\", then the tree will be shifted to level 5.
8249 If optional TREE is given, use this text instead of the kill ring.
8251 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8252 move back over whitespace before inserting, and move point to the end of
8253 the inserted text when done."
8254 (interactive "P")
8255 (setq tree (or tree (and kill-ring (current-kill 0))))
8256 (unless (org-kill-is-subtree-p tree)
8257 (user-error "%s"
8258 (substitute-command-keys
8259 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8260 (org-with-limited-levels
8261 (let* ((visp (not (outline-invisible-p)))
8262 (txt tree)
8263 (^re_ "\\(\\*+\\)[ \t]*")
8264 (old-level (if (string-match org-outline-regexp-bol txt)
8265 (- (match-end 0) (match-beginning 0) 1)
8266 -1))
8267 (force-level (cond (level (prefix-numeric-value level))
8268 ((and (looking-at "[ \t]*$")
8269 (string-match
8270 "^\\*+$" (buffer-substring
8271 (point-at-bol) (point))))
8272 (- (match-end 1) (match-beginning 1)))
8273 ((and (bolp)
8274 (looking-at org-outline-regexp))
8275 (- (match-end 0) (point) 1))))
8276 (previous-level (save-excursion
8277 (condition-case nil
8278 (progn
8279 (outline-previous-visible-heading 1)
8280 (if (looking-at ^re_)
8281 (- (match-end 0) (match-beginning 0) 1)
8283 (error 1))))
8284 (next-level (save-excursion
8285 (condition-case nil
8286 (progn
8287 (or (looking-at org-outline-regexp)
8288 (outline-next-visible-heading 1))
8289 (if (looking-at ^re_)
8290 (- (match-end 0) (match-beginning 0) 1)
8292 (error 1))))
8293 (new-level (or force-level (max previous-level next-level)))
8294 (shift (if (or (= old-level -1)
8295 (= new-level -1)
8296 (= old-level new-level))
8298 (- new-level old-level)))
8299 (delta (if (> shift 0) -1 1))
8300 (func (if (> shift 0) 'org-demote 'org-promote))
8301 (org-odd-levels-only nil)
8302 beg end newend)
8303 ;; Remove the forced level indicator
8304 (if force-level
8305 (delete-region (point-at-bol) (point)))
8306 ;; Paste
8307 (beginning-of-line (if (bolp) 1 2))
8308 (setq beg (point))
8309 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8310 (insert-before-markers txt)
8311 (unless (string-match "\n\\'" txt) (insert "\n"))
8312 (setq newend (point))
8313 (org-reinstall-markers-in-region beg)
8314 (setq end (point))
8315 (goto-char beg)
8316 (skip-chars-forward " \t\n\r")
8317 (setq beg (point))
8318 (if (and (outline-invisible-p) visp)
8319 (save-excursion (outline-show-heading)))
8320 ;; Shift if necessary
8321 (unless (= shift 0)
8322 (save-restriction
8323 (narrow-to-region beg end)
8324 (while (not (= shift 0))
8325 (org-map-region func (point-min) (point-max))
8326 (setq shift (+ delta shift)))
8327 (goto-char (point-min))
8328 (setq newend (point-max))))
8329 (when (or (org-called-interactively-p 'interactive) for-yank)
8330 (message "Clipboard pasted as level %d subtree" new-level))
8331 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8332 kill-ring
8333 (eq org-subtree-clip (current-kill 0))
8334 org-subtree-clip-folded)
8335 ;; The tree was folded before it was killed/copied
8336 (hide-subtree))
8337 (and for-yank (goto-char newend)))))
8339 (defun org-kill-is-subtree-p (&optional txt)
8340 "Check if the current kill is an outline subtree, or a set of trees.
8341 Returns nil if kill does not start with a headline, or if the first
8342 headline level is not the largest headline level in the tree.
8343 So this will actually accept several entries of equal levels as well,
8344 which is OK for `org-paste-subtree'.
8345 If optional TXT is given, check this string instead of the current kill."
8346 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8347 (re (org-get-limited-outline-regexp))
8348 (^re (concat "^" re))
8349 (start-level (and kill
8350 (string-match
8351 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8352 kill)
8353 (- (match-end 2) (match-beginning 2) 1)))
8354 (start (1+ (or (match-beginning 2) -1))))
8355 (if (not start-level)
8356 (progn
8357 nil) ;; does not even start with a heading
8358 (catch 'exit
8359 (while (setq start (string-match ^re kill (1+ start)))
8360 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8361 (throw 'exit nil)))
8362 t))))
8364 (defvar org-markers-to-move nil
8365 "Markers that should be moved with a cut-and-paste operation.
8366 Those markers are stored together with their positions relative to
8367 the start of the region.")
8369 (defun org-save-markers-in-region (beg end)
8370 "Check markers in region.
8371 If these markers are between BEG and END, record their position relative
8372 to BEG, so that after moving the block of text, we can put the markers back
8373 into place.
8374 This function gets called just before an entry or tree gets cut from the
8375 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8376 called immediately, to move the markers with the entries."
8377 (setq org-markers-to-move nil)
8378 (when (featurep 'org-clock)
8379 (org-clock-save-markers-for-cut-and-paste beg end))
8380 (when (featurep 'org-agenda)
8381 (org-agenda-save-markers-for-cut-and-paste beg end)))
8383 (defun org-check-and-save-marker (marker beg end)
8384 "Check if MARKER is between BEG and END.
8385 If yes, remember the marker and the distance to BEG."
8386 (when (and (marker-buffer marker)
8387 (equal (marker-buffer marker) (current-buffer)))
8388 (if (and (>= marker beg) (< marker end))
8389 (push (cons marker (- marker beg)) org-markers-to-move))))
8391 (defun org-reinstall-markers-in-region (beg)
8392 "Move all remembered markers to their position relative to BEG."
8393 (mapc (lambda (x)
8394 (move-marker (car x) (+ beg (cdr x))))
8395 org-markers-to-move)
8396 (setq org-markers-to-move nil))
8398 (defun org-narrow-to-subtree ()
8399 "Narrow buffer to the current subtree."
8400 (interactive)
8401 (save-excursion
8402 (save-match-data
8403 (org-with-limited-levels
8404 (narrow-to-region
8405 (progn (org-back-to-heading t) (point))
8406 (progn (org-end-of-subtree t t)
8407 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8408 (point)))))))
8410 (defun org-narrow-to-block ()
8411 "Narrow buffer to the current block."
8412 (interactive)
8413 (let* ((case-fold-search t)
8414 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8415 "^[ \t]*#\\+end_.*")))
8416 (if blockp
8417 (narrow-to-region (car blockp) (cdr blockp))
8418 (user-error "Not in a block"))))
8420 (eval-when-compile
8421 (defvar org-property-drawer-re))
8423 (defvar org-property-start-re) ;; defined below
8424 (defun org-clone-subtree-with-time-shift (n &optional shift)
8425 "Clone the task (subtree) at point N times.
8426 The clones will be inserted as siblings.
8428 In interactive use, the user will be prompted for the number of
8429 clones to be produced. If the entry has a timestamp, the user
8430 will also be prompted for a time shift, which may be a repeater
8431 as used in time stamps, for example `+3d'. To disable this,
8432 you can call the function with a universal prefix argument.
8434 When a valid repeater is given and the entry contains any time
8435 stamps, the clones will become a sequence in time, with time
8436 stamps in the subtree shifted for each clone produced. If SHIFT
8437 is nil or the empty string, time stamps will be left alone. The
8438 ID property of the original subtree is removed.
8440 If the original subtree did contain time stamps with a repeater,
8441 the following will happen:
8442 - the repeater will be removed in each clone
8443 - an additional clone will be produced, with the current, unshifted
8444 date(s) in the entry.
8445 - the original entry will be placed *after* all the clones, with
8446 repeater intact.
8447 - the start days in the repeater in the original entry will be shifted
8448 to past the last clone.
8449 In this way you can spell out a number of instances of a repeating task,
8450 and still retain the repeater to cover future instances of the task."
8451 (interactive "nNumber of clones to produce: ")
8452 (let ((shift
8453 (or shift
8454 (if (and (not (equal current-prefix-arg '(4)))
8455 (save-excursion
8456 (re-search-forward org-ts-regexp-both
8457 (save-excursion
8458 (org-end-of-subtree t)
8459 (point)) t)))
8460 (read-from-minibuffer
8461 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8462 ""))) ;; No time shift
8463 (n-no-remove -1)
8464 (drawer-re org-drawer-regexp)
8465 beg end template task idprop
8466 shift-n shift-what doshift nmin nmax)
8467 (if (not (and (integerp n) (> n 0)))
8468 (error "Invalid number of replications %s" n))
8469 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8470 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8471 shift)))
8472 (error "Invalid shift specification %s" shift))
8473 (when doshift
8474 (setq shift-n (string-to-number (match-string 1 shift))
8475 shift-what (cdr (assoc (match-string 2 shift)
8476 '(("d" . day) ("w" . week)
8477 ("m" . month) ("y" . year))))))
8478 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8479 (setq nmin 1 nmax n)
8480 (org-back-to-heading t)
8481 (setq beg (point))
8482 (setq idprop (org-entry-get nil "ID"))
8483 (org-end-of-subtree t t)
8484 (or (bolp) (insert "\n"))
8485 (setq end (point))
8486 (setq template (buffer-substring beg end))
8487 (when (and doshift
8488 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8489 (delete-region beg end)
8490 (setq end beg)
8491 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8492 (goto-char end)
8493 (loop for n from nmin to nmax do
8494 ;; prepare clone
8495 (with-temp-buffer
8496 (insert template)
8497 (org-mode)
8498 (goto-char (point-min))
8499 (org-show-subtree)
8500 (and idprop (if org-clone-delete-id
8501 (org-entry-delete nil "ID")
8502 (org-id-get-create t)))
8503 (unless (= n 0)
8504 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8505 (kill-whole-line))
8506 (goto-char (point-min))
8507 (while (re-search-forward drawer-re nil t)
8508 (mapc (lambda (d)
8509 (org-remove-empty-drawer-at d (point))) org-drawers)))
8510 (goto-char (point-min))
8511 (when doshift
8512 (while (re-search-forward org-ts-regexp-both nil t)
8513 (org-timestamp-change (* n shift-n) shift-what))
8514 (unless (= n n-no-remove)
8515 (goto-char (point-min))
8516 (while (re-search-forward org-ts-regexp nil t)
8517 (save-excursion
8518 (goto-char (match-beginning 0))
8519 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8520 (delete-region (match-beginning 1) (match-end 1)))))))
8521 (setq task (buffer-string)))
8522 (insert task))
8523 (goto-char beg)))
8525 ;;; Outline Sorting
8527 (defun org-sort (with-case)
8528 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8529 Optional argument WITH-CASE means sort case-sensitively."
8530 (interactive "P")
8531 (cond
8532 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8533 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8535 (org-call-with-arg 'org-sort-entries with-case))))
8537 (defun org-sort-remove-invisible (s)
8538 "Remove invisible links from string S."
8539 (remove-text-properties 0 (length s) org-rm-props s)
8540 (while (string-match org-bracket-link-regexp s)
8541 (setq s (replace-match (if (match-end 2)
8542 (match-string 3 s)
8543 (match-string 1 s)) t t s)))
8544 (let ((st (format " %s " s)))
8545 (while (string-match org-emph-re st)
8546 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8547 (setq s (substring st 1 -1)))
8550 (defvar org-priority-regexp) ; defined later in the file
8552 (defvar org-after-sorting-entries-or-items-hook nil
8553 "Hook that is run after a bunch of entries or items have been sorted.
8554 When children are sorted, the cursor is in the parent line when this
8555 hook gets called. When a region or a plain list is sorted, the cursor
8556 will be in the first entry of the sorted region/list.")
8558 (defun org-sort-entries
8559 (&optional with-case sorting-type getkey-func compare-func property)
8560 "Sort entries on a certain level of an outline tree.
8561 If there is an active region, the entries in the region are sorted.
8562 Else, if the cursor is before the first entry, sort the top-level items.
8563 Else, the children of the entry at point are sorted.
8565 Sorting can be alphabetically, numerically, by date/time as given by
8566 a time stamp, by a property, by priority order, or by a custom function.
8568 The command prompts for the sorting type unless it has been given to the
8569 function through the SORTING-TYPE argument, which needs to be a character,
8570 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8571 precise meaning of each character:
8573 n Numerically, by converting the beginning of the entry/item to a number.
8574 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8575 o By order of TODO keywords.
8576 t By date/time, either the first active time stamp in the entry, or, if
8577 none exist, by the first inactive one.
8578 s By the scheduled date/time.
8579 d By deadline date/time.
8580 c By creation time, which is assumed to be the first inactive time stamp
8581 at the beginning of a line.
8582 p By priority according to the cookie.
8583 r By the value of a property.
8585 Capital letters will reverse the sort order.
8587 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8588 called with point at the beginning of the record. It must return either
8589 a string or a number that should serve as the sorting key for that record.
8591 Comparing entries ignores case by default. However, with an optional argument
8592 WITH-CASE, the sorting considers case as well.
8594 Sorting is done against the visible part of the headlines, it ignores hidden
8595 links."
8596 (interactive "P")
8597 (let ((case-func (if with-case 'identity 'downcase))
8598 (cmstr
8599 ;; The clock marker is lost when using `sort-subr', let's
8600 ;; store the clocking string.
8601 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8602 (save-excursion
8603 (goto-char org-clock-marker)
8604 (looking-back "^.*") (match-string-no-properties 0))))
8605 start beg end stars re re2
8606 txt what tmp)
8607 ;; Find beginning and end of region to sort
8608 (cond
8609 ((org-region-active-p)
8610 ;; we will sort the region
8611 (setq end (region-end)
8612 what "region")
8613 (goto-char (region-beginning))
8614 (if (not (org-at-heading-p)) (outline-next-heading))
8615 (setq start (point)))
8616 ((or (org-at-heading-p)
8617 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8618 ;; we will sort the children of the current headline
8619 (org-back-to-heading)
8620 (setq start (point)
8621 end (progn (org-end-of-subtree t t)
8622 (or (bolp) (insert "\n"))
8623 (org-back-over-empty-lines)
8624 (point))
8625 what "children")
8626 (goto-char start)
8627 (show-subtree)
8628 (outline-next-heading))
8630 ;; we will sort the top-level entries in this file
8631 (goto-char (point-min))
8632 (or (org-at-heading-p) (outline-next-heading))
8633 (setq start (point))
8634 (goto-char (point-max))
8635 (beginning-of-line 1)
8636 (when (looking-at ".*?\\S-")
8637 ;; File ends in a non-white line
8638 (end-of-line 1)
8639 (insert "\n"))
8640 (setq end (point-max))
8641 (setq what "top-level")
8642 (goto-char start)
8643 (show-all)))
8645 (setq beg (point))
8646 (if (>= beg end) (user-error "Nothing to sort"))
8648 (looking-at "\\(\\*+\\)")
8649 (setq stars (match-string 1)
8650 re (concat "^" (regexp-quote stars) " +")
8651 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8652 txt (buffer-substring beg end))
8653 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8654 (if (and (not (equal stars "*")) (string-match re2 txt))
8655 (user-error "Region to sort contains a level above the first entry"))
8657 (unless sorting-type
8658 (message
8659 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8660 [t]ime [s]cheduled [d]eadline [c]reated
8661 A/N/P/R/O/F/T/S/D/C means reversed:"
8662 what)
8663 (setq sorting-type (read-char-exclusive))
8665 (unless getkey-func
8666 (and (= (downcase sorting-type) ?f)
8667 (setq getkey-func
8668 (org-icompleting-read "Sort using function: "
8669 obarray 'fboundp t nil nil))
8670 (setq getkey-func (intern getkey-func))))
8672 (and (= (downcase sorting-type) ?r)
8673 (not property)
8674 (setq property
8675 (org-icompleting-read "Property: "
8676 (mapcar 'list (org-buffer-property-keys t))
8677 nil t))))
8679 (message "Sorting entries...")
8681 (save-restriction
8682 (narrow-to-region start end)
8683 (let ((dcst (downcase sorting-type))
8684 (case-fold-search nil)
8685 (now (current-time)))
8686 (sort-subr
8687 (/= dcst sorting-type)
8688 ;; This function moves to the beginning character of the "record" to
8689 ;; be sorted.
8690 (lambda nil
8691 (if (re-search-forward re nil t)
8692 (goto-char (match-beginning 0))
8693 (goto-char (point-max))))
8694 ;; This function moves to the last character of the "record" being
8695 ;; sorted.
8696 (lambda nil
8697 (save-match-data
8698 (condition-case nil
8699 (outline-forward-same-level 1)
8700 (error
8701 (goto-char (point-max))))))
8702 ;; This function returns the value that gets sorted against.
8703 (lambda nil
8704 (cond
8705 ((= dcst ?n)
8706 (if (looking-at org-complex-heading-regexp)
8707 (string-to-number (org-sort-remove-invisible (match-string 4)))
8708 nil))
8709 ((= dcst ?a)
8710 (if (looking-at org-complex-heading-regexp)
8711 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8712 nil))
8713 ((= dcst ?t)
8714 (let ((end (save-excursion (outline-next-heading) (point))))
8715 (if (or (re-search-forward org-ts-regexp end t)
8716 (re-search-forward org-ts-regexp-both end t))
8717 (org-time-string-to-seconds (match-string 0))
8718 (org-float-time now))))
8719 ((= dcst ?c)
8720 (let ((end (save-excursion (outline-next-heading) (point))))
8721 (if (re-search-forward
8722 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8723 end t)
8724 (org-time-string-to-seconds (match-string 0))
8725 (org-float-time now))))
8726 ((= dcst ?s)
8727 (let ((end (save-excursion (outline-next-heading) (point))))
8728 (if (re-search-forward org-scheduled-time-regexp end t)
8729 (org-time-string-to-seconds (match-string 1))
8730 (org-float-time now))))
8731 ((= dcst ?d)
8732 (let ((end (save-excursion (outline-next-heading) (point))))
8733 (if (re-search-forward org-deadline-time-regexp end t)
8734 (org-time-string-to-seconds (match-string 1))
8735 (org-float-time now))))
8736 ((= dcst ?p)
8737 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8738 (string-to-char (match-string 2))
8739 org-default-priority))
8740 ((= dcst ?r)
8741 (or (org-entry-get nil property) ""))
8742 ((= dcst ?o)
8743 (if (looking-at org-complex-heading-regexp)
8744 (- 9999 (length (member (match-string 2)
8745 org-todo-keywords-1)))))
8746 ((= dcst ?f)
8747 (if getkey-func
8748 (progn
8749 (setq tmp (funcall getkey-func))
8750 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8751 tmp)
8752 (error "Invalid key function `%s'" getkey-func)))
8753 (t (error "Invalid sorting type `%c'" sorting-type))))
8755 (cond
8756 ((= dcst ?a) 'string<)
8757 ((= dcst ?f) compare-func)
8758 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8759 (run-hooks 'org-after-sorting-entries-or-items-hook)
8760 ;; Reset the clock marker if needed
8761 (when cmstr
8762 (save-excursion
8763 (goto-char start)
8764 (search-forward cmstr nil t)
8765 (move-marker org-clock-marker (point))))
8766 (message "Sorting entries...done")))
8768 (defun org-do-sort (table what &optional with-case sorting-type)
8769 "Sort TABLE of WHAT according to SORTING-TYPE.
8770 The user will be prompted for the SORTING-TYPE if the call to this
8771 function does not specify it. WHAT is only for the prompt, to indicate
8772 what is being sorted. The sorting key will be extracted from
8773 the car of the elements of the table.
8774 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8775 (unless sorting-type
8776 (message
8777 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8778 what)
8779 (setq sorting-type (read-char-exclusive)))
8780 (let ((dcst (downcase sorting-type))
8781 extractfun comparefun)
8782 ;; Define the appropriate functions
8783 (cond
8784 ((= dcst ?n)
8785 (setq extractfun 'string-to-number
8786 comparefun (if (= dcst sorting-type) '< '>)))
8787 ((= dcst ?a)
8788 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8789 (lambda(x) (downcase (org-sort-remove-invisible x))))
8790 comparefun (if (= dcst sorting-type)
8791 'string<
8792 (lambda (a b) (and (not (string< a b))
8793 (not (string= a b)))))))
8794 ((= dcst ?t)
8795 (setq extractfun
8796 (lambda (x)
8797 (if (or (string-match org-ts-regexp x)
8798 (string-match org-ts-regexp-both x))
8799 (org-float-time
8800 (org-time-string-to-time (match-string 0 x)))
8802 comparefun (if (= dcst sorting-type) '< '>)))
8803 (t (error "Invalid sorting type `%c'" sorting-type)))
8805 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8806 table)
8807 (lambda (a b) (funcall comparefun (car a) (car b))))))
8810 ;;; The orgstruct minor mode
8812 ;; Define a minor mode which can be used in other modes in order to
8813 ;; integrate the org-mode structure editing commands.
8815 ;; This is really a hack, because the org-mode structure commands use
8816 ;; keys which normally belong to the major mode. Here is how it
8817 ;; works: The minor mode defines all the keys necessary to operate the
8818 ;; structure commands, but wraps the commands into a function which
8819 ;; tests if the cursor is currently at a headline or a plain list
8820 ;; item. If that is the case, the structure command is used,
8821 ;; temporarily setting many Org-mode variables like regular
8822 ;; expressions for filling etc. However, when any of those keys is
8823 ;; used at a different location, function uses `key-binding' to look
8824 ;; up if the key has an associated command in another currently active
8825 ;; keymap (minor modes, major mode, global), and executes that
8826 ;; command. There might be problems if any of the keys is otherwise
8827 ;; used as a prefix key.
8829 (defcustom orgstruct-heading-prefix-regexp nil
8830 "Regexp that matches the custom prefix of Org headlines in
8831 orgstruct(++)-mode."
8832 :group 'org
8833 :version "24.4"
8834 :package-version '(Org . "8.0")
8835 :type 'string)
8836 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8838 (defcustom orgstruct-setup-hook nil
8839 "Hook run after orgstruct-mode-map is filled."
8840 :group 'org
8841 :version "24.4"
8842 :package-version '(Org . "8.0")
8843 :type 'hook)
8845 (defvar orgstruct-initialized nil)
8847 (defvar org-local-vars nil
8848 "List of local variables, for use by `orgstruct-mode'.")
8850 ;;;###autoload
8851 (define-minor-mode orgstruct-mode
8852 "Toggle the minor mode `orgstruct-mode'.
8853 This mode is for using Org-mode structure commands in other
8854 modes. The following keys behave as if Org-mode were active, if
8855 the cursor is on a headline, or on a plain list item (both as
8856 defined by Org-mode)."
8857 nil " OrgStruct" (make-sparse-keymap)
8858 (funcall (if orgstruct-mode
8859 'add-to-invisibility-spec
8860 'remove-from-invisibility-spec)
8861 '(outline . t))
8862 (when orgstruct-mode
8863 (org-load-modules-maybe)
8864 (unless orgstruct-initialized
8865 (orgstruct-setup)
8866 (setq orgstruct-initialized t))))
8868 ;;;###autoload
8869 (defun turn-on-orgstruct ()
8870 "Unconditionally turn on `orgstruct-mode'."
8871 (orgstruct-mode 1))
8873 (defvar org-fb-vars nil)
8874 (make-variable-buffer-local 'org-fb-vars)
8875 (defun orgstruct++-mode (&optional arg)
8876 "Toggle `orgstruct-mode', the enhanced version of it.
8877 In addition to setting orgstruct-mode, this also exports all
8878 indentation and autofilling variables from org-mode into the
8879 buffer. It will also recognize item context in multiline items."
8880 (interactive "P")
8881 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8882 (if (< arg 1)
8883 (progn (orgstruct-mode -1)
8884 (mapc (lambda(v)
8885 (org-set-local (car v)
8886 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8887 org-fb-vars))
8888 (orgstruct-mode 1)
8889 (setq org-fb-vars nil)
8890 (let (var val)
8891 (mapc
8892 (lambda (x)
8893 (when (string-match
8894 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8895 (symbol-name (car x)))
8896 (setq var (car x) val (nth 1 x))
8897 (push (list var `(quote ,(eval var))) org-fb-vars)
8898 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8899 org-local-vars)
8900 (org-set-local 'orgstruct-is-++ t))))
8902 (defvar orgstruct-is-++ nil
8903 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8904 (make-variable-buffer-local 'orgstruct-is-++)
8906 ;;;###autoload
8907 (defun turn-on-orgstruct++ ()
8908 "Unconditionally turn on `orgstruct++-mode'."
8909 (orgstruct++-mode 1))
8911 (defun orgstruct-error ()
8912 "Error when there is no default binding for a structure key."
8913 (interactive)
8914 (funcall (if (fboundp 'user-error)
8915 'user-error
8916 'error)
8917 "This key has no function outside structure elements"))
8919 (defun orgstruct-setup ()
8920 "Setup orgstruct keymap."
8921 (dolist (cell '((org-demote . t)
8922 (org-metaleft . t)
8923 (org-metaright . t)
8924 (org-promote . t)
8925 (org-shiftmetaleft . t)
8926 (org-shiftmetaright . t)
8927 org-backward-element
8928 org-backward-heading-same-level
8929 org-ctrl-c-ret
8930 org-ctrl-c-minus
8931 org-ctrl-c-star
8932 org-cycle
8933 org-forward-heading-same-level
8934 org-insert-heading
8935 org-insert-heading-respect-content
8936 org-kill-note-or-show-branches
8937 org-mark-subtree
8938 org-meta-return
8939 org-metadown
8940 org-metaup
8941 org-narrow-to-subtree
8942 org-promote-subtree
8943 org-reveal
8944 org-shiftdown
8945 org-shiftleft
8946 org-shiftmetadown
8947 org-shiftmetaup
8948 org-shiftright
8949 org-shifttab
8950 org-shifttab
8951 org-shiftup
8952 org-show-subtree
8953 org-sort
8954 org-up-element
8955 outline-demote
8956 outline-next-visible-heading
8957 outline-previous-visible-heading
8958 outline-promote
8959 outline-up-heading
8960 show-children))
8961 (let ((f (or (car-safe cell) cell))
8962 (disable-when-heading-prefix (cdr-safe cell)))
8963 (when (fboundp f)
8964 (dolist (binding (nconc (where-is-internal f org-mode-map)
8965 (where-is-internal f outline-mode-map)))
8966 ;; TODO use local-function-key-map
8967 (dolist (rep '(("<tab>" . "TAB")
8968 ("<return>" . "RET")
8969 ("<escape>" . "ESC")
8970 ("<delete>" . "DEL")))
8971 (setq binding (read-kbd-macro
8972 (let ((case-fold-search))
8973 (replace-regexp-in-string
8974 (regexp-quote (cdr rep))
8975 (car rep)
8976 (key-description binding))))))
8977 (let ((key (lookup-key orgstruct-mode-map binding)))
8978 (when (or (not key) (numberp key))
8979 (condition-case nil
8980 (org-defkey orgstruct-mode-map
8981 binding
8982 (orgstruct-make-binding f binding disable-when-heading-prefix))
8983 (error nil))))))))
8984 (run-hooks 'orgstruct-setup-hook))
8986 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8987 "Create a function for binding in the structure minor mode.
8988 FUN is the command to call inside a table. KEY is the key that
8989 should be checked in for a command to execute outside of tables.
8990 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8991 if `orgstruct-heading-prefix-regexp' is non-nil."
8992 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8993 (let ((nname name)
8994 (i 0))
8995 (while (fboundp (intern nname))
8996 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8997 (setq name (intern nname)))
8998 (eval
8999 (let ((bindings '((org-heading-regexp
9000 (concat "^"
9001 orgstruct-heading-prefix-regexp
9002 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9003 (org-outline-regexp
9004 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9005 (org-outline-regexp-bol
9006 (concat "^" org-outline-regexp))
9007 (outline-regexp org-outline-regexp)
9008 (outline-heading-end-regexp "\n")
9009 (outline-level 'org-outline-level)
9010 (outline-heading-alist))))
9011 `(defun ,name (arg)
9012 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9013 "Outside of structure, run the binding of `"
9014 (key-description key) "'."
9015 (when disable-when-heading-prefix
9016 (concat
9017 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9018 "back to the default binding due to limitations of Org's implementation of\n"
9019 "`" (symbol-name fun) "'.")))
9020 (interactive "p")
9021 (let* ((disable
9022 ,(when disable-when-heading-prefix
9023 '(and orgstruct-heading-prefix-regexp
9024 (not (string= orgstruct-heading-prefix-regexp "")))))
9025 (fallback
9026 (or disable
9027 (not
9028 (let* ,bindings
9029 (org-context-p 'headline 'item
9030 ,(when (memq fun '(org-insert-heading))
9031 '(when orgstruct-is-++
9032 'item-body))))))))
9033 (if fallback
9034 (let* ((orgstruct-mode)
9035 (binding
9036 (loop with key = ,key
9037 for rep in
9038 '(nil
9039 ("<\\([^>]*\\)tab>" . "\\1TAB")
9040 ("<\\([^>]*\\)return>" . "\\1RET")
9041 ("<\\([^>]*\\)escape>" . "\\1ESC")
9042 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9044 (when rep
9045 (setq key (read-kbd-macro
9046 (let ((case-fold-search))
9047 (replace-regexp-in-string
9048 (car rep)
9049 (cdr rep)
9050 (key-description key))))))
9051 thereis (key-binding key))))
9052 (if (keymapp binding)
9053 (set-temporary-overlay-map binding)
9054 (let ((func (or binding
9055 (unless disable
9056 'orgstruct-error))))
9057 (when func
9058 (call-interactively func)))))
9059 (org-run-like-in-org-mode
9060 (lambda ()
9061 (interactive)
9062 (let* ,bindings
9063 (call-interactively ',fun)))))))))
9064 name))
9066 (defun org-contextualize-keys (alist contexts)
9067 "Return valid elements in ALIST depending on CONTEXTS.
9069 `org-agenda-custom-commands' or `org-capture-templates' are the
9070 values used for ALIST, and `org-agenda-custom-commands-contexts'
9071 or `org-capture-templates-contexts' are the associated contexts
9072 definitions."
9073 (let ((contexts
9074 ;; normalize contexts
9075 (mapcar
9076 (lambda(c) (cond ((listp (cadr c))
9077 (list (car c) (car c) (cadr c)))
9078 ((string= "" (cadr c))
9079 (list (car c) (car c) (caddr c)))
9080 (t c))) contexts))
9081 (a alist) c r s)
9082 ;; loop over all commands or templates
9083 (while (setq c (pop a))
9084 (let (vrules repl)
9085 (cond
9086 ((not (assoc (car c) contexts))
9087 (push c r))
9088 ((and (assoc (car c) contexts)
9089 (setq vrules (org-contextualize-validate-key
9090 (car c) contexts)))
9091 (mapc (lambda (vr)
9092 (when (not (equal (car vr) (cadr vr)))
9093 (setq repl vr))) vrules)
9094 (if (not repl) (push c r)
9095 (push (cadr repl) s)
9096 (push
9097 (cons (car c)
9098 (cdr (or (assoc (cadr repl) alist)
9099 (error "Undefined key `%s' as contextual replacement for `%s'"
9100 (cadr repl) (car c)))))
9101 r))))))
9102 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9103 (delq
9105 (delete-dups
9106 (mapcar (lambda (x)
9107 (let ((tpl (car x)))
9108 (when (not (delq
9110 (mapcar (lambda(y)
9111 (equal y tpl)) s))) x)))
9112 (reverse r))))))
9114 (defun org-contextualize-validate-key (key contexts)
9115 "Check CONTEXTS for agenda or capture KEY."
9116 (let (r rr res)
9117 (while (setq r (pop contexts))
9118 (mapc
9119 (lambda (rr)
9120 (when
9121 (and (equal key (car r))
9122 (if (functionp rr) (funcall rr)
9123 (or (and (eq (car rr) 'in-file)
9124 (buffer-file-name)
9125 (string-match (cdr rr) (buffer-file-name)))
9126 (and (eq (car rr) 'in-mode)
9127 (string-match (cdr rr) (symbol-name major-mode)))
9128 (and (eq (car rr) 'in-buffer)
9129 (string-match (cdr rr) (buffer-name)))
9130 (when (and (eq (car rr) 'not-in-file)
9131 (buffer-file-name))
9132 (not (string-match (cdr rr) (buffer-file-name))))
9133 (when (eq (car rr) 'not-in-mode)
9134 (not (string-match (cdr rr) (symbol-name major-mode))))
9135 (when (eq (car rr) 'not-in-buffer)
9136 (not (string-match (cdr rr) (buffer-name)))))))
9137 (push r res)))
9138 (car (last r))))
9139 (delete-dups (delq nil res))))
9141 (defun org-context-p (&rest contexts)
9142 "Check if local context is any of CONTEXTS.
9143 Possible values in the list of contexts are `table', `headline', and `item'."
9144 (let ((pos (point)))
9145 (goto-char (point-at-bol))
9146 (prog1 (or (and (memq 'table contexts)
9147 (looking-at "[ \t]*|"))
9148 (and (memq 'headline contexts)
9149 (looking-at org-outline-regexp))
9150 (and (memq 'item contexts)
9151 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9152 (and (memq 'item-body contexts)
9153 (org-in-item-p)))
9154 (goto-char pos))))
9156 (defun org-get-local-variables ()
9157 "Return a list of all local variables in an Org mode buffer."
9158 (let (varlist)
9159 (with-current-buffer (get-buffer-create "*Org tmp*")
9160 (erase-buffer)
9161 (org-mode)
9162 (setq varlist (buffer-local-variables)))
9163 (kill-buffer "*Org tmp*")
9164 (delq nil
9165 (mapcar
9166 (lambda (x)
9167 (setq x
9168 (if (symbolp x)
9169 (list x)
9170 (list (car x) (cdr x))))
9171 (if (and (not (get (car x) 'org-state))
9172 (string-match
9173 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9174 (symbol-name (car x))))
9175 x nil))
9176 varlist))))
9178 (defun org-clone-local-variables (from-buffer &optional regexp)
9179 "Clone local variables from FROM-BUFFER.
9180 Optional argument REGEXP selects variables to clone."
9181 (mapc
9182 (lambda (pair)
9183 (and (symbolp (car pair))
9184 (or (null regexp)
9185 (string-match regexp (symbol-name (car pair))))
9186 (set (make-local-variable (car pair))
9187 (cdr pair))))
9188 (buffer-local-variables from-buffer)))
9190 ;;;###autoload
9191 (defun org-run-like-in-org-mode (cmd)
9192 "Run a command, pretending that the current buffer is in Org-mode.
9193 This will temporarily bind local variables that are typically bound in
9194 Org-mode to the values they have in Org-mode, and then interactively
9195 call CMD."
9196 (org-load-modules-maybe)
9197 (unless org-local-vars
9198 (setq org-local-vars (org-get-local-variables)))
9199 (let (binds)
9200 (dolist (var org-local-vars)
9201 (when (or (not (boundp (car var)))
9202 (eq (symbol-value (car var))
9203 (default-value (car var))))
9204 (push (list (car var) `(quote ,(cadr var))) binds)))
9205 (eval `(let ,binds
9206 (call-interactively (quote ,cmd))))))
9208 ;;;; Archiving
9210 (defun org-get-category (&optional pos force-refresh)
9211 "Get the category applying to position POS."
9212 (save-match-data
9213 (if force-refresh (org-refresh-category-properties))
9214 (let ((pos (or pos (point))))
9215 (or (get-text-property pos 'org-category)
9216 (progn (org-refresh-category-properties)
9217 (get-text-property pos 'org-category))))))
9219 (defun org-refresh-category-properties ()
9220 "Refresh category text properties in the buffer."
9221 (let ((case-fold-search t)
9222 (inhibit-read-only t)
9223 (def-cat (cond
9224 ((null org-category)
9225 (if buffer-file-name
9226 (file-name-sans-extension
9227 (file-name-nondirectory buffer-file-name))
9228 "???"))
9229 ((symbolp org-category) (symbol-name org-category))
9230 (t org-category)))
9231 beg end cat pos optionp)
9232 (org-with-silent-modifications
9233 (save-excursion
9234 (save-restriction
9235 (widen)
9236 (goto-char (point-min))
9237 (put-text-property (point) (point-max) 'org-category def-cat)
9238 (while (re-search-forward
9239 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9240 (setq pos (match-end 0)
9241 optionp (equal (char-after (match-beginning 0)) ?#)
9242 cat (org-trim (match-string 2)))
9243 (if optionp
9244 (setq beg (point-at-bol) end (point-max))
9245 (org-back-to-heading t)
9246 (setq beg (point) end (org-end-of-subtree t t)))
9247 (put-text-property beg end 'org-category cat)
9248 (put-text-property beg end 'org-category-position beg)
9249 (goto-char pos)))))))
9251 (defun org-refresh-properties (dprop tprop)
9252 "Refresh buffer text properties.
9253 DPROP is the drawer property and TPROP is the corresponding text
9254 property to set."
9255 (let ((case-fold-search t)
9256 (inhibit-read-only t) p)
9257 (org-with-silent-modifications
9258 (save-excursion
9259 (save-restriction
9260 (widen)
9261 (goto-char (point-min))
9262 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9263 (setq p (org-match-string-no-properties 1))
9264 (save-excursion
9265 (org-back-to-heading t)
9266 (put-text-property
9267 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9270 ;;;; Link Stuff
9272 ;;; Link abbreviations
9274 (defun org-link-expand-abbrev (link)
9275 "Apply replacements as defined in `org-link-abbrev-alist'."
9276 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9277 (let* ((key (match-string 1 link))
9278 (as (or (assoc key org-link-abbrev-alist-local)
9279 (assoc key org-link-abbrev-alist)))
9280 (tag (and (match-end 2) (match-string 3 link)))
9281 rpl)
9282 (if (not as)
9283 link
9284 (setq rpl (cdr as))
9285 (cond
9286 ((symbolp rpl) (funcall rpl tag))
9287 ((string-match "%(\\([^)]+\\))" rpl)
9288 (replace-match
9289 (save-match-data
9290 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9291 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9292 ((string-match "%h" rpl)
9293 (replace-match (url-hexify-string (or tag "")) t t rpl))
9294 (t (concat rpl tag)))))
9295 link))
9297 ;;; Storing and inserting links
9299 (defvar org-insert-link-history nil
9300 "Minibuffer history for links inserted with `org-insert-link'.")
9302 (defvar org-stored-links nil
9303 "Contains the links stored with `org-store-link'.")
9305 (defvar org-store-link-plist nil
9306 "Plist with info about the most recently link created with `org-store-link'.")
9308 (defvar org-link-protocols nil
9309 "Link protocols added to Org-mode using `org-add-link-type'.")
9311 (defvar org-store-link-functions nil
9312 "List of functions that are called to create and store a link.
9313 Each function will be called in turn until one returns a non-nil
9314 value. Each function should check if it is responsible for creating
9315 this link (for example by looking at the major mode).
9316 If not, it must exit and return nil.
9317 If yes, it should return a non-nil value after a calling
9318 `org-store-link-props' with a list of properties and values.
9319 Special properties are:
9321 :type The link prefix, like \"http\". This must be given.
9322 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9323 This is obligatory as well.
9324 :description Optional default description for the second pair
9325 of brackets in an Org-mode link. The user can still change
9326 this when inserting this link into an Org-mode buffer.
9328 In addition to these, any additional properties can be specified
9329 and then used in capture templates.")
9331 (defun org-add-link-type (type &optional follow export)
9332 "Add TYPE to the list of `org-link-types'.
9333 Re-compute all regular expressions depending on `org-link-types'
9335 FOLLOW and EXPORT are two functions.
9337 FOLLOW should take the link path as the single argument and do whatever
9338 is necessary to follow the link, for example find a file or display
9339 a mail message.
9341 EXPORT should format the link path for export to one of the export formats.
9342 It should be a function accepting three arguments:
9344 path the path of the link, the text after the prefix (like \"http:\")
9345 desc the description of the link, if any, or a description added by
9346 org-export-normalize-links if there is none
9347 format the export format, a symbol like `html' or `latex' or `ascii'..
9349 The function may use the FORMAT information to return different values
9350 depending on the format. The return value will be put literally into
9351 the exported file. If the return value is nil, this means Org should
9352 do what it normally does with links which do not have EXPORT defined.
9354 Org-mode has a built-in default for exporting links. If you are happy with
9355 this default, there is no need to define an export function for the link
9356 type. For a simple example of an export function, see `org-bbdb.el'."
9357 (add-to-list 'org-link-types type t)
9358 (org-make-link-regexps)
9359 (if (assoc type org-link-protocols)
9360 (setcdr (assoc type org-link-protocols) (list follow export))
9361 (push (list type follow export) org-link-protocols)))
9363 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9364 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9366 ;;;###autoload
9367 (defun org-store-link (arg)
9368 "\\<org-mode-map>Store an org-link to the current location.
9369 This link is added to `org-stored-links' and can later be inserted
9370 into an org-buffer with \\[org-insert-link].
9372 For some link types, a prefix arg is interpreted.
9373 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9374 For file links, arg negates `org-context-in-file-links'.
9376 A double prefix arg force skipping storing functions that are not
9377 part of Org's core.
9379 A triple prefix arg force storing a link for each line in the
9380 active region."
9381 (interactive "P")
9382 (org-load-modules-maybe)
9383 (if (and (equal arg '(64)) (org-region-active-p))
9384 (save-excursion
9385 (let ((end (region-end)))
9386 (goto-char (region-beginning))
9387 (set-mark (point))
9388 (while (< (point-at-eol) end)
9389 (move-end-of-line 1) (activate-mark)
9390 (let (current-prefix-arg)
9391 (call-interactively 'org-store-link))
9392 (move-beginning-of-line 2)
9393 (set-mark (point)))))
9394 (org-with-limited-levels
9395 (setq org-store-link-plist nil)
9396 (let (link cpltxt desc description search
9397 txt custom-id agenda-link sfuns sfunsn)
9398 (cond
9400 ;; Store a link using an external link type
9401 ((and (not (equal arg '(16)))
9402 (setq sfuns
9403 (delq
9404 nil (mapcar (lambda (f)
9405 (let (fs) (if (funcall f) (push f fs))))
9406 org-store-link-functions))
9407 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9408 (or (and (cdr sfuns)
9409 (funcall (intern
9410 (completing-read
9411 "Which function for creating the link? "
9412 sfunsn t (car sfunsn)))))
9413 (funcall (caar sfuns)))
9414 (setq link (plist-get org-store-link-plist :link)
9415 desc (or (plist-get org-store-link-plist
9416 :description) link))))
9418 ;; Store a link from a source code buffer
9419 ((org-src-edit-buffer-p)
9420 (let (label gc)
9421 (while (or (not label)
9422 (save-excursion
9423 (save-restriction
9424 (widen)
9425 (goto-char (point-min))
9426 (re-search-forward
9427 (regexp-quote (format org-coderef-label-format label))
9428 nil t))))
9429 (when label (message "Label exists already") (sit-for 2))
9430 (setq label (read-string "Code line label: " label)))
9431 (end-of-line 1)
9432 (setq link (format org-coderef-label-format label))
9433 (setq gc (- 79 (length link)))
9434 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9435 (insert link)
9436 (setq link (concat "(" label ")") desc nil)))
9438 ;; We are in the agenda, link to referenced location
9439 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9440 (let ((m (or (get-text-property (point) 'org-hd-marker)
9441 (get-text-property (point) 'org-marker))))
9442 (when m
9443 (org-with-point-at m
9444 (setq agenda-link
9445 (if (org-called-interactively-p 'any)
9446 (call-interactively 'org-store-link)
9447 (org-store-link nil)))))))
9449 ((eq major-mode 'calendar-mode)
9450 (let ((cd (calendar-cursor-to-date)))
9451 (setq link
9452 (format-time-string
9453 (car org-time-stamp-formats)
9454 (apply 'encode-time
9455 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9456 nil nil nil))))
9457 (org-store-link-props :type "calendar" :date cd)))
9459 ((eq major-mode 'help-mode)
9460 (setq link (concat "help:" (save-excursion
9461 (goto-char (point-min))
9462 (looking-at "^[^ ]+")
9463 (match-string 0))))
9464 (org-store-link-props :type "help"))
9466 ((eq major-mode 'w3-mode)
9467 (setq cpltxt (if (and (buffer-name)
9468 (not (string-match "Untitled" (buffer-name))))
9469 (buffer-name)
9470 (url-view-url t))
9471 link (url-view-url t))
9472 (org-store-link-props :type "w3" :url (url-view-url t)))
9474 ((eq major-mode 'image-mode)
9475 (setq cpltxt (concat "file:"
9476 (abbreviate-file-name buffer-file-name))
9477 link cpltxt)
9478 (org-store-link-props :type "image" :file buffer-file-name))
9480 ;; In dired, store a link to the file of the current line
9481 ((eq major-mode 'dired-mode)
9482 (let ((file (dired-get-filename nil t)))
9483 (setq file (if file
9484 (abbreviate-file-name
9485 (expand-file-name (dired-get-filename nil t)))
9486 ;; otherwise, no file so use current directory.
9487 default-directory))
9488 (setq cpltxt (concat "file:" file)
9489 link cpltxt)))
9491 ((setq search (run-hook-with-args-until-success
9492 'org-create-file-search-functions))
9493 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9494 "::" search))
9495 (setq cpltxt (or description link)))
9497 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9498 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9499 (cond
9500 ;; Store a link using the target at point
9501 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9502 (setq cpltxt
9503 (concat "file:"
9504 (abbreviate-file-name
9505 (buffer-file-name (buffer-base-buffer)))
9506 "::" (match-string 1))
9507 link cpltxt))
9508 ((and (featurep 'org-id)
9509 (or (eq org-id-link-to-org-use-id t)
9510 (and (org-called-interactively-p 'any)
9511 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9512 (and (eq org-id-link-to-org-use-id
9513 'create-if-interactive-and-no-custom-id)
9514 (not custom-id))))
9515 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9516 ;; Store a link using the ID at point
9517 (setq link (condition-case nil
9518 (prog1 (org-id-store-link)
9519 (setq desc (plist-get org-store-link-plist
9520 :description)))
9521 (error
9522 ;; Probably before first headline, link only to file
9523 (concat "file:"
9524 (abbreviate-file-name
9525 (buffer-file-name (buffer-base-buffer))))))))
9527 ;; Just link to current headline
9528 (setq cpltxt (concat "file:"
9529 (abbreviate-file-name
9530 (buffer-file-name (buffer-base-buffer)))))
9531 ;; Add a context search string
9532 (when (org-xor org-context-in-file-links arg)
9533 (let* ((ee (org-element-at-point))
9534 (et (org-element-type ee))
9535 (ev (plist-get (cadr ee) :value))
9536 (ek (plist-get (cadr ee) :key))
9537 (eok (and (stringp ek) (string-match "name" ek))))
9538 (setq txt (cond
9539 ((org-at-heading-p) nil)
9540 ((and (eq et 'keyword) eok) ev)
9541 ((org-region-active-p)
9542 (buffer-substring (region-beginning) (region-end)))))
9543 (when (or (null txt) (string-match "\\S-" txt))
9544 (setq cpltxt
9545 (concat cpltxt "::"
9546 (condition-case nil
9547 (org-make-org-heading-search-string txt)
9548 (error "")))
9549 desc (or (and (eq et 'keyword) eok ev)
9550 (nth 4 (ignore-errors (org-heading-components)))
9551 "NONE")))))
9552 (if (string-match "::\\'" cpltxt)
9553 (setq cpltxt (substring cpltxt 0 -2)))
9554 (setq link cpltxt))))
9556 ((buffer-file-name (buffer-base-buffer))
9557 ;; Just link to this file here.
9558 (setq cpltxt (concat "file:"
9559 (abbreviate-file-name
9560 (buffer-file-name (buffer-base-buffer)))))
9561 ;; Add a context string.
9562 (when (org-xor org-context-in-file-links arg)
9563 (setq txt (if (org-region-active-p)
9564 (buffer-substring (region-beginning) (region-end))
9565 (buffer-substring (point-at-bol) (point-at-eol))))
9566 ;; Only use search option if there is some text.
9567 (when (string-match "\\S-" txt)
9568 (setq cpltxt
9569 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9570 desc "NONE")))
9571 (setq link cpltxt))
9573 ((org-called-interactively-p 'interactive)
9574 (user-error "No method for storing a link from this buffer"))
9576 (t (setq link nil)))
9578 ;; We're done setting link and desc, clean up
9579 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9580 (setq link (or link cpltxt)
9581 desc (or desc cpltxt))
9582 (cond ((equal desc "NONE") (setq desc nil))
9583 ((string-match org-bracket-link-analytic-regexp desc)
9584 (let ((d0 (match-string 3 desc))
9585 (p0 (match-string 5 desc)))
9586 (setq desc
9587 (replace-regexp-in-string
9588 org-bracket-link-regexp
9589 (concat (or p0 d0)
9590 (if (equal (length (match-string 0 desc))
9591 (length desc)) "*" "")) desc)))))
9593 ;; Return the link
9594 (if (not (and (or (org-called-interactively-p 'any)
9595 executing-kbd-macro) link))
9596 (or agenda-link (and link (org-make-link-string link desc)))
9597 (push (list link desc) org-stored-links)
9598 (message "Stored: %s" (or desc link))
9599 (when custom-id
9600 (setq link (concat "file:" (abbreviate-file-name
9601 (buffer-file-name)) "::#" custom-id))
9602 (push (list link desc) org-stored-links)))))))
9604 (defun org-store-link-props (&rest plist)
9605 "Store link properties, extract names and addresses."
9606 (let (x adr)
9607 (when (setq x (plist-get plist :from))
9608 (setq adr (mail-extract-address-components x))
9609 (setq plist (plist-put plist :fromname (car adr)))
9610 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9611 (when (setq x (plist-get plist :to))
9612 (setq adr (mail-extract-address-components x))
9613 (setq plist (plist-put plist :toname (car adr)))
9614 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9615 (let ((from (plist-get plist :from))
9616 (to (plist-get plist :to)))
9617 (when (and from to org-from-is-user-regexp)
9618 (setq plist
9619 (plist-put plist :fromto
9620 (if (string-match org-from-is-user-regexp from)
9621 (concat "to %t")
9622 (concat "from %f"))))))
9623 (setq org-store-link-plist plist))
9625 (defun org-add-link-props (&rest plist)
9626 "Add these properties to the link property list."
9627 (let (key value)
9628 (while plist
9629 (setq key (pop plist) value (pop plist))
9630 (setq org-store-link-plist
9631 (plist-put org-store-link-plist key value)))))
9633 (defun org-email-link-description (&optional fmt)
9634 "Return the description part of an email link.
9635 This takes information from `org-store-link-plist' and formats it
9636 according to FMT (default from `org-email-link-description-format')."
9637 (setq fmt (or fmt org-email-link-description-format))
9638 (let* ((p org-store-link-plist)
9639 (to (plist-get p :toaddress))
9640 (from (plist-get p :fromaddress))
9641 (table
9642 (list
9643 (cons "%c" (plist-get p :fromto))
9644 (cons "%F" (plist-get p :from))
9645 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9646 (cons "%T" (plist-get p :to))
9647 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9648 (cons "%s" (plist-get p :subject))
9649 (cons "%d" (plist-get p :date))
9650 (cons "%m" (plist-get p :message-id)))))
9651 (when (string-match "%c" fmt)
9652 ;; Check if the user wrote this message
9653 (if (and org-from-is-user-regexp from to
9654 (save-match-data (string-match org-from-is-user-regexp from)))
9655 (setq fmt (replace-match "to %t" t t fmt))
9656 (setq fmt (replace-match "from %f" t t fmt))))
9657 (org-replace-escapes fmt table)))
9659 (defun org-make-org-heading-search-string (&optional string)
9660 "Make search string for the current headline or STRING."
9661 (let ((s (or string
9662 (and (derived-mode-p 'org-mode)
9663 (save-excursion
9664 (org-back-to-heading t)
9665 (org-element-property :raw-value (org-element-at-point))))))
9666 (lines org-context-in-file-links))
9667 (or string (setq s (concat "*" s))) ; Add * for headlines
9668 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9669 (when (and string (integerp lines) (> lines 0))
9670 (let ((slines (org-split-string s "\n")))
9671 (when (< lines (length slines))
9672 (setq s (mapconcat
9673 'identity
9674 (reverse (nthcdr (- (length slines) lines)
9675 (reverse slines))) "\n")))))
9676 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9678 (defun org-make-link-string (link &optional description)
9679 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9680 (unless (string-match "\\S-" link)
9681 (error "Empty link"))
9682 (when (and description
9683 (stringp description)
9684 (not (string-match "\\S-" description)))
9685 (setq description nil))
9686 (when (stringp description)
9687 ;; Remove brackets from the description, they are fatal.
9688 (while (string-match "\\[" description)
9689 (setq description (replace-match "{" t t description)))
9690 (while (string-match "\\]" description)
9691 (setq description (replace-match "}" t t description))))
9692 (when (equal link description)
9693 ;; No description needed, it is identical
9694 (setq description nil))
9695 (when (and (not description)
9696 (not (string-match (org-image-file-name-regexp) link))
9697 (not (equal link (org-link-escape link))))
9698 (setq description (org-extract-attributes link)))
9699 (setq link
9700 (cond ((string-match (org-image-file-name-regexp) link) link)
9701 ((string-match org-link-types-re link)
9702 (concat (match-string 1 link)
9703 (org-link-escape (substring link (match-end 1)))))
9704 (t (org-link-escape link))))
9705 (concat "[[" link "]"
9706 (if description (concat "[" description "]") "")
9707 "]"))
9709 (defconst org-link-escape-chars
9710 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9711 "List of characters that should be escaped in link.
9712 This is the list that is used for internal purposes.")
9714 (defconst org-link-escape-chars-browser
9715 '(?\ )
9716 "List of escapes for characters that are problematic in links.
9717 This is the list that is used before handing over to the browser.")
9719 (defun org-link-escape (text &optional table merge)
9720 "Return percent escaped representation of TEXT.
9721 TEXT is a string with the text to escape.
9722 Optional argument TABLE is a list with characters that should be
9723 escaped. When nil, `org-link-escape-chars' is used.
9724 If optional argument MERGE is set, merge TABLE into
9725 `org-link-escape-chars'."
9726 (cond
9727 ((and table merge)
9728 (mapc (lambda (defchr)
9729 (unless (member defchr table)
9730 (setq table (cons defchr table)))) org-link-escape-chars))
9731 ((null table)
9732 (setq table org-link-escape-chars)))
9733 (mapconcat
9734 (lambda (char)
9735 (if (or (member char table)
9736 (and (or (< char 32) (= char 37) (> char 126))
9737 org-url-hexify-p))
9738 (mapconcat (lambda (sequence-element)
9739 (format "%%%.2X" sequence-element))
9740 (or (encode-coding-char char 'utf-8)
9741 (error "Unable to percent escape character: %s"
9742 (char-to-string char))) "")
9743 (char-to-string char))) text ""))
9745 (defun org-link-unescape (str)
9746 "Unhex hexified Unicode strings as returned from the JavaScript function
9747 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9748 (unless (and (null str) (string= "" str))
9749 (let ((pos 0) (case-fold-search t) unhexed)
9750 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9751 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9752 (setq str (replace-match unhexed t t str))
9753 (setq pos (+ pos (length unhexed))))))
9754 str)
9756 (defun org-link-unescape-compound (hex)
9757 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9758 Note: this function also decodes single byte encodings like
9759 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9760 (save-match-data
9761 (let* ((bytes (cdr (split-string hex "%")))
9762 (ret "")
9763 (eat 0)
9764 (sum 0))
9765 (while bytes
9766 (let* ((val (string-to-number (pop bytes) 16))
9767 (shift-xor
9768 (if (= 0 eat)
9769 (cond
9770 ((>= val 252) (cons 6 252))
9771 ((>= val 248) (cons 5 248))
9772 ((>= val 240) (cons 4 240))
9773 ((>= val 224) (cons 3 224))
9774 ((>= val 192) (cons 2 192))
9775 (t (cons 0 0)))
9776 (cons 6 128))))
9777 (if (>= val 192) (setq eat (car shift-xor)))
9778 (setq val (logxor val (cdr shift-xor)))
9779 (setq sum (+ (lsh sum (car shift-xor)) val))
9780 (if (> eat 0) (setq eat (- eat 1)))
9781 (cond
9782 ((= 0 eat) ;multi byte
9783 (setq ret (concat ret (org-char-to-string sum)))
9784 (setq sum 0))
9785 ((not bytes) ; single byte(s)
9786 (setq ret (org-link-unescape-single-byte-sequence hex))))
9787 )) ;; end (while bytes
9788 ret )))
9790 (defun org-link-unescape-single-byte-sequence (hex)
9791 "Unhexify hex-encoded single byte character sequences."
9792 (mapconcat (lambda (byte)
9793 (char-to-string (string-to-number byte 16)))
9794 (cdr (split-string hex "%")) ""))
9796 (defun org-xor (a b)
9797 "Exclusive or."
9798 (if a (not b) b))
9800 (defun org-fixup-message-id-for-http (s)
9801 "Replace special characters in a message id, so it can be used in an http query."
9802 (when (string-match "%" s)
9803 (setq s (mapconcat (lambda (c)
9804 (if (eq c ?%)
9805 "%25"
9806 (char-to-string c)))
9807 s "")))
9808 (while (string-match "<" s)
9809 (setq s (replace-match "%3C" t t s)))
9810 (while (string-match ">" s)
9811 (setq s (replace-match "%3E" t t s)))
9812 (while (string-match "@" s)
9813 (setq s (replace-match "%40" t t s)))
9816 (defun org-link-prettify (link)
9817 "Return a human-readable representation of LINK.
9818 The car of LINK must be a raw link the cdr of LINK must be either
9819 a link description or nil."
9820 (let ((desc (or (cadr link) "<no description>")))
9821 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9822 "<" (car link) ">")))
9824 ;;;###autoload
9825 (defun org-insert-link-global ()
9826 "Insert a link like Org-mode does.
9827 This command can be called in any mode to insert a link in Org-mode syntax."
9828 (interactive)
9829 (org-load-modules-maybe)
9830 (org-run-like-in-org-mode 'org-insert-link))
9832 (defun org-insert-all-links (&optional keep)
9833 "Insert all links in `org-stored-links'."
9834 (interactive "P")
9835 (let ((links (copy-sequence org-stored-links)) l)
9836 (while (setq l (if keep (pop links) (pop org-stored-links)))
9837 (insert "- ")
9838 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9839 (insert "\n"))))
9841 (defun org-link-fontify-links-to-this-file ()
9842 "Fontify links to the current file in `org-stored-links'."
9843 (let ((f (buffer-file-name)) a b)
9844 (setq a (mapcar (lambda(l)
9845 (let ((ll (car l)))
9846 (when (and (string-match "^file:\\(.+\\)::" ll)
9847 (equal f (expand-file-name (match-string 1 ll))))
9848 ll)))
9849 org-stored-links))
9850 (when (featurep 'org-id)
9851 (setq b (mapcar (lambda(l)
9852 (let ((ll (car l)))
9853 (when (and (string-match "^id:\\(.+\\)$" ll)
9854 (equal f (expand-file-name
9855 (or (org-id-find-id-file
9856 (match-string 1 ll)) ""))))
9857 ll)))
9858 org-stored-links)))
9859 (mapcar (lambda(l)
9860 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9861 (delq nil (append a b)))))
9863 (defvar org-link-links-in-this-file nil)
9864 (defun org-insert-link (&optional complete-file link-location default-description)
9865 "Insert a link. At the prompt, enter the link.
9867 Completion can be used to insert any of the link protocol prefixes like
9868 http or ftp in use.
9870 The history can be used to select a link previously stored with
9871 `org-store-link'. When the empty string is entered (i.e. if you just
9872 press RET at the prompt), the link defaults to the most recently
9873 stored link. As SPC triggers completion in the minibuffer, you need to
9874 use M-SPC or C-q SPC to force the insertion of a space character.
9876 You will also be prompted for a description, and if one is given, it will
9877 be displayed in the buffer instead of the link.
9879 If there is already a link at point, this command will allow you to edit link
9880 and description parts.
9882 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9883 be selected using completion. The path to the file will be relative to the
9884 current directory if the file is in the current directory or a subdirectory.
9885 Otherwise, the link will be the absolute path as completed in the minibuffer
9886 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9887 option `org-link-file-path-type'.
9889 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9890 the current directory or below.
9892 With three \\[universal-argument] prefixes, negate the meaning of
9893 `org-keep-stored-link-after-insertion'.
9895 If `org-make-link-description-function' is non-nil, this function will be
9896 called with the link target, and the result will be the default
9897 link description.
9899 If the LINK-LOCATION parameter is non-nil, this value will be
9900 used as the link location instead of reading one interactively.
9902 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9903 be used as the default description."
9904 (interactive "P")
9905 (let* ((wcf (current-window-configuration))
9906 (origbuf (current-buffer))
9907 (region (if (org-region-active-p)
9908 (buffer-substring (region-beginning) (region-end))))
9909 (remove (and region (list (region-beginning) (region-end))))
9910 (desc region)
9911 tmphist ; byte-compile incorrectly complains about this
9912 (link link-location)
9913 (abbrevs org-link-abbrev-alist-local)
9914 entry file all-prefixes auto-desc)
9915 (cond
9916 (link-location) ; specified by arg, just use it.
9917 ((org-in-regexp org-bracket-link-regexp 1)
9918 ;; We do have a link at point, and we are going to edit it.
9919 (setq remove (list (match-beginning 0) (match-end 0)))
9920 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9921 (setq link (read-string "Link: "
9922 (org-link-unescape
9923 (org-match-string-no-properties 1)))))
9924 ((or (org-in-regexp org-angle-link-re)
9925 (org-in-regexp org-plain-link-re))
9926 ;; Convert to bracket link
9927 (setq remove (list (match-beginning 0) (match-end 0))
9928 link (read-string "Link: "
9929 (org-remove-angle-brackets (match-string 0)))))
9930 ((member complete-file '((4) (16)))
9931 ;; Completing read for file names.
9932 (setq link (org-file-complete-link complete-file)))
9934 ;; Read link, with completion for stored links.
9935 (org-link-fontify-links-to-this-file)
9936 (org-switch-to-buffer-other-window "*Org Links*")
9937 (with-current-buffer "*Org Links*"
9938 (erase-buffer)
9939 (insert "Insert a link.
9940 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9941 (when org-stored-links
9942 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9943 (insert (mapconcat 'org-link-prettify
9944 (reverse org-stored-links) "\n")))
9945 (goto-char (point-min)))
9946 (let ((cw (selected-window)))
9947 (select-window (get-buffer-window "*Org Links*" 'visible))
9948 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9949 (unless (pos-visible-in-window-p (point-max))
9950 (org-fit-window-to-buffer))
9951 (and (window-live-p cw) (select-window cw)))
9952 ;; Fake a link history, containing the stored links.
9953 (setq tmphist (append (mapcar 'car org-stored-links)
9954 org-insert-link-history))
9955 (setq all-prefixes (append (mapcar 'car abbrevs)
9956 (mapcar 'car org-link-abbrev-alist)
9957 org-link-types))
9958 (unwind-protect
9959 (progn
9960 (setq link
9961 (org-completing-read
9962 "Link: "
9963 (append
9964 (mapcar (lambda (x) (concat x ":"))
9965 all-prefixes)
9966 (mapcar 'car org-stored-links))
9967 nil nil nil
9968 'tmphist
9969 (caar org-stored-links)))
9970 (if (not (string-match "\\S-" link))
9971 (user-error "No link selected"))
9972 (mapc (lambda(l)
9973 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9974 org-stored-links)
9975 (if (or (member link all-prefixes)
9976 (and (equal ":" (substring link -1))
9977 (member (substring link 0 -1) all-prefixes)
9978 (setq link (substring link 0 -1))))
9979 (setq link (with-current-buffer origbuf
9980 (org-link-try-special-completion link)))))
9981 (set-window-configuration wcf)
9982 (kill-buffer "*Org Links*"))
9983 (setq entry (assoc link org-stored-links))
9984 (or entry (push link org-insert-link-history))
9985 (setq desc (or desc (nth 1 entry)))))
9987 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9988 (not org-keep-stored-link-after-insertion))
9989 (setq org-stored-links (delq (assoc link org-stored-links)
9990 org-stored-links)))
9992 (if (string-match org-plain-link-re link)
9993 ;; URL-like link, normalize the use of angular brackets.
9994 (setq link (org-remove-angle-brackets link)))
9996 ;; Check if we are linking to the current file with a search
9997 ;; option If yes, simplify the link by using only the search
9998 ;; option.
9999 (when (and buffer-file-name
10000 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10001 (let* ((path (match-string 1 link))
10002 (case-fold-search nil)
10003 (search (match-string 2 link)))
10004 (save-match-data
10005 (if (equal (file-truename buffer-file-name) (file-truename path))
10006 ;; We are linking to this same file, with a search option
10007 (setq link search)))))
10009 ;; Check if we can/should use a relative path. If yes, simplify the link
10010 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10011 (let* ((type (match-string 1 link))
10012 (path (match-string 2 link))
10013 (origpath path)
10014 (case-fold-search nil))
10015 (cond
10016 ((or (eq org-link-file-path-type 'absolute)
10017 (equal complete-file '(16)))
10018 (setq path (abbreviate-file-name (expand-file-name path))))
10019 ((eq org-link-file-path-type 'noabbrev)
10020 (setq path (expand-file-name path)))
10021 ((eq org-link-file-path-type 'relative)
10022 (setq path (file-relative-name path)))
10024 (save-match-data
10025 (if (string-match (concat "^" (regexp-quote
10026 (expand-file-name
10027 (file-name-as-directory
10028 default-directory))))
10029 (expand-file-name path))
10030 ;; We are linking a file with relative path name.
10031 (setq path (substring (expand-file-name path)
10032 (match-end 0)))
10033 (setq path (abbreviate-file-name (expand-file-name path)))))))
10034 (setq link (concat type path))
10035 (if (equal desc origpath)
10036 (setq desc path))))
10038 (if org-make-link-description-function
10039 (setq desc
10040 (or (condition-case nil
10041 (funcall org-make-link-description-function link desc)
10042 (error (progn (message "Can't get link description from `%s'"
10043 (symbol-name org-make-link-description-function))
10044 (sit-for 2) nil)))
10045 (read-string "Description: " default-description)))
10046 (if default-description (setq desc default-description)
10047 (setq desc (or (and auto-desc desc)
10048 (read-string "Description: " desc)))))
10050 (unless (string-match "\\S-" desc) (setq desc nil))
10051 (if remove (apply 'delete-region remove))
10052 (insert (org-make-link-string link desc))))
10054 (defun org-link-try-special-completion (type)
10055 "If there is completion support for link type TYPE, offer it."
10056 (let ((fun (intern (concat "org-" type "-complete-link"))))
10057 (if (functionp fun)
10058 (funcall fun)
10059 (read-string "Link (no completion support): " (concat type ":")))))
10061 (defun org-file-complete-link (&optional arg)
10062 "Create a file link using completion."
10063 (let (file link)
10064 (setq file (org-iread-file-name "File: "))
10065 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10066 (pwd1 (file-name-as-directory (abbreviate-file-name
10067 (expand-file-name ".")))))
10068 (cond
10069 ((equal arg '(16))
10070 (setq link (concat
10071 "file:"
10072 (abbreviate-file-name (expand-file-name file)))))
10073 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10074 (setq link (concat "file:" (match-string 1 file))))
10075 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10076 (expand-file-name file))
10077 (setq link (concat
10078 "file:" (match-string 1 (expand-file-name file)))))
10079 (t (setq link (concat "file:" file)))))
10080 link))
10082 (defun org-iread-file-name (&rest args)
10083 "Read-file-name using `ido-mode' speedup if available.
10084 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10085 See `read-file-name' for a description of parameters."
10086 (org-without-partial-completion
10087 (if (and org-completion-use-ido
10088 (fboundp 'ido-read-file-name)
10089 (boundp 'ido-mode) ido-mode
10090 (listp (second args)))
10091 (let ((ido-enter-matching-directory nil))
10092 (apply 'ido-read-file-name args))
10093 (apply 'read-file-name args))))
10095 (defun org-completing-read (&rest args)
10096 "Completing-read with SPACE being a normal character."
10097 (let ((enable-recursive-minibuffers t)
10098 (minibuffer-local-completion-map
10099 (copy-keymap minibuffer-local-completion-map)))
10100 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10101 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10102 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10103 (apply 'org-icompleting-read args)))
10105 (defun org-completing-read-no-i (&rest args)
10106 (let (org-completion-use-ido org-completion-use-iswitchb)
10107 (apply 'org-completing-read args)))
10109 (defun org-iswitchb-completing-read (prompt choices &rest args)
10110 "Use iswitch as a completing-read replacement to choose from choices.
10111 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10112 from."
10113 (let* ((iswitchb-use-virtual-buffers nil)
10114 (iswitchb-make-buflist-hook
10115 (lambda ()
10116 (setq iswitchb-temp-buflist choices))))
10117 (iswitchb-read-buffer prompt)))
10119 (defun org-icompleting-read (&rest args)
10120 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10121 (org-without-partial-completion
10122 (if (and org-completion-use-ido
10123 (fboundp 'ido-completing-read)
10124 (boundp 'ido-mode) ido-mode
10125 (listp (second args)))
10126 (let ((ido-enter-matching-directory nil))
10127 (apply 'ido-completing-read (concat (car args))
10128 (if (consp (car (nth 1 args)))
10129 (mapcar 'car (nth 1 args))
10130 (nth 1 args))
10131 (cddr args)))
10132 (if (and org-completion-use-iswitchb
10133 (boundp 'iswitchb-mode) iswitchb-mode
10134 (listp (second args)))
10135 (apply 'org-iswitchb-completing-read (concat (car args))
10136 (if (consp (car (nth 1 args)))
10137 (mapcar 'car (nth 1 args))
10138 (nth 1 args))
10139 (cddr args))
10140 (apply 'completing-read args)))))
10142 (defun org-extract-attributes (s)
10143 "Extract the attributes cookie from a string and set as text property."
10144 (let (a attr (start 0) key value)
10145 (save-match-data
10146 (when (string-match "{{\\([^}]+\\)}}$" s)
10147 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10148 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10149 (setq key (match-string 1 a) value (match-string 2 a)
10150 start (match-end 0)
10151 attr (plist-put attr (intern key) value))))
10152 (org-add-props s nil 'org-attr attr))
10155 ;;; Opening/following a link
10157 (defvar org-link-search-failed nil)
10159 (defvar org-open-link-functions nil
10160 "Hook for functions finding a plain text link.
10161 These functions must take a single argument, the link content.
10162 They will be called for links that look like [[link text][description]]
10163 when LINK TEXT does not have a protocol like \"http:\" and does not look
10164 like a filename (e.g. \"./blue.png\").
10166 These functions will be called *before* Org attempts to resolve the
10167 link by doing text searches in the current buffer - so if you want a
10168 link \"[[target]]\" to still find \"<<target>>\", your function should
10169 handle this as a special case.
10171 When the function does handle the link, it must return a non-nil value.
10172 If it decides that it is not responsible for this link, it must return
10173 nil to indicate that that Org-mode can continue with other options
10174 like exact and fuzzy text search.")
10176 (defun org-next-link (&optional search-backward)
10177 "Move forward to the next link.
10178 If the link is in hidden text, expose it."
10179 (interactive "P")
10180 (when (and org-link-search-failed (eq this-command last-command))
10181 (goto-char (point-min))
10182 (message "Link search wrapped back to beginning of buffer"))
10183 (setq org-link-search-failed nil)
10184 (let* ((pos (point))
10185 (ct (org-context))
10186 (a (assoc :link ct))
10187 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10188 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10189 ((looking-at org-any-link-re)
10190 ;; Don't stay stuck at link without an org-link face
10191 (forward-char (if search-backward -1 1))))
10192 (if (funcall srch-fun org-any-link-re nil t)
10193 (progn
10194 (goto-char (match-beginning 0))
10195 (if (outline-invisible-p) (org-show-context)))
10196 (goto-char pos)
10197 (setq org-link-search-failed t)
10198 (message "No further link found"))))
10200 (defun org-previous-link ()
10201 "Move backward to the previous link.
10202 If the link is in hidden text, expose it."
10203 (interactive)
10204 (funcall 'org-next-link t))
10206 (defun org-translate-link (s)
10207 "Translate a link string if a translation function has been defined."
10208 (if (and org-link-translation-function
10209 (fboundp org-link-translation-function)
10210 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10211 (progn
10212 (setq s (funcall org-link-translation-function
10213 (match-string 1 s) (match-string 2 s)))
10214 (concat (car s) ":" (cdr s)))
10217 (defun org-translate-link-from-planner (type path)
10218 "Translate a link from Emacs Planner syntax so that Org can follow it.
10219 This is still an experimental function, your mileage may vary."
10220 (cond
10221 ((member type '("http" "https" "news" "ftp"))
10222 ;; standard Internet links are the same.
10223 nil)
10224 ((and (equal type "irc") (string-match "^//" path))
10225 ;; Planner has two / at the beginning of an irc link, we have 1.
10226 ;; We should have zero, actually....
10227 (setq path (substring path 1)))
10228 ((and (equal type "lisp") (string-match "^/" path))
10229 ;; Planner has a slash, we do not.
10230 (setq type "elisp" path (substring path 1)))
10231 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10232 ;; A typical message link. Planner has the id after the final slash,
10233 ;; we separate it with a hash mark
10234 (setq path (concat (match-string 1 path) "#"
10235 (org-remove-angle-brackets (match-string 2 path))))))
10236 (cons type path))
10238 (defun org-find-file-at-mouse (ev)
10239 "Open file link or URL at mouse."
10240 (interactive "e")
10241 (mouse-set-point ev)
10242 (org-open-at-point 'in-emacs))
10244 (defun org-open-at-mouse (ev)
10245 "Open file link or URL at mouse.
10246 See the docstring of `org-open-file' for details."
10247 (interactive "e")
10248 (mouse-set-point ev)
10249 (if (eq major-mode 'org-agenda-mode)
10250 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10251 (org-open-at-point))
10253 (defvar org-window-config-before-follow-link nil
10254 "The window configuration before following a link.
10255 This is saved in case the need arises to restore it.")
10257 (defvar org-open-link-marker (make-marker)
10258 "Marker pointing to the location where `org-open-at-point; was called.")
10260 ;;;###autoload
10261 (defun org-open-at-point-global ()
10262 "Follow a link like Org-mode does.
10263 This command can be called in any mode to follow a link that has
10264 Org-mode syntax."
10265 (interactive)
10266 (org-run-like-in-org-mode 'org-open-at-point))
10268 ;;;###autoload
10269 (defun org-open-link-from-string (s &optional arg reference-buffer)
10270 "Open a link in the string S, as if it was in Org-mode."
10271 (interactive "sLink: \nP")
10272 (let ((reference-buffer (or reference-buffer (current-buffer))))
10273 (with-temp-buffer
10274 (let ((org-inhibit-startup (not reference-buffer)))
10275 (org-mode)
10276 (insert s)
10277 (goto-char (point-min))
10278 (when reference-buffer
10279 (setq org-link-abbrev-alist-local
10280 (with-current-buffer reference-buffer
10281 org-link-abbrev-alist-local)))
10282 (org-open-at-point arg reference-buffer)))))
10284 (defvar org-open-at-point-functions nil
10285 "Hook that is run when following a link at point.
10287 Functions in this hook must return t if they identify and follow
10288 a link at point. If they don't find anything interesting at point,
10289 they must return nil.")
10291 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10292 (defun org-open-at-point (&optional arg reference-buffer)
10293 "Open link at or after point.
10294 If there is no link at point, this function will search forward up to
10295 the end of the current line.
10296 Normally, files will be opened by an appropriate application. If the
10297 optional prefix argument ARG is non-nil, Emacs will visit the file.
10298 With a double prefix argument, try to open outside of Emacs, in the
10299 application the system uses for this file type."
10300 (interactive "P")
10301 ;; if in a code block, then open the block's results
10302 (unless (call-interactively #'org-babel-open-src-block-result)
10303 (org-load-modules-maybe)
10304 (move-marker org-open-link-marker (point))
10305 (setq org-window-config-before-follow-link (current-window-configuration))
10306 (org-remove-occur-highlights nil nil t)
10307 (cond
10308 ((and (org-at-heading-p)
10309 (not (org-at-timestamp-p t))
10310 (not (org-in-regexp
10311 (concat org-plain-link-re "\\|"
10312 org-bracket-link-regexp "\\|"
10313 org-angle-link-re "\\|"
10314 "[ \t]:[^ \t\n]+:[ \t]*$")))
10315 (not (get-text-property (point) 'org-linked-text)))
10316 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10317 (lk0 (car lkall))
10318 (lk (if (stringp lk0) (list lk0) lk0))
10319 (lkend (cdr lkall)))
10320 (mapcar (lambda(l)
10321 (search-forward l nil lkend)
10322 (goto-char (match-beginning 0))
10323 (org-open-at-point))
10324 lk))
10325 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10326 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10327 ((and (org-at-timestamp-p t)
10328 (not (org-in-regexp org-bracket-link-regexp)))
10329 (org-follow-timestamp-link))
10330 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10331 (not (org-in-regexp org-any-link-re)))
10332 (org-footnote-action))
10334 (let (type path link line search (pos (point)))
10335 (catch 'match
10336 (save-excursion
10337 (skip-chars-forward "^]\n\r")
10338 (when (org-in-regexp org-bracket-link-regexp 1)
10339 (setq link (org-extract-attributes
10340 (org-link-unescape (org-match-string-no-properties 1))))
10341 (while (string-match " *\n *" link)
10342 (setq link (replace-match " " t t link)))
10343 (setq link (org-link-expand-abbrev link))
10344 (cond
10345 ((or (file-name-absolute-p link)
10346 (string-match "^\\.\\.?/" link))
10347 (setq type "file" path link))
10348 ((string-match org-link-re-with-space3 link)
10349 (setq type (match-string 1 link) path (match-string 2 link)))
10350 ((string-match "^help:+\\(.+\\)" link)
10351 (setq type "help" path (match-string 1 link)))
10352 (t (setq type "thisfile" path link)))
10353 (throw 'match t)))
10355 (when (get-text-property (point) 'org-linked-text)
10356 (setq type "thisfile"
10357 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10358 (1+ (point)) (point))
10359 path (buffer-substring
10360 (or (previous-single-property-change pos 'org-linked-text)
10361 (point-min))
10362 (or (next-single-property-change pos 'org-linked-text)
10363 (point-max)))
10364 ;; Ensure we will search for a <<<radio>>> link, not
10365 ;; a simple reference like <<ref>>
10366 path (concat "<" path))
10367 (throw 'match t))
10369 (save-excursion
10370 (when (or (org-in-regexp org-angle-link-re)
10371 (let ((match (org-in-regexp org-plain-link-re)))
10372 ;; Check a plain link is not within a bracket link
10373 (and match
10374 (save-excursion
10375 (progn
10376 (goto-char (car match))
10377 (not (org-in-regexp org-bracket-link-regexp))))))
10378 (let ((line_ending (save-excursion (end-of-line) (point))))
10379 ;; We are in a line before a plain or bracket link
10380 (or (re-search-forward org-plain-link-re line_ending t)
10381 (re-search-forward org-bracket-link-regexp line_ending t))))
10382 (setq type (match-string 1)
10383 path (org-link-unescape (match-string 2)))
10384 (throw 'match t)))
10385 (save-excursion
10386 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10387 (setq type "tags"
10388 path (match-string 1))
10389 (while (string-match ":" path)
10390 (setq path (replace-match "+" t t path)))
10391 (throw 'match t)))
10392 (when (org-in-regexp "<\\([^><\n]+\\)>")
10393 (setq type "tree-match"
10394 path (match-string 1))
10395 (throw 'match t)))
10396 (unless path
10397 (user-error "No link found"))
10399 ;; switch back to reference buffer
10400 ;; needed when if called in a temporary buffer through
10401 ;; org-open-link-from-string
10402 (with-current-buffer (or reference-buffer (current-buffer))
10404 ;; Remove any trailing spaces in path
10405 (if (string-match " +\\'" path)
10406 (setq path (replace-match "" t t path)))
10407 (if (and org-link-translation-function
10408 (fboundp org-link-translation-function))
10409 ;; Check if we need to translate the link
10410 (let ((tmp (funcall org-link-translation-function type path)))
10411 (setq type (car tmp) path (cdr tmp))))
10413 (cond
10415 ((assoc type org-link-protocols)
10416 (funcall (nth 1 (assoc type org-link-protocols)) path))
10418 ((equal type "help")
10419 (let ((f-or-v (intern path)))
10420 (cond ((fboundp f-or-v)
10421 (describe-function f-or-v))
10422 ((boundp f-or-v)
10423 (describe-variable f-or-v))
10424 (t (error "Not a known function or variable")))))
10426 ((equal type "mailto")
10427 (let ((cmd (car org-link-mailto-program))
10428 (args (cdr org-link-mailto-program)) args1
10429 (address path) (subject "") a)
10430 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10431 (setq address (match-string 1 path)
10432 subject (org-link-escape (match-string 2 path))))
10433 (while args
10434 (cond
10435 ((not (stringp (car args))) (push (pop args) args1))
10436 (t (setq a (pop args))
10437 (if (string-match "%a" a)
10438 (setq a (replace-match address t t a)))
10439 (if (string-match "%s" a)
10440 (setq a (replace-match subject t t a)))
10441 (push a args1))))
10442 (apply cmd (nreverse args1))))
10444 ((member type '("http" "https" "ftp" "news"))
10445 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10446 (org-link-escape
10447 path org-link-escape-chars-browser)
10448 path))))
10450 ((string= type "doi")
10451 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10452 (org-link-escape
10453 path org-link-escape-chars-browser)
10454 path))))
10456 ((member type '("message"))
10457 (browse-url (concat type ":" path)))
10459 ((string= type "tags")
10460 (org-tags-view arg path))
10462 ((string= type "tree-match")
10463 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10465 ((string= type "file")
10466 (if (string-match "::\\([0-9]+\\)\\'" path)
10467 (setq line (string-to-number (match-string 1 path))
10468 path (substring path 0 (match-beginning 0)))
10469 (if (string-match "::\\(.+\\)\\'" path)
10470 (setq search (match-string 1 path)
10471 path (substring path 0 (match-beginning 0)))))
10472 (if (string-match "[*?{]" (file-name-nondirectory path))
10473 (dired path)
10474 (org-open-file path arg line search)))
10476 ((string= type "shell")
10477 (let ((buf (generate-new-buffer "*Org Shell Output"))
10478 (cmd path))
10479 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10480 (string-match org-confirm-shell-link-not-regexp cmd))
10481 (not org-confirm-shell-link-function)
10482 (funcall org-confirm-shell-link-function
10483 (format "Execute \"%s\" in shell? "
10484 (org-add-props cmd nil
10485 'face 'org-warning))))
10486 (progn
10487 (message "Executing %s" cmd)
10488 (shell-command cmd buf)
10489 (if (featurep 'midnight)
10490 (setq clean-buffer-list-kill-buffer-names
10491 (cons buf clean-buffer-list-kill-buffer-names))))
10492 (error "Abort"))))
10494 ((string= type "elisp")
10495 (let ((cmd path))
10496 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10497 (string-match org-confirm-elisp-link-not-regexp cmd))
10498 (not org-confirm-elisp-link-function)
10499 (funcall org-confirm-elisp-link-function
10500 (format "Execute \"%s\" as elisp? "
10501 (org-add-props cmd nil
10502 'face 'org-warning))))
10503 (message "%s => %s" cmd
10504 (if (equal (string-to-char cmd) ?\()
10505 (eval (read cmd))
10506 (call-interactively (read cmd))))
10507 (error "Abort"))))
10509 ((and (string= type "thisfile")
10510 (run-hook-with-args-until-success
10511 'org-open-link-functions path)))
10513 ((string= type "thisfile")
10514 (if arg
10515 (switch-to-buffer-other-window
10516 (org-get-buffer-for-internal-link (current-buffer)))
10517 (org-mark-ring-push))
10518 (let ((cmd `(org-link-search
10519 ,path
10520 ,(cond ((equal arg '(4)) ''occur)
10521 ((equal arg '(16)) ''org-occur))
10522 ,pos)))
10523 (condition-case nil (let ((org-link-search-inhibit-query t))
10524 (eval cmd))
10525 (error (progn (widen) (eval cmd))))))
10527 (t (browse-url-at-point)))))))
10528 (move-marker org-open-link-marker nil)
10529 (run-hook-with-args 'org-follow-link-hook)))
10531 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10532 "Offer links in the current entry and return the selected link.
10533 If there is only one link, return it.
10534 If NTH is an integer, return the NTH link found.
10535 If ZERO is a string, check also this string for a link, and if
10536 there is one, return it."
10537 (with-current-buffer buffer
10538 (save-excursion
10539 (save-restriction
10540 (widen)
10541 (goto-char marker)
10542 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10543 "\\(" org-angle-link-re "\\)\\|"
10544 "\\(" org-plain-link-re "\\)"))
10545 (cnt ?0)
10546 (in-emacs (if (integerp nth) nil nth))
10547 have-zero end links link c)
10548 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10549 (push (match-string 0 zero) links)
10550 (setq cnt (1- cnt) have-zero t))
10551 (save-excursion
10552 (org-back-to-heading t)
10553 (setq end (save-excursion (outline-next-heading) (point)))
10554 (while (re-search-forward re end t)
10555 (push (match-string 0) links))
10556 (setq links (org-uniquify (reverse links))))
10557 (cond
10558 ((null links)
10559 (message "No links"))
10560 ((equal (length links) 1)
10561 (setq link (car links)))
10562 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10563 (setq link (nth (if have-zero nth (1- nth)) links)))
10564 (t ; we have to select a link
10565 (save-excursion
10566 (save-window-excursion
10567 (delete-other-windows)
10568 (with-output-to-temp-buffer "*Select Link*"
10569 (mapc (lambda (l)
10570 (if (not (string-match org-bracket-link-regexp l))
10571 (princ (format "[%c] %s\n" (incf cnt)
10572 (org-remove-angle-brackets l)))
10573 (if (match-end 3)
10574 (princ (format "[%c] %s (%s)\n" (incf cnt)
10575 (match-string 3 l) (match-string 1 l)))
10576 (princ (format "[%c] %s\n" (incf cnt)
10577 (match-string 1 l))))))
10578 links))
10579 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10580 (message "Select link to open, RET to open all:")
10581 (setq c (read-char-exclusive))
10582 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10583 (when (equal c ?q) (error "Abort"))
10584 (if (equal c ?\C-m)
10585 (setq link links)
10586 (setq nth (- c ?0))
10587 (if have-zero (setq nth (1+ nth)))
10588 (unless (and (integerp nth) (>= (length links) nth))
10589 (user-error "Invalid link selection"))
10590 (setq link (nth (1- nth) links)))))
10591 (cons link end))))))
10593 ;; Add special file links that specify the way of opening
10595 (org-add-link-type "file+sys" 'org-open-file-with-system)
10596 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10597 (defun org-open-file-with-system (path)
10598 "Open file at PATH using the system way of opening it."
10599 (org-open-file path 'system))
10600 (defun org-open-file-with-emacs (path)
10601 "Open file at PATH in Emacs."
10602 (org-open-file path 'emacs))
10605 ;;; File search
10607 (defvar org-create-file-search-functions nil
10608 "List of functions to construct the right search string for a file link.
10609 These functions are called in turn with point at the location to
10610 which the link should point.
10612 A function in the hook should first test if it would like to
10613 handle this file type, for example by checking the `major-mode'
10614 or the file extension. If it decides not to handle this file, it
10615 should just return nil to give other functions a chance. If it
10616 does handle the file, it must return the search string to be used
10617 when following the link. The search string will be part of the
10618 file link, given after a double colon, and `org-open-at-point'
10619 will automatically search for it. If special measures must be
10620 taken to make the search successful, another function should be
10621 added to the companion hook `org-execute-file-search-functions',
10622 which see.
10624 A function in this hook may also use `setq' to set the variable
10625 `description' to provide a suggestion for the descriptive text to
10626 be used for this link when it gets inserted into an Org-mode
10627 buffer with \\[org-insert-link].")
10629 (defvar org-execute-file-search-functions nil
10630 "List of functions to execute a file search triggered by a link.
10632 Functions added to this hook must accept a single argument, the
10633 search string that was part of the file link, the part after the
10634 double colon. The function must first check if it would like to
10635 handle this search, for example by checking the `major-mode' or
10636 the file extension. If it decides not to handle this search, it
10637 should just return nil to give other functions a chance. If it
10638 does handle the search, it must return a non-nil value to keep
10639 other functions from trying.
10641 Each function can access the current prefix argument through the
10642 variable `current-prefix-arg'. Note that a single prefix is used
10643 to force opening a link in Emacs, so it may be good to only use a
10644 numeric or double prefix to guide the search function.
10646 In case this is needed, a function in this hook can also restore
10647 the window configuration before `org-open-at-point' was called using:
10649 (set-window-configuration org-window-config-before-follow-link)")
10651 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10652 (defun org-link-search (s &optional type avoid-pos stealth)
10653 "Search for a link search option.
10654 If S is surrounded by forward slashes, it is interpreted as a
10655 regular expression. In org-mode files, this will create an `org-occur'
10656 sparse tree. In ordinary files, `occur' will be used to list matches.
10657 If the current buffer is in `dired-mode', grep will be used to search
10658 in all files. If AVOID-POS is given, ignore matches near that position.
10660 When optional argument STEALTH is non-nil, do not modify
10661 visibility around point, thus ignoring
10662 `org-show-hierarchy-above', `org-show-following-heading' and
10663 `org-show-siblings' variables."
10664 (let ((case-fold-search t)
10665 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10666 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10667 (append '(("") (" ") ("\t") ("\n"))
10668 org-emphasis-alist)
10669 "\\|") "\\)"))
10670 (pos (point))
10671 (pre nil) (post nil)
10672 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10673 (cond
10674 ;; First check if there are any special search functions
10675 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10676 ;; Now try the builtin stuff
10677 ((and (equal (string-to-char s0) ?#)
10678 (> (length s0) 1)
10679 (save-excursion
10680 (goto-char (point-min))
10681 (and
10682 (re-search-forward
10683 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10684 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10685 (setq type 'dedicated
10686 pos (match-beginning 0))))
10687 ;; There is an exact target for this
10688 (goto-char pos)
10689 (org-back-to-heading t)))
10690 ((save-excursion
10691 (goto-char (point-min))
10692 (and
10693 (re-search-forward
10694 (concat "<<" (regexp-quote s0) ">>") nil t)
10695 (setq type 'dedicated
10696 pos (match-beginning 0))))
10697 ;; There is an exact target for this
10698 (goto-char pos))
10699 ((save-excursion
10700 (goto-char (point-min))
10701 (and
10702 (re-search-forward
10703 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10704 (setq type 'dedicated pos (match-beginning 0))))
10705 ;; Found an element with a matching #+name affiliated keyword.
10706 (goto-char pos))
10707 ((and (string-match "^(\\(.*\\))$" s0)
10708 (save-excursion
10709 (goto-char (point-min))
10710 (and
10711 (re-search-forward
10712 (concat "[^[]" (regexp-quote
10713 (format org-coderef-label-format
10714 (match-string 1 s0))))
10715 nil t)
10716 (setq type 'dedicated
10717 pos (1+ (match-beginning 0))))))
10718 ;; There is a coderef target for this
10719 (goto-char pos))
10720 ((string-match "^/\\(.*\\)/$" s)
10721 ;; A regular expression
10722 (cond
10723 ((derived-mode-p 'org-mode)
10724 (org-occur (match-string 1 s)))
10725 (t (org-do-occur (match-string 1 s)))))
10726 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10727 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10728 (goto-char (point-min))
10729 (cond
10730 ((let (case-fold-search)
10731 (re-search-forward (format org-complex-heading-regexp-format
10732 (regexp-quote s))
10733 nil t))
10734 ;; OK, found a match
10735 (setq type 'dedicated)
10736 (goto-char (match-beginning 0)))
10737 ((and (not org-link-search-inhibit-query)
10738 (eq org-link-search-must-match-exact-headline 'query-to-create)
10739 (y-or-n-p "No match - create this as a new heading? "))
10740 (goto-char (point-max))
10741 (or (bolp) (newline))
10742 (insert "* " s "\n")
10743 (beginning-of-line 0))
10745 (goto-char pos)
10746 (error "No match"))))
10748 ;; A normal search string
10749 (when (equal (string-to-char s) ?*)
10750 ;; Anchor on headlines, post may include tags.
10751 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10752 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10753 s (substring s 1)))
10754 (remove-text-properties
10755 0 (length s)
10756 '(face nil mouse-face nil keymap nil fontified nil) s)
10757 ;; Make a series of regular expressions to find a match
10758 (setq words (org-split-string s "[ \n\r\t]+")
10760 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10761 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10762 "\\)" markers)
10763 re2a_ (concat "\\(" (mapconcat 'downcase words
10764 "[ \t\r\n]+") "\\)[ \t\r\n]")
10765 re2a (concat "[ \t\r\n]" re2a_)
10766 re4_ (concat "\\(" (mapconcat 'downcase words
10767 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10768 re4 (concat "[^a-zA-Z_]" re4_)
10770 re1 (concat pre re2 post)
10771 re3 (concat pre (if pre re4_ re4) post)
10772 re5 (concat pre ".*" re4)
10773 re2 (concat pre re2)
10774 re2a (concat pre (if pre re2a_ re2a))
10775 re4 (concat pre (if pre re4_ re4))
10776 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10777 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10778 re5 "\\)"))
10779 (cond
10780 ((eq type 'org-occur) (org-occur reall))
10781 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10782 (t (goto-char (point-min))
10783 (setq type 'fuzzy)
10784 (if (or (and (org-search-not-self 1 re0 nil t)
10785 (setq type 'dedicated))
10786 (org-search-not-self 1 re1 nil t)
10787 (org-search-not-self 1 re2 nil t)
10788 (org-search-not-self 1 re2a nil t)
10789 (org-search-not-self 1 re3 nil t)
10790 (org-search-not-self 1 re4 nil t)
10791 (org-search-not-self 1 re5 nil t))
10792 (goto-char (match-beginning 1))
10793 (goto-char pos)
10794 (error "No match"))))))
10795 (and (derived-mode-p 'org-mode)
10796 (not stealth)
10797 (org-show-context 'link-search))
10798 type))
10800 (defun org-search-not-self (group &rest args)
10801 "Execute `re-search-forward', but only accept matches that do not
10802 enclose the position of `org-open-link-marker'."
10803 (let ((m org-open-link-marker))
10804 (catch 'exit
10805 (while (apply 're-search-forward args)
10806 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10807 (goto-char (match-end group))
10808 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10809 (> (match-beginning 0) (marker-position m))
10810 (< (match-end 0) (marker-position m)))
10811 (save-match-data
10812 (or (not (org-in-regexp
10813 org-bracket-link-analytic-regexp 1))
10814 (not (match-end 4)) ; no description
10815 (and (<= (match-beginning 4) (point))
10816 (>= (match-end 4) (point))))))
10817 (throw 'exit (point))))))))
10819 (defun org-get-buffer-for-internal-link (buffer)
10820 "Return a buffer to be used for displaying the link target of internal links."
10821 (cond
10822 ((not org-display-internal-link-with-indirect-buffer)
10823 buffer)
10824 ((string-match "(Clone)$" (buffer-name buffer))
10825 (message "Buffer is already a clone, not making another one")
10826 ;; we also do not modify visibility in this case
10827 buffer)
10828 (t ; make a new indirect buffer for displaying the link
10829 (let* ((bn (buffer-name buffer))
10830 (ibn (concat bn "(Clone)"))
10831 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10832 (with-current-buffer ib (org-overview))
10833 ib))))
10835 (defun org-do-occur (regexp &optional cleanup)
10836 "Call the Emacs command `occur'.
10837 If CLEANUP is non-nil, remove the printout of the regular expression
10838 in the *Occur* buffer. This is useful if the regex is long and not useful
10839 to read."
10840 (occur regexp)
10841 (when cleanup
10842 (let ((cwin (selected-window)) win beg end)
10843 (when (setq win (get-buffer-window "*Occur*"))
10844 (select-window win))
10845 (goto-char (point-min))
10846 (when (re-search-forward "match[a-z]+" nil t)
10847 (setq beg (match-end 0))
10848 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10849 (setq end (1- (match-beginning 0)))))
10850 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10851 (goto-char (point-min))
10852 (select-window cwin))))
10854 ;;; The mark ring for links jumps
10856 (defvar org-mark-ring nil
10857 "Mark ring for positions before jumps in Org-mode.")
10858 (defvar org-mark-ring-last-goto nil
10859 "Last position in the mark ring used to go back.")
10860 ;; Fill and close the ring
10861 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10862 (loop for i from 1 to org-mark-ring-length do
10863 (push (make-marker) org-mark-ring))
10864 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10865 org-mark-ring)
10867 (defun org-mark-ring-push (&optional pos buffer)
10868 "Put the current position or POS into the mark ring and rotate it."
10869 (interactive)
10870 (setq pos (or pos (point)))
10871 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10872 (move-marker (car org-mark-ring)
10873 (or pos (point))
10874 (or buffer (current-buffer)))
10875 (message "%s"
10876 (substitute-command-keys
10877 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10879 (defun org-mark-ring-goto (&optional n)
10880 "Jump to the previous position in the mark ring.
10881 With prefix arg N, jump back that many stored positions. When
10882 called several times in succession, walk through the entire ring.
10883 Org-mode commands jumping to a different position in the current file,
10884 or to another Org-mode file, automatically push the old position
10885 onto the ring."
10886 (interactive "p")
10887 (let (p m)
10888 (if (eq last-command this-command)
10889 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10890 (setq p org-mark-ring))
10891 (setq org-mark-ring-last-goto p)
10892 (setq m (car p))
10893 (org-pop-to-buffer-same-window (marker-buffer m))
10894 (goto-char m)
10895 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10897 (defun org-remove-angle-brackets (s)
10898 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10899 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10901 (defun org-add-angle-brackets (s)
10902 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10903 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10905 (defun org-remove-double-quotes (s)
10906 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10907 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10910 ;;; Following specific links
10912 (defun org-follow-timestamp-link ()
10913 "Open an agenda view for the time-stamp date/range at point."
10914 (cond
10915 ((org-at-date-range-p t)
10916 (let ((org-agenda-start-on-weekday)
10917 (t1 (match-string 1))
10918 (t2 (match-string 2)) tt1 tt2)
10919 (setq tt1 (time-to-days (org-time-string-to-time t1))
10920 tt2 (time-to-days (org-time-string-to-time t2)))
10921 (let ((org-agenda-buffer-tmp-name
10922 (format "*Org Agenda(a:%s)"
10923 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10924 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10925 ((org-at-timestamp-p t)
10926 (let ((org-agenda-buffer-tmp-name
10927 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10928 (org-agenda-list nil (time-to-days (org-time-string-to-time
10929 (substring (match-string 1) 0 10)))
10930 1)))
10931 (t (error "This should not happen"))))
10934 ;;; Following file links
10935 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10936 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10937 (declare-function mailcap-mime-info
10938 "mailcap" (string &optional request no-decode))
10939 (defvar org-wait nil)
10940 (defun org-open-file (path &optional in-emacs line search)
10941 "Open the file at PATH.
10942 First, this expands any special file name abbreviations. Then the
10943 configuration variable `org-file-apps' is checked if it contains an
10944 entry for this file type, and if yes, the corresponding command is launched.
10946 If no application is found, Emacs simply visits the file.
10948 With optional prefix argument IN-EMACS, Emacs will visit the file.
10949 With a double \\[universal-argument] \\[universal-argument] \
10950 prefix arg, Org tries to avoid opening in Emacs
10951 and to use an external application to visit the file.
10953 Optional LINE specifies a line to go to, optional SEARCH a string
10954 to search for. If LINE or SEARCH is given, the file will be
10955 opened in Emacs, unless an entry from org-file-apps that makes
10956 use of groups in a regexp matches.
10958 If you want to change the way frames are used when following a
10959 link, please customize `org-link-frame-setup'.
10961 If the file does not exist, an error is thrown."
10962 (let* ((file (if (equal path "")
10963 buffer-file-name
10964 (substitute-in-file-name (expand-file-name path))))
10965 (file-apps (append org-file-apps (org-default-apps)))
10966 (apps (org-remove-if
10967 'org-file-apps-entry-match-against-dlink-p file-apps))
10968 (apps-dlink (org-remove-if-not
10969 'org-file-apps-entry-match-against-dlink-p file-apps))
10970 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10971 (dirp (if remp nil (file-directory-p file)))
10972 (file (if (and dirp org-open-directory-means-index-dot-org)
10973 (concat (file-name-as-directory file) "index.org")
10974 file))
10975 (a-m-a-p (assq 'auto-mode apps))
10976 (dfile (downcase file))
10977 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10978 (link (cond ((and (eq line nil)
10979 (eq search nil))
10980 file)
10981 (line
10982 (concat file "::" (number-to-string line)))
10983 (search
10984 (concat file "::" search))))
10985 (dlink (downcase link))
10986 (old-buffer (current-buffer))
10987 (old-pos (point))
10988 (old-mode major-mode)
10989 ext cmd link-match-data)
10990 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10991 (setq ext (match-string 1 dfile))
10992 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10993 (setq ext (match-string 1 dfile))))
10994 (cond
10995 ((member in-emacs '((16) system))
10996 (setq cmd (cdr (assoc 'system apps))))
10997 (in-emacs (setq cmd 'emacs))
10999 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11000 (and dirp (cdr (assoc 'directory apps)))
11001 ; first, try matching against apps-dlink
11002 ; if we get a match here, store the match data for later
11003 (let ((match (assoc-default dlink apps-dlink
11004 'string-match)))
11005 (if match
11006 (progn (setq link-match-data (match-data))
11007 match)
11008 (progn (setq in-emacs (or in-emacs line search))
11009 nil))) ; if we have no match in apps-dlink,
11010 ; always open the file in emacs if line or search
11011 ; is given (for backwards compatibility)
11012 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11013 'string-match)
11014 (cdr (assoc ext apps))
11015 (cdr (assoc t apps))))))
11016 (when (eq cmd 'system)
11017 (setq cmd (cdr (assoc 'system apps))))
11018 (when (eq cmd 'default)
11019 (setq cmd (cdr (assoc t apps))))
11020 (when (eq cmd 'mailcap)
11021 (require 'mailcap)
11022 (mailcap-parse-mailcaps)
11023 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11024 (command (mailcap-mime-info mime-type)))
11025 (if (stringp command)
11026 (setq cmd command)
11027 (setq cmd 'emacs))))
11028 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11029 (not (file-exists-p file))
11030 (not org-open-non-existing-files))
11031 (user-error "No such file: %s" file))
11032 (cond
11033 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11034 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11035 (while (string-match "['\"]%s['\"]" cmd)
11036 (setq cmd (replace-match "%s" t t cmd)))
11037 (while (string-match "%s" cmd)
11038 (setq cmd (replace-match
11039 (save-match-data
11040 (shell-quote-argument
11041 (convert-standard-filename file)))
11042 t t cmd)))
11044 ;; Replace "%1", "%2" etc. in command with group matches from regex
11045 (save-match-data
11046 (let ((match-index 1)
11047 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11048 (set-match-data link-match-data)
11049 (while (<= match-index number-of-groups)
11050 (let ((regex (concat "%" (number-to-string match-index)))
11051 (replace-with (match-string match-index dlink)))
11052 (while (string-match regex cmd)
11053 (setq cmd (replace-match replace-with t t cmd))))
11054 (setq match-index (+ match-index 1)))))
11056 (save-window-excursion
11057 (message "Running %s...done" cmd)
11058 (start-process-shell-command cmd nil cmd)
11059 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11060 ((or (stringp cmd)
11061 (eq cmd 'emacs))
11062 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11063 (widen)
11064 (if line (org-goto-line line)
11065 (if search (org-link-search search))))
11066 ((consp cmd)
11067 (let ((file (convert-standard-filename file)))
11068 (save-match-data
11069 (set-match-data link-match-data)
11070 (eval cmd))))
11071 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11072 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11073 (or (not (equal old-buffer (current-buffer)))
11074 (not (equal old-pos (point))))
11075 (org-mark-ring-push old-pos old-buffer))))
11077 (defun org-file-apps-entry-match-against-dlink-p (entry)
11078 "This function returns non-nil if `entry' uses a regular
11079 expression which should be matched against the whole link by
11080 org-open-file.
11082 It assumes that is the case when the entry uses a regular
11083 expression which has at least one grouping construct and the
11084 action is either a lisp form or a command string containing
11085 '%1', i.e. using at least one subexpression match as a
11086 parameter."
11087 (let ((selector (car entry))
11088 (action (cdr entry)))
11089 (if (stringp selector)
11090 (and (> (regexp-opt-depth selector) 0)
11091 (or (and (stringp action)
11092 (string-match "%[0-9]" action))
11093 (consp action)))
11094 nil)))
11096 (defun org-default-apps ()
11097 "Return the default applications for this operating system."
11098 (cond
11099 ((eq system-type 'darwin)
11100 org-file-apps-defaults-macosx)
11101 ((eq system-type 'windows-nt)
11102 org-file-apps-defaults-windowsnt)
11103 (t org-file-apps-defaults-gnu)))
11105 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11106 "Convert extensions to regular expressions in the cars of LIST.
11107 Also, weed out any non-string entries, because the return value is used
11108 only for regexp matching.
11109 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11110 point to the symbol `emacs', indicating that the file should
11111 be opened in Emacs."
11112 (append
11113 (delq nil
11114 (mapcar (lambda (x)
11115 (if (not (stringp (car x)))
11117 (if (string-match "\\W" (car x))
11119 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11120 list))
11121 (if add-auto-mode
11122 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11124 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11125 (defun org-file-remote-p (file)
11126 "Test whether FILE specifies a location on a remote system.
11127 Return non-nil if the location is indeed remote.
11129 For example, the filename \"/user@host:/foo\" specifies a location
11130 on the system \"/user@host:\"."
11131 (cond ((fboundp 'file-remote-p)
11132 (file-remote-p file))
11133 ((fboundp 'tramp-handle-file-remote-p)
11134 (tramp-handle-file-remote-p file))
11135 ((and (boundp 'ange-ftp-name-format)
11136 (string-match (car ange-ftp-name-format) file))
11137 t)))
11140 ;;;; Refiling
11142 (defun org-get-org-file ()
11143 "Read a filename, with default directory `org-directory'."
11144 (let ((default (or org-default-notes-file remember-data-file)))
11145 (read-file-name (format "File name [%s]: " default)
11146 (file-name-as-directory org-directory)
11147 default)))
11149 (defun org-notes-order-reversed-p ()
11150 "Check if the current file should receive notes in reversed order."
11151 (cond
11152 ((not org-reverse-note-order) nil)
11153 ((eq t org-reverse-note-order) t)
11154 ((not (listp org-reverse-note-order)) nil)
11155 (t (catch 'exit
11156 (let ((all org-reverse-note-order)
11157 entry)
11158 (while (setq entry (pop all))
11159 (if (string-match (car entry) buffer-file-name)
11160 (throw 'exit (cdr entry))))
11161 nil)))))
11163 (defvar org-refile-target-table nil
11164 "The list of refile targets, created by `org-refile'.")
11166 (defvar org-agenda-new-buffers nil
11167 "Buffers created to visit agenda files.")
11169 (defvar org-refile-cache nil
11170 "Cache for refile targets.")
11172 (defvar org-refile-markers nil
11173 "All the markers used for caching refile locations.")
11175 (defun org-refile-marker (pos)
11176 "Get a new refile marker, but only if caching is in use."
11177 (if (not org-refile-use-cache)
11179 (let ((m (make-marker)))
11180 (move-marker m pos)
11181 (push m org-refile-markers)
11182 m)))
11184 (defun org-refile-cache-clear ()
11185 "Clear the refile cache and disable all the markers."
11186 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11187 (setq org-refile-markers nil)
11188 (setq org-refile-cache nil)
11189 (message "Refile cache has been cleared"))
11191 (defun org-refile-cache-check-set (set)
11192 "Check if all the markers in the cache still have live buffers."
11193 (let (marker)
11194 (catch 'exit
11195 (while (and set (setq marker (nth 3 (pop set))))
11196 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11197 (when (and marker (null (marker-buffer marker)))
11198 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11199 (sit-for 3)
11200 (throw 'exit nil)))
11201 t)))
11203 (defun org-refile-cache-put (set &rest identifiers)
11204 "Push the refile targets SET into the cache, under IDENTIFIERS."
11205 (let* ((key (sha1 (prin1-to-string identifiers)))
11206 (entry (assoc key org-refile-cache)))
11207 (if entry
11208 (setcdr entry set)
11209 (push (cons key set) org-refile-cache))))
11211 (defun org-refile-cache-get (&rest identifiers)
11212 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11213 (cond
11214 ((not org-refile-cache) nil)
11215 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11217 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11218 org-refile-cache))))
11219 (and set (org-refile-cache-check-set set) set)))))
11221 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11222 "Produce a table with refile targets."
11223 (let ((case-fold-search nil)
11224 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11225 (entries (or org-refile-targets '((nil . (:level . 1)))))
11226 targets tgs txt re files f desc descre fast-path-p level pos0)
11227 (message "Getting targets...")
11228 (with-current-buffer (or default-buffer (current-buffer))
11229 (while (setq entry (pop entries))
11230 (setq files (car entry) desc (cdr entry))
11231 (setq fast-path-p nil)
11232 (cond
11233 ((null files) (setq files (list (current-buffer))))
11234 ((eq files 'org-agenda-files)
11235 (setq files (org-agenda-files 'unrestricted)))
11236 ((and (symbolp files) (fboundp files))
11237 (setq files (funcall files)))
11238 ((and (symbolp files) (boundp files))
11239 (setq files (symbol-value files))))
11240 (if (stringp files) (setq files (list files)))
11241 (cond
11242 ((eq (car desc) :tag)
11243 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11244 ((eq (car desc) :todo)
11245 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11246 ((eq (car desc) :regexp)
11247 (setq descre (cdr desc)))
11248 ((eq (car desc) :level)
11249 (setq descre (concat "^\\*\\{" (number-to-string
11250 (if org-odd-levels-only
11251 (1- (* 2 (cdr desc)))
11252 (cdr desc)))
11253 "\\}[ \t]")))
11254 ((eq (car desc) :maxlevel)
11255 (setq fast-path-p t)
11256 (setq descre (concat "^\\*\\{1," (number-to-string
11257 (if org-odd-levels-only
11258 (1- (* 2 (cdr desc)))
11259 (cdr desc)))
11260 "\\}[ \t]")))
11261 (t (error "Bad refiling target description %s" desc)))
11262 (while (setq f (pop files))
11263 (with-current-buffer
11264 (if (bufferp f) f (org-get-agenda-file-buffer f))
11266 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11267 (progn
11268 (if (bufferp f) (setq f (buffer-file-name
11269 (buffer-base-buffer f))))
11270 (setq f (and f (expand-file-name f)))
11271 (if (eq org-refile-use-outline-path 'file)
11272 (push (list (file-name-nondirectory f) f nil nil) tgs))
11273 (save-excursion
11274 (save-restriction
11275 (widen)
11276 (goto-char (point-min))
11277 (while (re-search-forward descre nil t)
11278 (goto-char (setq pos0 (point-at-bol)))
11279 (catch 'next
11280 (when org-refile-target-verify-function
11281 (save-match-data
11282 (or (funcall org-refile-target-verify-function)
11283 (throw 'next t))))
11284 (when (and (looking-at org-complex-heading-regexp)
11285 (not (member (match-string 4) excluded-entries))
11286 (match-string 4))
11287 (setq level (org-reduced-level
11288 (- (match-end 1) (match-beginning 1)))
11289 txt (org-link-display-format (match-string 4))
11290 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11291 re (format org-complex-heading-regexp-format
11292 (regexp-quote (match-string 4))))
11293 (when org-refile-use-outline-path
11294 (setq txt (mapconcat
11295 'org-protect-slash
11296 (append
11297 (if (eq org-refile-use-outline-path
11298 'file)
11299 (list (file-name-nondirectory
11300 (buffer-file-name
11301 (buffer-base-buffer))))
11302 (if (eq org-refile-use-outline-path
11303 'full-file-path)
11304 (list (buffer-file-name
11305 (buffer-base-buffer)))))
11306 (org-get-outline-path fast-path-p
11307 level txt)
11308 (list txt))
11309 "/")))
11310 (push (list txt f re (org-refile-marker (point)))
11311 tgs)))
11312 (when (= (point) pos0)
11313 ;; verification function has not moved point
11314 (goto-char (point-at-eol))))))))
11315 (when org-refile-use-cache
11316 (org-refile-cache-put tgs (buffer-file-name) descre))
11317 (setq targets (append tgs targets))))))
11318 (message "Getting targets...done")
11319 (nreverse targets)))
11321 (defun org-protect-slash (s)
11322 (while (string-match "/" s)
11323 (setq s (replace-match "\\" t t s)))
11326 (defvar org-olpa (make-vector 20 nil))
11328 (defun org-get-outline-path (&optional fastp level heading)
11329 "Return the outline path to the current entry, as a list.
11331 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11332 routine which makes outline path derivations for an entire file,
11333 avoiding backtracing. Refile target collection makes use of that."
11334 (if fastp
11335 (progn
11336 (if (> level 19)
11337 (error "Outline path failure, more than 19 levels"))
11338 (loop for i from level upto 19 do
11339 (aset org-olpa i nil))
11340 (prog1
11341 (delq nil (append org-olpa nil))
11342 (aset org-olpa level heading)))
11343 (let (rtn case-fold-search)
11344 (save-excursion
11345 (save-restriction
11346 (widen)
11347 (while (org-up-heading-safe)
11348 (when (looking-at org-complex-heading-regexp)
11349 (push (org-trim
11350 (replace-regexp-in-string
11351 ;; Remove statistical/checkboxes cookies
11352 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11353 (org-match-string-no-properties 4)))
11354 rtn)))
11355 rtn)))))
11357 (defun org-format-outline-path (path &optional width prefix separator)
11358 "Format the outline path PATH for display.
11359 WIDTH is the maximum number of characters that is available.
11360 PREFIX is a prefix to be included in the returned string,
11361 such as the file name.
11362 SEPARATOR is inserted between the different parts of the path,
11363 the default is \"/\"."
11364 (setq width (or width 79))
11365 (if prefix (setq width (- width (length prefix))))
11366 (if (not path)
11367 (or prefix "")
11368 (let* ((nsteps (length path))
11369 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11370 (maxwidth (if (<= total-width width)
11371 10000 ;; everything fits
11372 ;; we need to shorten the level headings
11373 (/ (- width nsteps) nsteps)))
11374 (org-odd-levels-only nil)
11375 (n 0)
11376 (total (1+ (length prefix))))
11377 (setq maxwidth (max maxwidth 10))
11378 (concat prefix
11379 (if prefix (or separator "/"))
11380 (mapconcat
11381 (lambda (h)
11382 (setq n (1+ n))
11383 (if (and (= n nsteps) (< maxwidth 10000))
11384 (setq maxwidth (- total-width total)))
11385 (if (< (length h) maxwidth)
11386 (progn (setq total (+ total (length h) 1)) h)
11387 (setq h (substring h 0 (- maxwidth 2))
11388 total (+ total maxwidth 1))
11389 (if (string-match "[ \t]+\\'" h)
11390 (setq h (substring h 0 (match-beginning 0))))
11391 (setq h (concat h "..")))
11392 (org-add-props h nil 'face
11393 (nth (% (1- n) org-n-level-faces)
11394 org-level-faces))
11396 path (or separator "/"))))))
11398 (defun org-display-outline-path (&optional file current separator just-return-string)
11399 "Display the current outline path in the echo area.
11401 If FILE is non-nil, prepend the output with the file name.
11402 If CURRENT is non-nil, append the current heading to the output.
11403 SEPARATOR is passed through to `org-format-outline-path'. It separates
11404 the different parts of the path and defaults to \"/\".
11405 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11406 (interactive "P")
11407 (let* (case-fold-search
11408 message-log-max ; Don't populate the *Messages* buffer
11409 (bfn (buffer-file-name (buffer-base-buffer)))
11410 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11411 res)
11412 (if current (setq path (append path
11413 (save-excursion
11414 (org-back-to-heading t)
11415 (if (looking-at org-complex-heading-regexp)
11416 (list (match-string 4)))))))
11417 (setq res
11418 (org-format-outline-path
11419 path
11420 (1- (frame-width))
11421 (and file bfn (concat (file-name-nondirectory bfn) separator))
11422 separator))
11423 (if just-return-string
11424 (org-no-properties res)
11425 (message "%s" res))))
11427 (defvar org-refile-history nil
11428 "History for refiling operations.")
11430 (defvar org-after-refile-insert-hook nil
11431 "Hook run after `org-refile' has inserted its stuff at the new location.
11432 Note that this is still *before* the stuff will be removed from
11433 the *old* location.")
11435 (defvar org-capture-last-stored-marker)
11436 (defvar org-refile-keep nil
11437 "Non-nil means `org-refile' will copy instead of refile.")
11439 (defun org-copy ()
11440 "Like `org-refile', but copy."
11441 (interactive)
11442 (let ((org-refile-keep t))
11443 (funcall 'org-refile nil nil nil "Copy")))
11445 (defun org-refile (&optional goto default-buffer rfloc msg)
11446 "Move the entry or entries at point to another heading.
11447 The list of target headings is compiled using the information in
11448 `org-refile-targets', which see.
11450 At the target location, the entry is filed as a subitem of the target
11451 heading. Depending on `org-reverse-note-order', the new subitem will
11452 either be the first or the last subitem.
11454 If there is an active region, all entries in that region will be moved.
11455 However, the region must fulfill the requirement that the first heading
11456 is the first one sets the top-level of the moved text - at most siblings
11457 below it are allowed.
11459 With prefix arg GOTO, the command will only visit the target location
11460 and not actually move anything.
11462 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11463 go to the location where the last refiling operation has put the subtree.
11464 With a prefix argument of `2', refile to the running clock.
11466 RFLOC can be a refile location obtained in a different way.
11468 MSG is a string to replace \"Refile\" in the default prompt with
11469 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11471 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11473 If you are using target caching (see `org-refile-use-cache'),
11474 you have to clear the target cache in order to find new targets.
11475 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11476 prefix argument (`C-u C-u C-u C-c C-w')."
11478 (interactive "P")
11479 (if (member goto '(0 (64)))
11480 (org-refile-cache-clear)
11481 (let* ((actionmsg (or msg "Refile"))
11482 (cbuf (current-buffer))
11483 (regionp (org-region-active-p))
11484 (region-start (and regionp (region-beginning)))
11485 (region-end (and regionp (region-end)))
11486 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11487 pos it nbuf file re level reversed)
11488 (setq last-command nil)
11489 (when regionp
11490 (goto-char region-start)
11491 (or (bolp) (goto-char (point-at-bol)))
11492 (setq region-start (point))
11493 (unless (or (org-kill-is-subtree-p
11494 (buffer-substring region-start region-end))
11495 (prog1 org-refile-active-region-within-subtree
11496 (let ((s (point-at-eol)))
11497 (org-toggle-heading)
11498 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11499 (user-error "The region is not a (sequence of) subtree(s)")))
11500 (if (equal goto '(16))
11501 (org-refile-goto-last-stored)
11502 (when (or
11503 (and (equal goto 2)
11504 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11505 (prog1
11506 (setq it (list (or org-clock-heading "running clock")
11507 (buffer-file-name
11508 (marker-buffer org-clock-hd-marker))
11510 (marker-position org-clock-hd-marker)))
11511 (setq goto nil)))
11512 (setq it (or rfloc
11513 (let (heading-text)
11514 (save-excursion
11515 (unless goto
11516 (org-back-to-heading t)
11517 (setq heading-text
11518 (nth 4 (org-heading-components))))
11520 (org-refile-get-location
11521 (cond (goto "Goto")
11522 (regionp (concat actionmsg " region to"))
11523 (t (concat actionmsg " subtree \""
11524 heading-text "\" to")))
11525 default-buffer
11526 (and (not (equal '(4) goto))
11527 org-refile-allow-creating-parent-nodes)
11528 goto))))))
11529 (setq file (nth 1 it)
11530 re (nth 2 it)
11531 pos (nth 3 it))
11532 (if (and (not goto)
11534 (equal (buffer-file-name) file)
11535 (if regionp
11536 (and (>= pos region-start)
11537 (<= pos region-end))
11538 (and (>= pos (point))
11539 (< pos (save-excursion
11540 (org-end-of-subtree t t))))))
11541 (error "Cannot refile to position inside the tree or region"))
11543 (setq nbuf (or (find-buffer-visiting file)
11544 (find-file-noselect file)))
11545 (if goto
11546 (progn
11547 (org-pop-to-buffer-same-window nbuf)
11548 (goto-char pos)
11549 (org-show-context 'org-goto))
11550 (if regionp
11551 (progn
11552 (org-kill-new (buffer-substring region-start region-end))
11553 (org-save-markers-in-region region-start region-end))
11554 (org-copy-subtree 1 nil t))
11555 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11556 (find-file-noselect file)))
11557 (setq reversed (org-notes-order-reversed-p))
11558 (save-excursion
11559 (save-restriction
11560 (widen)
11561 (if pos
11562 (progn
11563 (goto-char pos)
11564 (looking-at org-outline-regexp)
11565 (setq level (org-get-valid-level (funcall outline-level) 1))
11566 (goto-char
11567 (if reversed
11568 (or (outline-next-heading) (point-max))
11569 (or (save-excursion (org-get-next-sibling))
11570 (org-end-of-subtree t t)
11571 (point-max)))))
11572 (setq level 1)
11573 (if (not reversed)
11574 (goto-char (point-max))
11575 (goto-char (point-min))
11576 (or (outline-next-heading) (goto-char (point-max)))))
11577 (if (not (bolp)) (newline))
11578 (org-paste-subtree level)
11579 (when org-log-refile
11580 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11581 (unless (eq org-log-refile 'note)
11582 (save-excursion (org-add-log-note))))
11583 (and org-auto-align-tags
11584 (let ((org-loop-over-headlines-in-active-region nil))
11585 (org-set-tags nil t)))
11586 (with-demoted-errors
11587 (bookmark-set "org-refile-last-stored"))
11588 ;; If we are refiling for capture, make sure that the
11589 ;; last-capture pointers point here
11590 (when (org-bound-and-true-p org-refile-for-capture)
11591 (with-demoted-errors
11592 (bookmark-set "org-capture-last-stored-marker"))
11593 (move-marker org-capture-last-stored-marker (point)))
11594 (if (fboundp 'deactivate-mark) (deactivate-mark))
11595 (run-hooks 'org-after-refile-insert-hook))))
11596 (unless org-refile-keep
11597 (if regionp
11598 (delete-region (point) (+ (point) (- region-end region-start)))
11599 (delete-region
11600 (and (org-back-to-heading t) (point))
11601 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11602 (when (featurep 'org-inlinetask)
11603 (org-inlinetask-remove-END-maybe))
11604 (setq org-markers-to-move nil)
11605 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11607 (defun org-refile-goto-last-stored ()
11608 "Go to the location where the last refile was stored."
11609 (interactive)
11610 (bookmark-jump "org-refile-last-stored")
11611 (message "This is the location of the last refile"))
11613 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11614 no-exclude)
11615 "Prompt the user for a refile location, using PROMPT.
11616 PROMPT should not be suffixed with a colon and a space, because
11617 this function appends the default value from
11618 `org-refile-history' automatically, if that is not empty.
11619 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11620 this is used for the GOTO interface."
11621 (let ((org-refile-targets org-refile-targets)
11622 (org-refile-use-outline-path org-refile-use-outline-path)
11623 excluded-entries)
11624 (when (and (derived-mode-p 'org-mode)
11625 (not org-refile-use-cache)
11626 (not no-exclude))
11627 (org-map-tree
11628 (lambda()
11629 (setq excluded-entries
11630 (append excluded-entries (list (org-get-heading t t)))))))
11631 (setq org-refile-target-table
11632 (org-refile-get-targets default-buffer excluded-entries)))
11633 (unless org-refile-target-table
11634 (user-error "No refile targets"))
11635 (let* ((cbuf (current-buffer))
11636 (partial-completion-mode nil)
11637 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11638 (cfunc (if (and org-refile-use-outline-path
11639 org-outline-path-complete-in-steps)
11640 'org-olpath-completing-read
11641 'org-icompleting-read))
11642 (extra (if org-refile-use-outline-path "/" ""))
11643 (cbnex (concat (buffer-name) extra))
11644 (filename (and cfn (expand-file-name cfn)))
11645 (tbl (mapcar
11646 (lambda (x)
11647 (if (and (not (member org-refile-use-outline-path
11648 '(file full-file-path)))
11649 (not (equal filename (nth 1 x))))
11650 (cons (concat (car x) extra " ("
11651 (file-name-nondirectory (nth 1 x)) ")")
11652 (cdr x))
11653 (cons (concat (car x) extra) (cdr x))))
11654 org-refile-target-table))
11655 (completion-ignore-case t)
11656 cdef
11657 (prompt (concat prompt
11658 (or (and (car org-refile-history)
11659 (concat " (default " (car org-refile-history) ")"))
11660 (and (assoc cbnex tbl) (setq cdef cbnex)
11661 (concat " (default " cbnex ")"))) ": "))
11662 pa answ parent-target child parent old-hist)
11663 (setq old-hist org-refile-history)
11664 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11665 nil 'org-refile-history (or cdef (car org-refile-history))))
11666 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11667 (org-refile-check-position pa)
11668 (if pa
11669 (progn
11670 (when (or (not org-refile-history)
11671 (not (eq old-hist org-refile-history))
11672 (not (equal (car pa) (car org-refile-history))))
11673 (setq org-refile-history
11674 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11675 org-refile-history
11676 (cdr org-refile-history))))
11677 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11678 (pop org-refile-history)))
11680 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11681 (progn
11682 (setq parent (match-string 1 answ)
11683 child (match-string 2 answ))
11684 (setq parent-target (or (assoc parent tbl)
11685 (assoc (concat parent "/") tbl)))
11686 (when (and parent-target
11687 (or (eq new-nodes t)
11688 (and (eq new-nodes 'confirm)
11689 (y-or-n-p (format "Create new node \"%s\"? "
11690 child)))))
11691 (org-refile-new-child parent-target child)))
11692 (user-error "Invalid target location")))))
11694 (declare-function org-string-nw-p "org-macs" (s))
11695 (defun org-refile-check-position (refile-pointer)
11696 "Check if the refile pointer matches the headline to which it points."
11697 (let* ((file (nth 1 refile-pointer))
11698 (re (nth 2 refile-pointer))
11699 (pos (nth 3 refile-pointer))
11700 buffer)
11701 (if (and (not (markerp pos)) (not file))
11702 (user-error "Please save the buffer to a file before refiling")
11703 (when (org-string-nw-p re)
11704 (setq buffer (if (markerp pos)
11705 (marker-buffer pos)
11706 (or (find-buffer-visiting file)
11707 (find-file-noselect file))))
11708 (with-current-buffer buffer
11709 (save-excursion
11710 (save-restriction
11711 (widen)
11712 (goto-char pos)
11713 (beginning-of-line 1)
11714 (unless (org-looking-at-p re)
11715 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11717 (defun org-refile-new-child (parent-target child)
11718 "Use refile target PARENT-TARGET to add new CHILD below it."
11719 (unless parent-target
11720 (error "Cannot find parent for new node"))
11721 (let ((file (nth 1 parent-target))
11722 (pos (nth 3 parent-target))
11723 level)
11724 (with-current-buffer (or (find-buffer-visiting file)
11725 (find-file-noselect file))
11726 (save-excursion
11727 (save-restriction
11728 (widen)
11729 (if pos
11730 (goto-char pos)
11731 (goto-char (point-max))
11732 (if (not (bolp)) (newline)))
11733 (when (looking-at org-outline-regexp)
11734 (setq level (funcall outline-level))
11735 (org-end-of-subtree t t))
11736 (org-back-over-empty-lines)
11737 (insert "\n" (make-string
11738 (if pos (org-get-valid-level level 1) 1) ?*)
11739 " " child "\n")
11740 (beginning-of-line 0)
11741 (list (concat (car parent-target) "/" child) file "" (point)))))))
11743 (defun org-olpath-completing-read (prompt collection &rest args)
11744 "Read an outline path like a file name."
11745 (let ((thetable collection)
11746 (org-completion-use-ido nil) ; does not work with ido.
11747 (org-completion-use-iswitchb nil)) ; or iswitchb
11748 (apply
11749 'org-icompleting-read prompt
11750 (lambda (string predicate &optional flag)
11751 (let (rtn r f (l (length string)))
11752 (cond
11753 ((eq flag nil)
11754 ;; try completion
11755 (try-completion string thetable))
11756 ((eq flag t)
11757 ;; all-completions
11758 (setq rtn (all-completions string thetable predicate))
11759 (mapcar
11760 (lambda (x)
11761 (setq r (substring x l))
11762 (if (string-match " ([^)]*)$" x)
11763 (setq f (match-string 0 x))
11764 (setq f ""))
11765 (if (string-match "/" r)
11766 (concat string (substring r 0 (match-end 0)) f)
11768 rtn))
11769 ((eq flag 'lambda)
11770 ;; exact match?
11771 (assoc string thetable)))))
11772 args)))
11774 ;;;; Dynamic blocks
11776 (defun org-find-dblock (name)
11777 "Find the first dynamic block with name NAME in the buffer.
11778 If not found, stay at current position and return nil."
11779 (let ((case-fold-search t) pos)
11780 (save-excursion
11781 (goto-char (point-min))
11782 (setq pos (and (re-search-forward
11783 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11784 (match-beginning 0))))
11785 (if pos (goto-char pos))
11786 pos))
11788 (defconst org-dblock-start-re
11789 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11790 "Matches the start line of a dynamic block, with parameters.")
11792 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11793 "Matches the end of a dynamic block.")
11795 (defun org-create-dblock (plist)
11796 "Create a dynamic block section, with parameters taken from PLIST.
11797 PLIST must contain a :name entry which is used as name of the block."
11798 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11799 (end-of-line 1)
11800 (newline))
11801 (let ((col (current-column))
11802 (name (plist-get plist :name)))
11803 (insert "#+BEGIN: " name)
11804 (while plist
11805 (if (eq (car plist) :name)
11806 (setq plist (cddr plist))
11807 (insert " " (prin1-to-string (pop plist)))))
11808 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11809 (beginning-of-line -2)))
11811 (defun org-prepare-dblock ()
11812 "Prepare dynamic block for refresh.
11813 This empties the block, puts the cursor at the insert position and returns
11814 the property list including an extra property :name with the block name."
11815 (unless (looking-at org-dblock-start-re)
11816 (user-error "Not at a dynamic block"))
11817 (let* ((begdel (1+ (match-end 0)))
11818 (name (org-no-properties (match-string 1)))
11819 (params (append (list :name name)
11820 (read (concat "(" (match-string 3) ")")))))
11821 (save-excursion
11822 (beginning-of-line 1)
11823 (skip-chars-forward " \t")
11824 (setq params (plist-put params :indentation-column (current-column))))
11825 (unless (re-search-forward org-dblock-end-re nil t)
11826 (error "Dynamic block not terminated"))
11827 (setq params
11828 (append params
11829 (list :content (buffer-substring
11830 begdel (match-beginning 0)))))
11831 (delete-region begdel (match-beginning 0))
11832 (goto-char begdel)
11833 (open-line 1)
11834 params))
11836 (defun org-map-dblocks (&optional command)
11837 "Apply COMMAND to all dynamic blocks in the current buffer.
11838 If COMMAND is not given, use `org-update-dblock'."
11839 (let ((cmd (or command 'org-update-dblock)))
11840 (save-excursion
11841 (goto-char (point-min))
11842 (while (re-search-forward org-dblock-start-re nil t)
11843 (goto-char (match-beginning 0))
11844 (save-excursion
11845 (condition-case nil
11846 (funcall cmd)
11847 (error (message "Error during update of dynamic block"))))
11848 (unless (re-search-forward org-dblock-end-re nil t)
11849 (error "Dynamic block not terminated"))))))
11851 (defun org-dblock-update (&optional arg)
11852 "User command for updating dynamic blocks.
11853 Update the dynamic block at point. With prefix ARG, update all dynamic
11854 blocks in the buffer."
11855 (interactive "P")
11856 (if arg
11857 (org-update-all-dblocks)
11858 (or (looking-at org-dblock-start-re)
11859 (org-beginning-of-dblock))
11860 (org-update-dblock)))
11862 (defun org-update-dblock ()
11863 "Update the dynamic block at point.
11864 This means to empty the block, parse for parameters and then call
11865 the correct writing function."
11866 (interactive)
11867 (save-window-excursion
11868 (let* ((pos (point))
11869 (line (org-current-line))
11870 (params (org-prepare-dblock))
11871 (name (plist-get params :name))
11872 (indent (plist-get params :indentation-column))
11873 (cmd (intern (concat "org-dblock-write:" name))))
11874 (message "Updating dynamic block `%s' at line %d..." name line)
11875 (funcall cmd params)
11876 (message "Updating dynamic block `%s' at line %d...done" name line)
11877 (goto-char pos)
11878 (when (and indent (> indent 0))
11879 (setq indent (make-string indent ?\ ))
11880 (save-excursion
11881 (org-beginning-of-dblock)
11882 (forward-line 1)
11883 (while (not (looking-at org-dblock-end-re))
11884 (insert indent)
11885 (beginning-of-line 2))
11886 (when (looking-at org-dblock-end-re)
11887 (and (looking-at "[ \t]+")
11888 (replace-match ""))
11889 (insert indent)))))))
11891 (defun org-beginning-of-dblock ()
11892 "Find the beginning of the dynamic block at point.
11893 Error if there is no such block at point."
11894 (let ((pos (point))
11895 beg)
11896 (end-of-line 1)
11897 (if (and (re-search-backward org-dblock-start-re nil t)
11898 (setq beg (match-beginning 0))
11899 (re-search-forward org-dblock-end-re nil t)
11900 (> (match-end 0) pos))
11901 (goto-char beg)
11902 (goto-char pos)
11903 (error "Not in a dynamic block"))))
11905 (defun org-update-all-dblocks ()
11906 "Update all dynamic blocks in the buffer.
11907 This function can be used in a hook."
11908 (interactive)
11909 (when (derived-mode-p 'org-mode)
11910 (org-map-dblocks 'org-update-dblock)))
11913 ;;;; Completion
11915 (defun org-get-export-keywords ()
11916 "Return a list of all currently understood export keywords.
11917 Export keywords include options, block names, attributes and
11918 keywords relative to each registered export back-end."
11919 (delq nil
11920 (let (keywords)
11921 (mapc
11922 (lambda (back-end)
11923 (let ((props (cdr back-end)))
11924 ;; Back-end name (for keywords, like #+LATEX:)
11925 (push (upcase (symbol-name (car back-end))) keywords)
11926 ;; Back-end options.
11927 (mapc (lambda (option) (push (cadr option) keywords))
11928 (plist-get (cdr back-end) :options-alist))))
11929 (org-bound-and-true-p org-export-registered-backends))
11930 keywords)))
11932 (defconst org-options-keywords
11933 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11934 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11935 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11936 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11937 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11939 (defcustom org-structure-template-alist
11940 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11941 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11942 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11943 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11944 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11945 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11946 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11947 "<literal style=\"latex\">\n?\n</literal>")
11948 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11949 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11950 "<literal style=\"html\">\n?\n</literal>")
11951 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11952 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11953 ("A" "#+ASCII: " "")
11954 ("i" "#+INDEX: ?" "#+INDEX: ?")
11955 ("I" "#+INCLUDE: %file ?"
11956 "<include file=%file markup=\"?\">"))
11957 "Structure completion elements.
11958 This is a list of abbreviation keys and values. The value gets inserted
11959 if you type `<' followed by the key and then press the completion key,
11960 usually `M-TAB'. %file will be replaced by a file name after prompting
11961 for the file using completion. The cursor will be placed at the position
11962 of the `?` in the template.
11963 There are two templates for each key, the first uses the original Org syntax,
11964 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11965 the default when the /org-mtags.el/ module has been loaded. See also the
11966 variable `org-mtags-prefer-muse-templates'."
11967 :group 'org-completion
11968 :type '(repeat
11969 (list
11970 (string :tag "Key")
11971 (string :tag "Template")
11972 (string :tag "Muse Template"))))
11974 (defun org-try-structure-completion ()
11975 "Try to complete a structure template before point.
11976 This looks for strings like \"<e\" on an otherwise empty line and
11977 expands them."
11978 (let ((l (buffer-substring (point-at-bol) (point)))
11980 (when (and (looking-at "[ \t]*$")
11981 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11982 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11983 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11984 (match-beginning 1)) a)
11985 t)))
11987 (defun org-complete-expand-structure-template (start cell)
11988 "Expand a structure template."
11989 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11990 (rpl (nth (if musep 2 1) cell))
11991 (ind ""))
11992 (delete-region start (point))
11993 (when (string-match "\\`#\\+" rpl)
11994 (cond
11995 ((bolp))
11996 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11997 (setq ind (buffer-substring (point-at-bol) (point))))
11998 (t (newline))))
11999 (setq start (point))
12000 (if (string-match "%file" rpl)
12001 (setq rpl (replace-match
12002 (concat
12003 "\""
12004 (save-match-data
12005 (abbreviate-file-name (read-file-name "Include file: ")))
12006 "\"")
12007 t t rpl)))
12008 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12009 (concat "\n" ind)))
12010 (insert rpl)
12011 (if (re-search-backward "\\?" start t) (delete-char 1))))
12013 ;;;; TODO, DEADLINE, Comments
12015 (defun org-toggle-comment ()
12016 "Change the COMMENT state of an entry."
12017 (interactive)
12018 (save-excursion
12019 (org-back-to-heading)
12020 (let (case-fold-search)
12021 (cond
12022 ((looking-at (format org-heading-keyword-regexp-format
12023 org-comment-string))
12024 (goto-char (match-end 1))
12025 (looking-at (concat " +" org-comment-string))
12026 (replace-match "" t t)
12027 (when (eolp) (insert " ")))
12028 ((looking-at org-outline-regexp)
12029 (goto-char (match-end 0))
12030 (insert org-comment-string " "))))))
12032 (defvar org-last-todo-state-is-todo nil
12033 "This is non-nil when the last TODO state change led to a TODO state.
12034 If the last change removed the TODO tag or switched to DONE, then
12035 this is nil.")
12037 (defvar org-setting-tags nil) ; dynamically skipped
12039 (defvar org-todo-setup-filter-hook nil
12040 "Hook for functions that pre-filter todo specs.
12041 Each function takes a todo spec and returns either nil or the spec
12042 transformed into canonical form." )
12044 (defvar org-todo-get-default-hook nil
12045 "Hook for functions that get a default item for todo.
12046 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12047 nil or a string to be used for the todo mark." )
12049 (defvar org-agenda-headline-snapshot-before-repeat)
12051 (defun org-current-effective-time ()
12052 "Return current time adjusted for `org-extend-today-until' variable."
12053 (let* ((ct (org-current-time))
12054 (dct (decode-time ct))
12055 (ct1
12056 (cond
12057 (org-use-last-clock-out-time-as-effective-time
12058 (or (org-clock-get-last-clock-out-time) ct))
12059 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12060 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12061 (t ct))))
12062 ct1))
12064 (defun org-todo-yesterday (&optional arg)
12065 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12066 (interactive "P")
12067 (if (eq major-mode 'org-agenda-mode)
12068 (apply 'org-agenda-todo-yesterday arg)
12069 (let* ((hour (third (decode-time
12070 (org-current-time))))
12071 (org-extend-today-until (1+ hour)))
12072 (org-todo arg))))
12074 (defvar org-block-entry-blocking ""
12075 "First entry preventing the TODO state change.")
12077 (defun org-todo (&optional arg)
12078 "Change the TODO state of an item.
12079 The state of an item is given by a keyword at the start of the heading,
12080 like
12081 *** TODO Write paper
12082 *** DONE Call mom
12084 The different keywords are specified in the variable `org-todo-keywords'.
12085 By default the available states are \"TODO\" and \"DONE\".
12086 So for this example: when the item starts with TODO, it is changed to DONE.
12087 When it starts with DONE, the DONE is removed. And when neither TODO nor
12088 DONE are present, add TODO at the beginning of the heading.
12090 With \\[universal-argument] prefix arg, use completion to determine the new \
12091 state.
12092 With numeric prefix arg, switch to that state.
12093 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12094 keywords (nextset).
12095 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12096 With a numeric prefix arg of 0, inhibit note taking for the change.
12098 For calling through lisp, arg is also interpreted in the following way:
12099 'none -> empty state
12100 \"\"(empty string) -> switch to empty state
12101 'done -> switch to DONE
12102 'nextset -> switch to the next set of keywords
12103 'previousset -> switch to the previous set of keywords
12104 \"WAITING\" -> switch to the specified keyword, but only if it
12105 really is a member of `org-todo-keywords'."
12106 (interactive "P")
12107 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12108 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12109 'region-start-level 'region))
12110 org-loop-over-headlines-in-active-region)
12111 (org-map-entries
12112 `(org-todo ,arg)
12113 org-loop-over-headlines-in-active-region
12114 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12115 (if (equal arg '(16)) (setq arg 'nextset))
12116 (let ((org-blocker-hook org-blocker-hook)
12117 commentp
12118 case-fold-search)
12119 (when (equal arg '(64))
12120 (setq arg nil org-blocker-hook nil))
12121 (when (and org-blocker-hook
12122 (or org-inhibit-blocking
12123 (org-entry-get nil "NOBLOCKING")))
12124 (setq org-blocker-hook nil))
12125 (save-excursion
12126 (catch 'exit
12127 (org-back-to-heading t)
12128 (when (looking-at (concat "^\\*+ " org-comment-string))
12129 (org-toggle-comment)
12130 (setq commentp t))
12131 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12132 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12133 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12134 (let* ((match-data (match-data))
12135 (startpos (point-at-bol))
12136 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12137 (org-log-done org-log-done)
12138 (org-log-repeat org-log-repeat)
12139 (org-todo-log-states org-todo-log-states)
12140 (org-inhibit-logging
12141 (if (equal arg 0)
12142 (progn (setq arg nil) 'note) org-inhibit-logging))
12143 (this (match-string 1))
12144 (hl-pos (match-beginning 0))
12145 (head (org-get-todo-sequence-head this))
12146 (ass (assoc head org-todo-kwd-alist))
12147 (interpret (nth 1 ass))
12148 (done-word (nth 3 ass))
12149 (final-done-word (nth 4 ass))
12150 (org-last-state (or this ""))
12151 (completion-ignore-case t)
12152 (member (member this org-todo-keywords-1))
12153 (tail (cdr member))
12154 (org-state (cond
12155 ((and org-todo-key-trigger
12156 (or (and (equal arg '(4))
12157 (eq org-use-fast-todo-selection 'prefix))
12158 (and (not arg) org-use-fast-todo-selection
12159 (not (eq org-use-fast-todo-selection
12160 'prefix)))))
12161 ;; Use fast selection
12162 (org-fast-todo-selection))
12163 ((and (equal arg '(4))
12164 (or (not org-use-fast-todo-selection)
12165 (not org-todo-key-trigger)))
12166 ;; Read a state with completion
12167 (org-icompleting-read
12168 "State: " (mapcar 'list org-todo-keywords-1)
12169 nil t))
12170 ((eq arg 'right)
12171 (if this
12172 (if tail (car tail) nil)
12173 (car org-todo-keywords-1)))
12174 ((eq arg 'left)
12175 (if (equal member org-todo-keywords-1)
12177 (if this
12178 (nth (- (length org-todo-keywords-1)
12179 (length tail) 2)
12180 org-todo-keywords-1)
12181 (org-last org-todo-keywords-1))))
12182 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12183 (setq arg nil))) ; hack to fall back to cycling
12184 (arg
12185 ;; user or caller requests a specific state
12186 (cond
12187 ((equal arg "") nil)
12188 ((eq arg 'none) nil)
12189 ((eq arg 'done) (or done-word (car org-done-keywords)))
12190 ((eq arg 'nextset)
12191 (or (car (cdr (member head org-todo-heads)))
12192 (car org-todo-heads)))
12193 ((eq arg 'previousset)
12194 (let ((org-todo-heads (reverse org-todo-heads)))
12195 (or (car (cdr (member head org-todo-heads)))
12196 (car org-todo-heads))))
12197 ((car (member arg org-todo-keywords-1)))
12198 ((stringp arg)
12199 (user-error "State `%s' not valid in this file" arg))
12200 ((nth (1- (prefix-numeric-value arg))
12201 org-todo-keywords-1))))
12202 ((null member) (or head (car org-todo-keywords-1)))
12203 ((equal this final-done-word) nil) ;; -> make empty
12204 ((null tail) nil) ;; -> first entry
12205 ((memq interpret '(type priority))
12206 (if (eq this-command last-command)
12207 (car tail)
12208 (if (> (length tail) 0)
12209 (or done-word (car org-done-keywords))
12210 nil)))
12212 (car tail))))
12213 (org-state (or
12214 (run-hook-with-args-until-success
12215 'org-todo-get-default-hook org-state org-last-state)
12216 org-state))
12217 (next (if org-state (concat " " org-state " ") " "))
12218 (change-plist (list :type 'todo-state-change :from this :to org-state
12219 :position startpos))
12220 dolog now-done-p)
12221 (when org-blocker-hook
12222 (setq org-last-todo-state-is-todo
12223 (not (member this org-done-keywords)))
12224 (unless (save-excursion
12225 (save-match-data
12226 (org-with-wide-buffer
12227 (run-hook-with-args-until-failure
12228 'org-blocker-hook change-plist))))
12229 (if (org-called-interactively-p 'interactive)
12230 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12231 this org-state org-block-entry-blocking)
12232 ;; fail silently
12233 (message "TODO state change from %s to %s blocked (by \"%s\")"
12234 this org-state org-block-entry-blocking)
12235 (throw 'exit nil))))
12236 (store-match-data match-data)
12237 (replace-match next t t)
12238 (unless (pos-visible-in-window-p hl-pos)
12239 (message "TODO state changed to %s" (org-trim next)))
12240 (unless head
12241 (setq head (org-get-todo-sequence-head org-state)
12242 ass (assoc head org-todo-kwd-alist)
12243 interpret (nth 1 ass)
12244 done-word (nth 3 ass)
12245 final-done-word (nth 4 ass)))
12246 (when (memq arg '(nextset previousset))
12247 (message "Keyword-Set %d/%d: %s"
12248 (- (length org-todo-sets) -1
12249 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12250 (length org-todo-sets)
12251 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12252 (setq org-last-todo-state-is-todo
12253 (not (member org-state org-done-keywords)))
12254 (setq now-done-p (and (member org-state org-done-keywords)
12255 (not (member this org-done-keywords))))
12256 (and logging (org-local-logging logging))
12257 (when (and (or org-todo-log-states org-log-done)
12258 (not (eq org-inhibit-logging t))
12259 (not (memq arg '(nextset previousset))))
12260 ;; we need to look at recording a time and note
12261 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12262 (nth 2 (assoc this org-todo-log-states))))
12263 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12264 (setq dolog 'time))
12265 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12266 (and org-state
12267 (member org-state org-not-done-keywords)
12268 (not (member this org-not-done-keywords))))
12269 ;; This is now a todo state and was not one before
12270 ;; If there was a CLOSED time stamp, get rid of it.
12271 (org-add-planning-info nil nil 'closed))
12272 (when (and now-done-p org-log-done)
12273 ;; It is now done, and it was not done before
12274 (org-add-planning-info 'closed (org-current-effective-time))
12275 (if (and (not dolog) (eq 'note org-log-done))
12276 (org-add-log-setup 'done org-state this 'findpos 'note)))
12277 (when (and org-state dolog)
12278 ;; This is a non-nil state, and we need to log it
12279 (org-add-log-setup 'state org-state this 'findpos dolog)))
12280 ;; Fixup tag positioning
12281 (org-todo-trigger-tag-changes org-state)
12282 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12283 (when org-provide-todo-statistics
12284 (org-update-parent-todo-statistics))
12285 (run-hooks 'org-after-todo-state-change-hook)
12286 (if (and arg (not (member org-state org-done-keywords)))
12287 (setq head (org-get-todo-sequence-head org-state)))
12288 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12289 ;; Do we need to trigger a repeat?
12290 (when now-done-p
12291 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12292 ;; This is for the agenda, take a snapshot of the headline.
12293 (save-match-data
12294 (setq org-agenda-headline-snapshot-before-repeat
12295 (org-get-heading))))
12296 (org-auto-repeat-maybe org-state))
12297 ;; Fixup cursor location if close to the keyword
12298 (if (and (outline-on-heading-p)
12299 (not (bolp))
12300 (save-excursion (beginning-of-line 1)
12301 (looking-at org-todo-line-regexp))
12302 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12303 (progn
12304 (goto-char (or (match-end 2) (match-end 1)))
12305 (and (looking-at " ") (just-one-space))))
12306 (when org-trigger-hook
12307 (save-excursion
12308 (run-hook-with-args 'org-trigger-hook change-plist)))
12309 (when commentp (org-toggle-comment))))))))
12311 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12312 "Block turning an entry into a TODO, using the hierarchy.
12313 This checks whether the current task should be blocked from state
12314 changes. Such blocking occurs when:
12316 1. The task has children which are not all in a completed state.
12318 2. A task has a parent with the property :ORDERED:, and there
12319 are siblings prior to the current task with incomplete
12320 status.
12322 3. The parent of the task is blocked because it has siblings that should
12323 be done first, or is child of a block grandparent TODO entry."
12325 (if (not org-enforce-todo-dependencies)
12326 t ; if locally turned off don't block
12327 (catch 'dont-block
12328 ;; If this is not a todo state change, or if this entry is already DONE,
12329 ;; do not block
12330 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12331 (member (plist-get change-plist :from)
12332 (cons 'done org-done-keywords))
12333 (member (plist-get change-plist :to)
12334 (cons 'todo org-not-done-keywords))
12335 (not (plist-get change-plist :to)))
12336 (throw 'dont-block t))
12337 ;; If this task has children, and any are undone, it's blocked
12338 (save-excursion
12339 (org-back-to-heading t)
12340 (let ((this-level (funcall outline-level)))
12341 (outline-next-heading)
12342 (let ((child-level (funcall outline-level)))
12343 (while (and (not (eobp))
12344 (> child-level this-level))
12345 ;; this todo has children, check whether they are all
12346 ;; completed
12347 (if (and (not (org-entry-is-done-p))
12348 (org-entry-is-todo-p))
12349 (progn (setq org-block-entry-blocking (org-get-heading))
12350 (throw 'dont-block nil)))
12351 (outline-next-heading)
12352 (setq child-level (funcall outline-level))))))
12353 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12354 ;; any previous siblings are undone, it's blocked
12355 (save-excursion
12356 (org-back-to-heading t)
12357 (let* ((pos (point))
12358 (parent-pos (and (org-up-heading-safe) (point))))
12359 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12360 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12361 (forward-line 1)
12362 (re-search-forward org-not-done-heading-regexp pos t))
12363 (setq org-block-entry-blocking (match-string 0))
12364 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12365 ;; Search further up the hierarchy, to see if an ancestor is blocked
12366 (while t
12367 (goto-char parent-pos)
12368 (if (not (looking-at org-not-done-heading-regexp))
12369 (throw 'dont-block t)) ; do not block, parent is not a TODO
12370 (setq pos (point))
12371 (setq parent-pos (and (org-up-heading-safe) (point)))
12372 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12373 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12374 (forward-line 1)
12375 (re-search-forward org-not-done-heading-regexp pos t)
12376 (setq org-block-entry-blocking (org-get-heading)))
12377 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12379 (defcustom org-track-ordered-property-with-tag nil
12380 "Should the ORDERED property also be shown as a tag?
12381 The ORDERED property decides if an entry should require subtasks to be
12382 completed in sequence. Since a property is not very visible, setting
12383 this option means that toggling the ORDERED property with the command
12384 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12385 not relevant for the behavior, but it makes things more visible.
12387 Note that toggling the tag with tags commands will not change the property
12388 and therefore not influence behavior!
12390 This can be t, meaning the tag ORDERED should be used, It can also be a
12391 string to select a different tag for this task."
12392 :group 'org-todo
12393 :type '(choice
12394 (const :tag "No tracking" nil)
12395 (const :tag "Track with ORDERED tag" t)
12396 (string :tag "Use other tag")))
12398 (defun org-toggle-ordered-property ()
12399 "Toggle the ORDERED property of the current entry.
12400 For better visibility, you can track the value of this property with a tag.
12401 See variable `org-track-ordered-property-with-tag'."
12402 (interactive)
12403 (let* ((t1 org-track-ordered-property-with-tag)
12404 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12405 (save-excursion
12406 (org-back-to-heading)
12407 (if (org-entry-get nil "ORDERED")
12408 (progn
12409 (org-delete-property "ORDERED" "PROPERTIES")
12410 (and tag (org-toggle-tag tag 'off))
12411 (message "Subtasks can be completed in arbitrary order"))
12412 (org-entry-put nil "ORDERED" "t")
12413 (and tag (org-toggle-tag tag 'on))
12414 (message "Subtasks must be completed in sequence")))))
12416 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12417 (defun org-block-todo-from-checkboxes (change-plist)
12418 "Block turning an entry into a TODO, using checkboxes.
12419 This checks whether the current task should be blocked from state
12420 changes because there are unchecked boxes in this entry."
12421 (if (not org-enforce-todo-checkbox-dependencies)
12422 t ; if locally turned off don't block
12423 (catch 'dont-block
12424 ;; If this is not a todo state change, or if this entry is already DONE,
12425 ;; do not block
12426 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12427 (member (plist-get change-plist :from)
12428 (cons 'done org-done-keywords))
12429 (member (plist-get change-plist :to)
12430 (cons 'todo org-not-done-keywords))
12431 (not (plist-get change-plist :to)))
12432 (throw 'dont-block t))
12433 ;; If this task has checkboxes that are not checked, it's blocked
12434 (save-excursion
12435 (org-back-to-heading t)
12436 (let ((beg (point)) end)
12437 (outline-next-heading)
12438 (setq end (point))
12439 (goto-char beg)
12440 (if (org-list-search-forward
12441 (concat (org-item-beginning-re)
12442 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12443 "\\[[- ]\\]")
12444 end t)
12445 (progn
12446 (if (boundp 'org-blocked-by-checkboxes)
12447 (setq org-blocked-by-checkboxes t))
12448 (throw 'dont-block nil)))))
12449 t))) ; do not block
12451 (defun org-entry-blocked-p ()
12452 "Is the current entry blocked?"
12453 (org-with-silent-modifications
12454 (if (org-entry-get nil "NOBLOCKING")
12455 nil ;; Never block this entry
12456 (not (run-hook-with-args-until-failure
12457 'org-blocker-hook
12458 (list :type 'todo-state-change
12459 :position (point)
12460 :from 'todo
12461 :to 'done))))))
12463 (defun org-update-statistics-cookies (all)
12464 "Update the statistics cookie, either from TODO or from checkboxes.
12465 This should be called with the cursor in a line with a statistics cookie."
12466 (interactive "P")
12467 (if all
12468 (progn
12469 (org-update-checkbox-count 'all)
12470 (org-map-entries 'org-update-parent-todo-statistics))
12471 (if (not (org-at-heading-p))
12472 (org-update-checkbox-count)
12473 (let ((pos (point-marker))
12474 end l1 l2)
12475 (ignore-errors (org-back-to-heading t))
12476 (if (not (org-at-heading-p))
12477 (org-update-checkbox-count)
12478 (setq l1 (org-outline-level))
12479 (setq end (save-excursion
12480 (outline-next-heading)
12481 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12482 (point)))
12483 (if (and (save-excursion
12484 (re-search-forward
12485 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12486 (not (save-excursion (re-search-forward
12487 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12488 (org-update-checkbox-count)
12489 (if (and l2 (> l2 l1))
12490 (progn
12491 (goto-char end)
12492 (org-update-parent-todo-statistics))
12493 (goto-char pos)
12494 (beginning-of-line 1)
12495 (while (re-search-forward
12496 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12497 (point-at-eol) t)
12498 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12499 (goto-char pos)
12500 (move-marker pos nil)))))
12502 (defvar org-entry-property-inherited-from) ;; defined below
12503 (defun org-update-parent-todo-statistics ()
12504 "Update any statistics cookie in the parent of the current headline.
12505 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12506 the entire subtree and this will travel up the hierarchy and update
12507 statistics everywhere."
12508 (let* ((prop (save-excursion (org-up-heading-safe)
12509 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12510 (recursive (or (not org-hierarchical-todo-statistics)
12511 (and prop (string-match "\\<recursive\\>" prop))))
12512 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12514 (first t)
12515 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12516 level ltoggle l1 new ndel
12517 (cnt-all 0) (cnt-done 0) is-percent kwd
12518 checkbox-beg ov ovs ove cookie-present)
12519 (catch 'exit
12520 (save-excursion
12521 (beginning-of-line 1)
12522 (setq ltoggle (funcall outline-level))
12523 ;; Three situations are to consider:
12525 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12526 ;; to the top-level ancestor on the headline;
12528 ;; 2. If parent has "recursive" property, repeat up to the
12529 ;; headline setting that property, taking inheritance into
12530 ;; account;
12532 ;; 3. Else, move up to direct parent and proceed only once.
12533 (while (and (setq level (org-up-heading-safe))
12534 (or recursive first)
12535 (>= (point) lim))
12536 (setq first nil cookie-present nil)
12537 (unless (and level
12538 (not (string-match
12539 "\\<checkbox\\>"
12540 (downcase (or (org-entry-get nil "COOKIE_DATA")
12541 "")))))
12542 (throw 'exit nil))
12543 (while (re-search-forward box-re (point-at-eol) t)
12544 (setq cnt-all 0 cnt-done 0 cookie-present t)
12545 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12546 (save-match-data
12547 (unless (outline-next-heading) (throw 'exit nil))
12548 (while (and (looking-at org-complex-heading-regexp)
12549 (> (setq l1 (length (match-string 1))) level))
12550 (setq kwd (and (or recursive (= l1 ltoggle))
12551 (match-string 2)))
12552 (if (or (eq org-provide-todo-statistics 'all-headlines)
12553 (and (listp org-provide-todo-statistics)
12554 (or (member kwd org-provide-todo-statistics)
12555 (member kwd org-done-keywords))))
12556 (setq cnt-all (1+ cnt-all))
12557 (if (eq org-provide-todo-statistics t)
12558 (and kwd (setq cnt-all (1+ cnt-all)))))
12559 (and (member kwd org-done-keywords)
12560 (setq cnt-done (1+ cnt-done)))
12561 (outline-next-heading)))
12562 (setq new
12563 (if is-percent
12564 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12565 (format "[%d/%d]" cnt-done cnt-all))
12566 ndel (- (match-end 0) checkbox-beg))
12567 ;; handle overlays when updating cookie from column view
12568 (when (setq ov (car (overlays-at checkbox-beg)))
12569 (setq ovs (overlay-start ov) ove (overlay-end ov))
12570 (delete-overlay ov))
12571 (goto-char checkbox-beg)
12572 (insert new)
12573 (delete-region (point) (+ (point) ndel))
12574 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12575 (when ov (move-overlay ov ovs ove)))
12576 (when cookie-present
12577 (run-hook-with-args 'org-after-todo-statistics-hook
12578 cnt-done (- cnt-all cnt-done))))))
12579 (run-hooks 'org-todo-statistics-hook)))
12581 (defvar org-after-todo-statistics-hook nil
12582 "Hook that is called after a TODO statistics cookie has been updated.
12583 Each function is called with two arguments: the number of not-done entries
12584 and the number of done entries.
12586 For example, the following function, when added to this hook, will switch
12587 an entry to DONE when all children are done, and back to TODO when new
12588 entries are set to a TODO status. Note that this hook is only called
12589 when there is a statistics cookie in the headline!
12591 (defun org-summary-todo (n-done n-not-done)
12592 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12593 (let (org-log-done org-log-states) ; turn off logging
12594 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12597 (defvar org-todo-statistics-hook nil
12598 "Hook that is run whenever Org thinks TODO statistics should be updated.
12599 This hook runs even if there is no statistics cookie present, in which case
12600 `org-after-todo-statistics-hook' would not run.")
12602 (defun org-todo-trigger-tag-changes (state)
12603 "Apply the changes defined in `org-todo-state-tags-triggers'."
12604 (let ((l org-todo-state-tags-triggers)
12605 changes)
12606 (when (or (not state) (equal state ""))
12607 (setq changes (append changes (cdr (assoc "" l)))))
12608 (when (and (stringp state) (> (length state) 0))
12609 (setq changes (append changes (cdr (assoc state l)))))
12610 (when (member state org-not-done-keywords)
12611 (setq changes (append changes (cdr (assoc 'todo l)))))
12612 (when (member state org-done-keywords)
12613 (setq changes (append changes (cdr (assoc 'done l)))))
12614 (dolist (c changes)
12615 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12617 (defun org-local-logging (value)
12618 "Get logging settings from a property VALUE."
12619 (let* (words w a)
12620 ;; directly set the variables, they are already local.
12621 (setq org-log-done nil
12622 org-log-repeat nil
12623 org-todo-log-states nil)
12624 (setq words (org-split-string value))
12625 (while (setq w (pop words))
12626 (cond
12627 ((setq a (assoc w org-startup-options))
12628 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12629 (set (nth 1 a) (nth 2 a))))
12630 ((setq a (org-extract-log-state-settings w))
12631 (and (member (car a) org-todo-keywords-1)
12632 (push a org-todo-log-states)))))))
12634 (defun org-get-todo-sequence-head (kwd)
12635 "Return the head of the TODO sequence to which KWD belongs.
12636 If KWD is not set, check if there is a text property remembering the
12637 right sequence."
12638 (let (p)
12639 (cond
12640 ((not kwd)
12641 (or (get-text-property (point-at-bol) 'org-todo-head)
12642 (progn
12643 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12644 nil (point-at-eol)))
12645 (get-text-property p 'org-todo-head))))
12646 ((not (member kwd org-todo-keywords-1))
12647 (car org-todo-keywords-1))
12648 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12650 (defun org-fast-todo-selection ()
12651 "Fast TODO keyword selection with single keys.
12652 Returns the new TODO keyword, or nil if no state change should occur."
12653 (let* ((fulltable org-todo-key-alist)
12654 (done-keywords org-done-keywords) ;; needed for the faces.
12655 (maxlen (apply 'max (mapcar
12656 (lambda (x)
12657 (if (stringp (car x)) (string-width (car x)) 0))
12658 fulltable)))
12659 (expert nil)
12660 (fwidth (+ maxlen 3 1 3))
12661 (ncol (/ (- (window-width) 4) fwidth))
12662 tg cnt e c tbl
12663 groups ingroup)
12664 (save-excursion
12665 (save-window-excursion
12666 (if expert
12667 (set-buffer (get-buffer-create " *Org todo*"))
12668 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12669 (erase-buffer)
12670 (org-set-local 'org-done-keywords done-keywords)
12671 (setq tbl fulltable cnt 0)
12672 (while (setq e (pop tbl))
12673 (cond
12674 ((equal e '(:startgroup))
12675 (push '() groups) (setq ingroup t)
12676 (when (not (= cnt 0))
12677 (setq cnt 0)
12678 (insert "\n"))
12679 (insert "{ "))
12680 ((equal e '(:endgroup))
12681 (setq ingroup nil cnt 0)
12682 (insert "}\n"))
12683 ((equal e '(:newline))
12684 (when (not (= cnt 0))
12685 (setq cnt 0)
12686 (insert "\n")
12687 (setq e (car tbl))
12688 (while (equal (car tbl) '(:newline))
12689 (insert "\n")
12690 (setq tbl (cdr tbl)))))
12692 (setq tg (car e) c (cdr e))
12693 (if ingroup (push tg (car groups)))
12694 (setq tg (org-add-props tg nil 'face
12695 (org-get-todo-face tg)))
12696 (if (and (= cnt 0) (not ingroup)) (insert " "))
12697 (insert "[" c "] " tg (make-string
12698 (- fwidth 4 (length tg)) ?\ ))
12699 (when (= (setq cnt (1+ cnt)) ncol)
12700 (insert "\n")
12701 (if ingroup (insert " "))
12702 (setq cnt 0)))))
12703 (insert "\n")
12704 (goto-char (point-min))
12705 (if (not expert) (org-fit-window-to-buffer))
12706 (message "[a-z..]:Set [SPC]:clear")
12707 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12708 (cond
12709 ((or (= c ?\C-g)
12710 (and (= c ?q) (not (rassoc c fulltable))))
12711 (setq quit-flag t))
12712 ((= c ?\ ) nil)
12713 ((setq e (rassoc c fulltable) tg (car e))
12715 (t (setq quit-flag t)))))))
12717 (defun org-entry-is-todo-p ()
12718 (member (org-get-todo-state) org-not-done-keywords))
12720 (defun org-entry-is-done-p ()
12721 (member (org-get-todo-state) org-done-keywords))
12723 (defun org-get-todo-state ()
12724 "Return the TODO keyword of the current subtree."
12725 (save-excursion
12726 (org-back-to-heading t)
12727 (and (looking-at org-todo-line-regexp)
12728 (match-end 2)
12729 (match-string 2))))
12731 (defun org-at-date-range-p (&optional inactive-ok)
12732 "Is the cursor inside a date range?"
12733 (interactive)
12734 (save-excursion
12735 (catch 'exit
12736 (let ((pos (point)))
12737 (skip-chars-backward "^[<\r\n")
12738 (skip-chars-backward "<[")
12739 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12740 (>= (match-end 0) pos)
12741 (throw 'exit t))
12742 (skip-chars-backward "^<[\r\n")
12743 (skip-chars-backward "<[")
12744 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12745 (>= (match-end 0) pos)
12746 (throw 'exit t)))
12747 nil)))
12749 (defun org-get-repeat (&optional tagline)
12750 "Check if there is a deadline/schedule with repeater in this entry."
12751 (save-match-data
12752 (save-excursion
12753 (org-back-to-heading t)
12754 (and (re-search-forward (if tagline
12755 (concat tagline "\\s-*" org-repeat-re)
12756 org-repeat-re)
12757 (org-entry-end-position) t)
12758 (match-string-no-properties 1)))))
12760 (defvar org-last-changed-timestamp)
12761 (defvar org-last-inserted-timestamp)
12762 (defvar org-log-post-message)
12763 (defvar org-log-note-purpose)
12764 (defvar org-log-note-how)
12765 (defvar org-log-note-extra)
12766 (defun org-auto-repeat-maybe (done-word)
12767 "Check if the current headline contains a repeated deadline/schedule.
12768 If yes, set TODO state back to what it was and change the base date
12769 of repeating deadline/scheduled time stamps to new date.
12770 This function is run automatically after each state change to a DONE state."
12771 ;; last-state is dynamically scoped into this function
12772 (let* ((repeat (org-get-repeat))
12773 (aa (assoc org-last-state org-todo-kwd-alist))
12774 (interpret (nth 1 aa))
12775 (head (nth 2 aa))
12776 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12777 (msg "Entry repeats: ")
12778 (org-log-done nil)
12779 (org-todo-log-states nil)
12780 re type n what ts time to-state)
12781 (when repeat
12782 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12783 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12784 org-todo-repeat-to-state))
12785 (unless (and to-state (member to-state org-todo-keywords-1))
12786 (setq to-state (if (eq interpret 'type) org-last-state head)))
12787 (org-todo to-state)
12788 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12789 (org-entry-put nil "LAST_REPEAT" (format-time-string
12790 (org-time-stamp-format t t))))
12791 (when org-log-repeat
12792 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12793 (memq 'org-add-log-note post-command-hook))
12794 ;; OK, we are already setup for some record
12795 (if (eq org-log-repeat 'note)
12796 ;; make sure we take a note, not only a time stamp
12797 (setq org-log-note-how 'note))
12798 ;; Set up for taking a record
12799 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12800 org-last-state
12801 'findpos org-log-repeat)))
12802 (org-back-to-heading t)
12803 (org-add-planning-info nil nil 'closed)
12804 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12805 org-deadline-time-regexp "\\)\\|\\("
12806 org-ts-regexp "\\)"))
12807 (while (re-search-forward
12808 re (save-excursion (outline-next-heading) (point)) t)
12809 (setq type (if (match-end 1) org-scheduled-string
12810 (if (match-end 3) org-deadline-string "Plain:"))
12811 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12812 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12813 (setq n (string-to-number (match-string 2 ts))
12814 what (match-string 3 ts))
12815 (if (equal what "w") (setq n (* n 7) what "d"))
12816 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12817 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12818 ;; Preparation, see if we need to modify the start date for the change
12819 (when (match-end 1)
12820 (setq time (save-match-data (org-time-string-to-time ts)))
12821 (cond
12822 ((equal (match-string 1 ts) ".")
12823 ;; Shift starting date to today
12824 (org-timestamp-change
12825 (- (org-today) (time-to-days time))
12826 'day))
12827 ((equal (match-string 1 ts) "+")
12828 (let ((nshiftmax 10) (nshift 0))
12829 (while (or (= nshift 0)
12830 (<= (time-to-days time)
12831 (time-to-days (current-time))))
12832 (when (= (incf nshift) nshiftmax)
12833 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12834 (error "Abort")))
12835 (org-timestamp-change n (cdr (assoc what whata)))
12836 (org-at-timestamp-p t)
12837 (setq ts (match-string 1))
12838 (setq time (save-match-data (org-time-string-to-time ts)))))
12839 (org-timestamp-change (- n) (cdr (assoc what whata)))
12840 ;; rematch, so that we have everything in place for the real shift
12841 (org-at-timestamp-p t)
12842 (setq ts (match-string 1))
12843 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12844 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12845 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12846 (setq org-log-post-message msg)
12847 (message "%s" msg))))
12849 (defun org-show-todo-tree (arg)
12850 "Make a compact tree which shows all headlines marked with TODO.
12851 The tree will show the lines where the regexp matches, and all higher
12852 headlines above the match.
12853 With a \\[universal-argument] prefix, prompt for a regexp to match.
12854 With a numeric prefix N, construct a sparse tree for the Nth element
12855 of `org-todo-keywords-1'."
12856 (interactive "P")
12857 (let ((case-fold-search nil)
12858 (kwd-re
12859 (cond ((null arg) org-not-done-regexp)
12860 ((equal arg '(4))
12861 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12862 (mapcar 'list org-todo-keywords-1))))
12863 (concat "\\("
12864 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12865 "\\)\\>")))
12866 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12867 (regexp-quote (nth (1- (prefix-numeric-value arg))
12868 org-todo-keywords-1)))
12869 (t (user-error "Invalid prefix argument: %s" arg)))))
12870 (message "%d TODO entries found"
12871 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12873 (defun org-deadline (arg &optional time)
12874 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12875 With one universal prefix argument, remove any deadline from the item.
12876 With two universal prefix arguments, prompt for a warning delay.
12877 With argument TIME, set the deadline at the corresponding date. TIME
12878 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12879 (interactive "P")
12880 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12881 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12882 'region-start-level 'region))
12883 org-loop-over-headlines-in-active-region)
12884 (org-map-entries
12885 `(org-deadline ',arg ,time)
12886 org-loop-over-headlines-in-active-region
12887 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12888 (let* ((old-date (org-entry-get nil "DEADLINE"))
12889 (old-date-time (if old-date (org-time-string-to-time old-date)))
12890 (repeater (and old-date
12891 (string-match
12892 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12893 old-date)
12894 (match-string 1 old-date))))
12895 (cond
12896 ((equal arg '(4))
12897 (when (and old-date org-log-redeadline)
12898 (org-add-log-setup 'deldeadline nil old-date 'findpos
12899 org-log-redeadline))
12900 (org-remove-timestamp-with-keyword org-deadline-string)
12901 (message "Item no longer has a deadline."))
12902 ((equal arg '(16))
12903 (save-excursion
12904 (if (re-search-forward
12905 org-deadline-time-regexp
12906 (save-excursion (outline-next-heading) (point)) t)
12907 (let* ((rpl0 (match-string 1))
12908 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12909 (replace-match
12910 (concat org-deadline-string
12911 " <" rpl
12912 (format " -%dd"
12913 (abs
12914 (- (time-to-days
12915 (save-match-data
12916 (org-read-date nil t nil "Warn starting from" old-date-time)))
12917 (time-to-days old-date-time))))
12918 ">") t t))
12919 (user-error "No deadline information to update"))))
12921 (org-add-planning-info 'deadline time 'closed)
12922 (when (and old-date org-log-redeadline
12923 (not (equal old-date
12924 (substring org-last-inserted-timestamp 1 -1))))
12925 (org-add-log-setup 'redeadline nil old-date 'findpos
12926 org-log-redeadline))
12927 (when repeater
12928 (save-excursion
12929 (org-back-to-heading t)
12930 (when (re-search-forward (concat org-deadline-string " "
12931 org-last-inserted-timestamp)
12932 (save-excursion
12933 (outline-next-heading) (point)) t)
12934 (goto-char (1- (match-end 0)))
12935 (insert " " repeater)
12936 (setq org-last-inserted-timestamp
12937 (concat (substring org-last-inserted-timestamp 0 -1)
12938 " " repeater
12939 (substring org-last-inserted-timestamp -1))))))
12940 (message "Deadline on %s" org-last-inserted-timestamp))))))
12942 (defun org-schedule (arg &optional time)
12943 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12944 With one universal prefix argument, remove any scheduling date from the item.
12945 With two universal prefix arguments, prompt for a delay cookie.
12946 With argument TIME, scheduled at the corresponding date. TIME can
12947 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12948 (interactive "P")
12949 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12950 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12951 'region-start-level 'region))
12952 org-loop-over-headlines-in-active-region)
12953 (org-map-entries
12954 `(org-schedule ',arg ,time)
12955 org-loop-over-headlines-in-active-region
12956 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12957 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12958 (old-date-time (if old-date (org-time-string-to-time old-date)))
12959 (repeater (and old-date
12960 (string-match
12961 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12962 old-date)
12963 (match-string 1 old-date))))
12964 (cond
12965 ((equal arg '(4))
12966 (progn
12967 (when (and old-date org-log-reschedule)
12968 (org-add-log-setup 'delschedule nil old-date 'findpos
12969 org-log-reschedule))
12970 (org-remove-timestamp-with-keyword org-scheduled-string)
12971 (message "Item is no longer scheduled.")))
12972 ((equal arg '(16))
12973 (save-excursion
12974 (if (re-search-forward
12975 org-scheduled-time-regexp
12976 (save-excursion (outline-next-heading) (point)) t)
12977 (let* ((rpl0 (match-string 1))
12978 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12979 (replace-match
12980 (concat org-scheduled-string
12981 " <" rpl
12982 (format " -%dd"
12983 (abs
12984 (- (time-to-days
12985 (save-match-data
12986 (org-read-date nil t nil "Delay until" old-date-time)))
12987 (time-to-days old-date-time))))
12988 ">") t t))
12989 (user-error "No scheduled information to update"))))
12991 (org-add-planning-info 'scheduled time 'closed)
12992 (when (and old-date org-log-reschedule
12993 (not (equal old-date
12994 (substring org-last-inserted-timestamp 1 -1))))
12995 (org-add-log-setup 'reschedule nil old-date 'findpos
12996 org-log-reschedule))
12997 (when repeater
12998 (save-excursion
12999 (org-back-to-heading t)
13000 (when (re-search-forward (concat org-scheduled-string " "
13001 org-last-inserted-timestamp)
13002 (save-excursion
13003 (outline-next-heading) (point)) t)
13004 (goto-char (1- (match-end 0)))
13005 (insert " " repeater)
13006 (setq org-last-inserted-timestamp
13007 (concat (substring org-last-inserted-timestamp 0 -1)
13008 " " repeater
13009 (substring org-last-inserted-timestamp -1))))))
13010 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13012 (defun org-get-scheduled-time (pom &optional inherit)
13013 "Get the scheduled time as a time tuple, of a format suitable
13014 for calling org-schedule with, or if there is no scheduling,
13015 returns nil."
13016 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13017 (when time
13018 (apply 'encode-time (org-parse-time-string time)))))
13020 (defun org-get-deadline-time (pom &optional inherit)
13021 "Get the deadline as a time tuple, of a format suitable for
13022 calling org-deadline with, or if there is no scheduling, returns
13023 nil."
13024 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13025 (when time
13026 (apply 'encode-time (org-parse-time-string time)))))
13028 (defun org-remove-timestamp-with-keyword (keyword)
13029 "Remove all time stamps with KEYWORD in the current entry."
13030 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13031 beg)
13032 (save-excursion
13033 (org-back-to-heading t)
13034 (setq beg (point))
13035 (outline-next-heading)
13036 (while (re-search-backward re beg t)
13037 (replace-match "")
13038 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13039 (equal (char-before) ?\ ))
13040 (backward-delete-char 1)
13041 (if (string-match "^[ \t]*$" (buffer-substring
13042 (point-at-bol) (point-at-eol)))
13043 (delete-region (point-at-bol)
13044 (min (point-max) (1+ (point-at-eol))))))))))
13046 (defun org-add-planning-info (what &optional time &rest remove)
13047 "Insert new timestamp with keyword in the line directly after the headline.
13048 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13049 If non is given, the user is prompted for a date.
13050 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13051 be removed."
13052 (interactive)
13053 (let (org-time-was-given org-end-time-was-given ts
13054 end default-time default-input)
13056 (catch 'exit
13057 (when (and (memq what '(scheduled deadline))
13058 (or (not time)
13059 (and (stringp time)
13060 (string-match "^[-+]+[0-9]" time))))
13061 ;; Try to get a default date/time from existing timestamp
13062 (save-excursion
13063 (org-back-to-heading t)
13064 (setq end (save-excursion (outline-next-heading) (point)))
13065 (when (re-search-forward (if (eq what 'scheduled)
13066 org-scheduled-time-regexp
13067 org-deadline-time-regexp)
13068 end t)
13069 (setq ts (match-string 1)
13070 default-time
13071 (apply 'encode-time (org-parse-time-string ts))
13072 default-input (and ts (org-get-compact-tod ts))))))
13073 (when what
13074 (setq time
13075 (if (stringp time)
13076 ;; This is a string (relative or absolute), set proper date
13077 (apply 'encode-time
13078 (org-read-date-analyze
13079 time default-time (decode-time default-time)))
13080 ;; If necessary, get the time from the user
13081 (or time (org-read-date nil 'to-time nil nil
13082 default-time default-input)))))
13084 (when (and org-insert-labeled-timestamps-at-point
13085 (member what '(scheduled deadline)))
13086 (insert
13087 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13088 (org-insert-time-stamp time org-time-was-given
13089 nil nil nil (list org-end-time-was-given))
13090 (setq what nil))
13091 (save-excursion
13092 (save-restriction
13093 (let (col list elt ts buffer-invisibility-spec)
13094 (org-back-to-heading t)
13095 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13096 (goto-char (match-end 1))
13097 (setq col (current-column))
13098 (goto-char (match-end 0))
13099 (if (eobp) (insert "\n") (forward-char 1))
13100 (when (and (not what)
13101 (not (looking-at
13102 (concat "[ \t]*"
13103 org-keyword-time-not-clock-regexp))))
13104 ;; Nothing to add, nothing to remove...... :-)
13105 (throw 'exit nil))
13106 (if (and (not (looking-at org-outline-regexp))
13107 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13108 "[^\r\n]*"))
13109 (not (equal (match-string 1) org-clock-string)))
13110 (narrow-to-region (match-beginning 0) (match-end 0))
13111 (insert-before-markers "\n")
13112 (backward-char 1)
13113 (narrow-to-region (point) (point))
13114 (and org-adapt-indentation (org-indent-to-column col)))
13115 ;; Check if we have to remove something.
13116 (setq list (cons what remove))
13117 (while list
13118 (setq elt (pop list))
13119 (when (or (and (eq elt 'scheduled)
13120 (re-search-forward org-scheduled-time-regexp nil t))
13121 (and (eq elt 'deadline)
13122 (re-search-forward org-deadline-time-regexp nil t))
13123 (and (eq elt 'closed)
13124 (re-search-forward org-closed-time-regexp nil t)))
13125 (replace-match "")
13126 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13127 (and (looking-at "[ \t]+") (replace-match ""))
13128 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13129 (when what
13130 (insert
13131 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13132 (cond ((eq what 'scheduled) org-scheduled-string)
13133 ((eq what 'deadline) org-deadline-string)
13134 ((eq what 'closed) org-closed-string))
13135 " ")
13136 (setq ts (org-insert-time-stamp
13137 time
13138 (or org-time-was-given
13139 (and (eq what 'closed) org-log-done-with-time))
13140 (eq what 'closed)
13141 nil nil (list org-end-time-was-given)))
13142 (insert
13143 (if (not (or (bolp) (eq (char-before) ?\ )
13144 (memq (char-after) '(32 10))
13145 (eobp))) " " ""))
13146 (end-of-line 1))
13147 (goto-char (point-min))
13148 (widen)
13149 (if (and (looking-at "[ \t]*\n")
13150 (equal (char-before) ?\n))
13151 (delete-region (1- (point)) (point-at-eol)))
13152 ts))))))
13154 (defvar org-log-note-marker (make-marker))
13155 (defvar org-log-note-purpose nil)
13156 (defvar org-log-note-state nil)
13157 (defvar org-log-note-previous-state nil)
13158 (defvar org-log-note-how nil)
13159 (defvar org-log-note-extra nil)
13160 (defvar org-log-note-window-configuration nil)
13161 (defvar org-log-note-return-to (make-marker))
13162 (defvar org-log-note-effective-time nil
13163 "Remembered current time so that dynamically scoped
13164 `org-extend-today-until' affects tha timestamps in state change
13165 log")
13167 (defvar org-log-post-message nil
13168 "Message to be displayed after a log note has been stored.
13169 The auto-repeater uses this.")
13171 (defun org-add-note ()
13172 "Add a note to the current entry.
13173 This is done in the same way as adding a state change note."
13174 (interactive)
13175 (org-add-log-setup 'note nil nil 'findpos nil))
13177 (defvar org-property-end-re)
13178 (defun org-add-log-setup (&optional purpose state prev-state
13179 findpos how extra)
13180 "Set up the post command hook to take a note.
13181 If this is about to TODO state change, the new state is expected in STATE.
13182 When FINDPOS is non-nil, find the correct position for the note in
13183 the current entry. If not, assume that it can be inserted at point.
13184 HOW is an indicator what kind of note should be created.
13185 EXTRA is additional text that will be inserted into the notes buffer."
13186 (let* ((org-log-into-drawer (org-log-into-drawer))
13187 (drawer (cond ((stringp org-log-into-drawer)
13188 org-log-into-drawer)
13189 (org-log-into-drawer "LOGBOOK"))))
13190 (save-restriction
13191 (save-excursion
13192 (when findpos
13193 (org-back-to-heading t)
13194 (narrow-to-region (point) (save-excursion
13195 (outline-next-heading) (point)))
13196 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13197 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13198 "[^\r\n]*\\)?"))
13199 (goto-char (match-end 0))
13200 (cond
13201 (drawer
13202 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13203 nil t)
13204 (progn
13205 (goto-char (match-end 0))
13206 (or org-log-states-order-reversed
13207 (and (re-search-forward org-property-end-re nil t)
13208 (goto-char (1- (match-beginning 0))))))
13209 (insert "\n:" drawer ":\n:END:")
13210 (beginning-of-line 0)
13211 (org-indent-line)
13212 (beginning-of-line 2)
13213 (org-indent-line)
13214 (end-of-line 0)))
13215 ((and org-log-state-notes-insert-after-drawers
13216 (save-excursion
13217 (forward-line) (looking-at org-drawer-regexp)))
13218 (forward-line)
13219 (while (looking-at org-drawer-regexp)
13220 (goto-char (match-end 0))
13221 (re-search-forward org-property-end-re (point-max) t)
13222 (forward-line))
13223 (forward-line -1)))
13224 (unless org-log-states-order-reversed
13225 (and (= (char-after) ?\n) (forward-char 1))
13226 (org-skip-over-state-notes)
13227 (skip-chars-backward " \t\n\r")))
13228 (move-marker org-log-note-marker (point))
13229 (setq org-log-note-purpose purpose
13230 org-log-note-state state
13231 org-log-note-previous-state prev-state
13232 org-log-note-how how
13233 org-log-note-extra extra
13234 org-log-note-effective-time (org-current-effective-time))
13235 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13237 (defun org-skip-over-state-notes ()
13238 "Skip past the list of State notes in an entry."
13239 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13240 (when (ignore-errors (goto-char (org-in-item-p)))
13241 (let* ((struct (org-list-struct))
13242 (prevs (org-list-prevs-alist struct)))
13243 (while (looking-at "[ \t]*- State")
13244 (goto-char (or (org-list-get-next-item (point) struct prevs)
13245 (org-list-get-item-end (point) struct)))))))
13247 (defun org-add-log-note (&optional purpose)
13248 "Pop up a window for taking a note, and add this note later at point."
13249 (remove-hook 'post-command-hook 'org-add-log-note)
13250 (setq org-log-note-window-configuration (current-window-configuration))
13251 (delete-other-windows)
13252 (move-marker org-log-note-return-to (point))
13253 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13254 (goto-char org-log-note-marker)
13255 (org-switch-to-buffer-other-window "*Org Note*")
13256 (erase-buffer)
13257 (if (memq org-log-note-how '(time state))
13258 (let (current-prefix-arg) (org-store-log-note))
13259 (let ((org-inhibit-startup t)) (org-mode))
13260 (insert (format "# Insert note for %s.
13261 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13262 (cond
13263 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13264 ((eq org-log-note-purpose 'done) "closed todo item")
13265 ((eq org-log-note-purpose 'state)
13266 (format "state change from \"%s\" to \"%s\""
13267 (or org-log-note-previous-state "")
13268 (or org-log-note-state "")))
13269 ((eq org-log-note-purpose 'reschedule)
13270 "rescheduling")
13271 ((eq org-log-note-purpose 'delschedule)
13272 "no longer scheduled")
13273 ((eq org-log-note-purpose 'redeadline)
13274 "changing deadline")
13275 ((eq org-log-note-purpose 'deldeadline)
13276 "removing deadline")
13277 ((eq org-log-note-purpose 'refile)
13278 "refiling")
13279 ((eq org-log-note-purpose 'note)
13280 "this entry")
13281 (t (error "This should not happen")))))
13282 (if org-log-note-extra (insert org-log-note-extra))
13283 (org-set-local 'org-finish-function 'org-store-log-note)
13284 (run-hooks 'org-log-buffer-setup-hook)))
13286 (defvar org-note-abort nil) ; dynamically scoped
13287 (defun org-store-log-note ()
13288 "Finish taking a log note, and insert it to where it belongs."
13289 (let ((txt (buffer-string)))
13290 (kill-buffer (current-buffer))
13291 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13292 lines ind bul)
13293 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13294 (setq txt (replace-match "" t t txt)))
13295 (if (string-match "\\s-+\\'" txt)
13296 (setq txt (replace-match "" t t txt)))
13297 (setq lines (org-split-string txt "\n"))
13298 (when (and note (string-match "\\S-" note))
13299 (setq note
13300 (org-replace-escapes
13301 note
13302 (list (cons "%u" (user-login-name))
13303 (cons "%U" user-full-name)
13304 (cons "%t" (format-time-string
13305 (org-time-stamp-format 'long 'inactive)
13306 org-log-note-effective-time))
13307 (cons "%T" (format-time-string
13308 (org-time-stamp-format 'long nil)
13309 org-log-note-effective-time))
13310 (cons "%d" (format-time-string
13311 (org-time-stamp-format nil 'inactive)
13312 org-log-note-effective-time))
13313 (cons "%D" (format-time-string
13314 (org-time-stamp-format nil nil)
13315 org-log-note-effective-time))
13316 (cons "%s" (if org-log-note-state
13317 (concat "\"" org-log-note-state "\"")
13318 ""))
13319 (cons "%S" (if org-log-note-previous-state
13320 (concat "\"" org-log-note-previous-state "\"")
13321 "\"\"")))))
13322 (if lines (setq note (concat note " \\\\")))
13323 (push note lines))
13324 (when (or current-prefix-arg org-note-abort)
13325 (when org-log-into-drawer
13326 (org-remove-empty-drawer-at
13327 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13328 org-log-note-marker))
13329 (setq lines nil))
13330 (when lines
13331 (with-current-buffer (marker-buffer org-log-note-marker)
13332 (save-excursion
13333 (goto-char org-log-note-marker)
13334 (move-marker org-log-note-marker nil)
13335 (end-of-line 1)
13336 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13337 (setq ind (save-excursion
13338 (if (ignore-errors (goto-char (org-in-item-p)))
13339 (let ((struct (org-list-struct)))
13340 (org-list-get-ind
13341 (org-list-get-top-point struct) struct))
13342 (skip-chars-backward " \r\t\n")
13343 (cond
13344 ((and (org-at-heading-p)
13345 org-adapt-indentation)
13346 (1+ (org-current-level)))
13347 ((org-at-heading-p) 0)
13348 (t (org-get-indentation))))))
13349 (setq bul (org-list-bullet-string "-"))
13350 (org-indent-line-to ind)
13351 (insert bul (pop lines))
13352 (let ((ind-body (+ (length bul) ind)))
13353 (while lines
13354 (insert "\n")
13355 (org-indent-line-to ind-body)
13356 (insert (pop lines))))
13357 (message "Note stored")
13358 (org-back-to-heading t)
13359 (org-cycle-hide-drawers 'children))
13360 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13361 ;; from within `org-add-log-note' because `buffer-undo-list'
13362 ;; is then modified outside of `org-with-remote-undo'.
13363 (when (eq this-command 'org-agenda-todo)
13364 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13365 ;; Don't add undo information when called from `org-agenda-todo'
13366 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13367 (set-window-configuration org-log-note-window-configuration)
13368 (with-current-buffer (marker-buffer org-log-note-return-to)
13369 (goto-char org-log-note-return-to))
13370 (move-marker org-log-note-return-to nil)
13371 (and org-log-post-message (message "%s" org-log-post-message))))
13373 (defun org-remove-empty-drawer-at (drawer pos)
13374 "Remove an empty drawer DRAWER at position POS.
13375 POS may also be a marker."
13376 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13377 (save-excursion
13378 (save-restriction
13379 (widen)
13380 (goto-char pos)
13381 (if (org-in-regexp
13382 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13383 (replace-match ""))))))
13385 (defvar org-ts-type nil)
13386 (defun org-sparse-tree (&optional arg type)
13387 "Create a sparse tree, prompt for the details.
13388 This command can create sparse trees. You first need to select the type
13389 of match used to create the tree:
13391 t Show all TODO entries.
13392 T Show entries with a specific TODO keyword.
13393 m Show entries selected by a tags/property match.
13394 p Enter a property name and its value (both with completion on existing
13395 names/values) and show entries with that property.
13396 r Show entries matching a regular expression (`/' can be used as well).
13397 b Show deadlines and scheduled items before a date.
13398 a Show deadlines and scheduled items after a date.
13399 d Show deadlines due within `org-deadline-warning-days'.
13400 D Show deadlines and scheduled items between a date range."
13401 (interactive "P")
13402 (let (ans kwd value ts-type)
13403 (setq type (or type org-sparse-tree-default-date-type))
13404 (setq org-ts-type type)
13405 (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"
13406 (cond ((eq type 'all) "all timestamps")
13407 ((eq type 'scheduled) "only scheduled")
13408 ((eq type 'deadline) "only deadline")
13409 ((eq type 'active) "only active timestamps")
13410 ((eq type 'inactive) "only inactive timestamps")
13411 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13412 ((eq type 'closed) "with a closed time-stamp")
13413 (t "scheduled/deadline")))
13414 (setq ans (read-char-exclusive))
13415 (cond
13416 ((equal ans ?c)
13417 (org-sparse-tree
13418 arg (cadr (member type '(scheduled-or-deadline
13419 all scheduled deadline active inactive closed)))))
13420 ((equal ans ?d)
13421 (call-interactively 'org-check-deadlines))
13422 ((equal ans ?b)
13423 (call-interactively 'org-check-before-date))
13424 ((equal ans ?a)
13425 (call-interactively 'org-check-after-date))
13426 ((equal ans ?D)
13427 (call-interactively 'org-check-dates-range))
13428 ((equal ans ?t)
13429 (call-interactively 'org-show-todo-tree))
13430 ((equal ans ?T)
13431 (org-show-todo-tree '(4)))
13432 ((member ans '(?T ?m))
13433 (call-interactively 'org-match-sparse-tree))
13434 ((member ans '(?p ?P))
13435 (setq kwd (org-icompleting-read "Property: "
13436 (mapcar 'list (org-buffer-property-keys))))
13437 (setq value (org-icompleting-read "Value: "
13438 (mapcar 'list (org-property-values kwd))))
13439 (unless (string-match "\\`{.*}\\'" value)
13440 (setq value (concat "\"" value "\"")))
13441 (org-match-sparse-tree arg (concat kwd "=" value)))
13442 ((member ans '(?r ?R ?/))
13443 (call-interactively 'org-occur))
13444 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13446 (defvar org-occur-highlights nil
13447 "List of overlays used for occur matches.")
13448 (make-variable-buffer-local 'org-occur-highlights)
13449 (defvar org-occur-parameters nil
13450 "Parameters of the active org-occur calls.
13451 This is a list, each call to org-occur pushes as cons cell,
13452 containing the regular expression and the callback, onto the list.
13453 The list can contain several entries if `org-occur' has been called
13454 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13455 will only contain one set of parameters. When the highlights are
13456 removed (for example with `C-c C-c', or with the next edit (depending
13457 on `org-remove-highlights-with-change'), this variable is emptied
13458 as well.")
13459 (make-variable-buffer-local 'org-occur-parameters)
13461 (defun org-occur (regexp &optional keep-previous callback)
13462 "Make a compact tree which shows all matches of REGEXP.
13463 The tree will show the lines where the regexp matches, and all higher
13464 headlines above the match. It will also show the heading after the match,
13465 to make sure editing the matching entry is easy.
13466 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13467 call to `org-occur' will be kept, to allow stacking of calls to this
13468 command.
13469 If CALLBACK is non-nil, it is a function which is called to confirm
13470 that the match should indeed be shown."
13471 (interactive "sRegexp: \nP")
13472 (when (equal regexp "")
13473 (user-error "Regexp cannot be empty"))
13474 (unless keep-previous
13475 (org-remove-occur-highlights nil nil t))
13476 (push (cons regexp callback) org-occur-parameters)
13477 (let ((cnt 0))
13478 (save-excursion
13479 (goto-char (point-min))
13480 (if (or (not keep-previous) ; do not want to keep
13481 (not org-occur-highlights)) ; no previous matches
13482 ;; hide everything
13483 (org-overview))
13484 (while (re-search-forward regexp nil t)
13485 (when (or (not callback)
13486 (save-match-data (funcall callback)))
13487 (setq cnt (1+ cnt))
13488 (when org-highlight-sparse-tree-matches
13489 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13490 (org-show-context 'occur-tree))))
13491 (when org-remove-highlights-with-change
13492 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13493 nil 'local))
13494 (unless org-sparse-tree-open-archived-trees
13495 (org-hide-archived-subtrees (point-min) (point-max)))
13496 (run-hooks 'org-occur-hook)
13497 (if (org-called-interactively-p 'interactive)
13498 (message "%d match(es) for regexp %s" cnt regexp))
13499 cnt))
13501 (defun org-occur-next-match (&optional n reset)
13502 "Function for `next-error-function' to find sparse tree matches.
13503 N is the number of matches to move, when negative move backwards.
13504 RESET is entirely ignored - this function always goes back to the
13505 starting point when no match is found."
13506 (let* ((limit (if (< n 0) (point-min) (point-max)))
13507 (search-func (if (< n 0)
13508 'previous-single-char-property-change
13509 'next-single-char-property-change))
13510 (n (abs n))
13511 (pos (point))
13513 (catch 'exit
13514 (while (setq p1 (funcall search-func (point) 'org-type))
13515 (when (equal p1 limit)
13516 (goto-char pos)
13517 (error "No more matches"))
13518 (when (equal (get-char-property p1 'org-type) 'org-occur)
13519 (setq n (1- n))
13520 (when (= n 0)
13521 (goto-char p1)
13522 (throw 'exit (point))))
13523 (goto-char p1))
13524 (goto-char p1)
13525 (error "No more matches"))))
13527 (defun org-show-context (&optional key)
13528 "Make sure point and context are visible.
13529 How much context is shown depends upon the variables
13530 `org-show-hierarchy-above', `org-show-following-heading',
13531 `org-show-entry-below' and `org-show-siblings'."
13532 (let ((heading-p (org-at-heading-p t))
13533 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13534 (following-p (org-get-alist-option org-show-following-heading key))
13535 (entry-p (org-get-alist-option org-show-entry-below key))
13536 (siblings-p (org-get-alist-option org-show-siblings key)))
13537 ;; Show heading or entry text
13538 (if (and heading-p (not entry-p))
13539 (org-flag-heading nil) ; only show the heading
13540 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13541 (org-show-hidden-entry))) ; show entire entry
13542 (when following-p
13543 ;; Show next sibling, or heading below text
13544 (save-excursion
13545 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13546 (org-flag-heading nil))))
13547 (when siblings-p (org-show-siblings))
13548 (when hierarchy-p
13549 ;; show all higher headings, possibly with siblings
13550 (save-excursion
13551 (while (and (condition-case nil
13552 (progn (org-up-heading-all 1) t)
13553 (error nil))
13554 (not (bobp)))
13555 (org-flag-heading nil)
13556 (when siblings-p (org-show-siblings)))))
13557 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13559 (defvar org-reveal-start-hook nil
13560 "Hook run before revealing a location.")
13562 (defun org-reveal (&optional siblings)
13563 "Show current entry, hierarchy above it, and the following headline.
13564 This can be used to show a consistent set of context around locations
13565 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13566 not t for the search context.
13568 With optional argument SIBLINGS, on each level of the hierarchy all
13569 siblings are shown. This repairs the tree structure to what it would
13570 look like when opened with hierarchical calls to `org-cycle'.
13571 With double optional argument \\[universal-argument] \\[universal-argument], \
13572 go to the parent and show the
13573 entire tree."
13574 (interactive "P")
13575 (run-hooks 'org-reveal-start-hook)
13576 (let ((org-show-hierarchy-above t)
13577 (org-show-following-heading t)
13578 (org-show-siblings (if siblings t org-show-siblings)))
13579 (org-show-context nil))
13580 (when (equal siblings '(16))
13581 (save-excursion
13582 (when (org-up-heading-safe)
13583 (org-show-subtree)
13584 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13586 (defun org-highlight-new-match (beg end)
13587 "Highlight from BEG to END and mark the highlight is an occur headline."
13588 (let ((ov (make-overlay beg end)))
13589 (overlay-put ov 'face 'secondary-selection)
13590 (overlay-put ov 'org-type 'org-occur)
13591 (push ov org-occur-highlights)))
13593 (defun org-remove-occur-highlights (&optional beg end noremove)
13594 "Remove the occur highlights from the buffer.
13595 BEG and END are ignored. If NOREMOVE is nil, remove this function
13596 from the `before-change-functions' in the current buffer."
13597 (interactive)
13598 (unless org-inhibit-highlight-removal
13599 (mapc 'delete-overlay org-occur-highlights)
13600 (setq org-occur-highlights nil)
13601 (setq org-occur-parameters nil)
13602 (unless noremove
13603 (remove-hook 'before-change-functions
13604 'org-remove-occur-highlights 'local))))
13606 ;;;; Priorities
13608 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13609 "Regular expression matching the priority indicator.")
13611 (defvar org-remove-priority-next-time nil)
13613 (defun org-priority-up ()
13614 "Increase the priority of the current item."
13615 (interactive)
13616 (org-priority 'up))
13618 (defun org-priority-down ()
13619 "Decrease the priority of the current item."
13620 (interactive)
13621 (org-priority 'down))
13623 (defun org-priority (&optional action show)
13624 "Change the priority of an item.
13625 ACTION can be `set', `up', `down', or a character."
13626 (interactive "P")
13627 (if (equal action '(4))
13628 (org-show-priority)
13629 (unless org-enable-priority-commands
13630 (user-error "Priority commands are disabled"))
13631 (setq action (or action 'set))
13632 (let (current new news have remove)
13633 (save-excursion
13634 (org-back-to-heading t)
13635 (if (looking-at org-priority-regexp)
13636 (setq current (string-to-char (match-string 2))
13637 have t))
13638 (cond
13639 ((eq action 'remove)
13640 (setq remove t new ?\ ))
13641 ((or (eq action 'set)
13642 (if (featurep 'xemacs) (characterp action) (integerp action)))
13643 (if (not (eq action 'set))
13644 (setq new action)
13645 (message "Priority %c-%c, SPC to remove: "
13646 org-highest-priority org-lowest-priority)
13647 (save-match-data
13648 (setq new (read-char-exclusive))))
13649 (if (and (= (upcase org-highest-priority) org-highest-priority)
13650 (= (upcase org-lowest-priority) org-lowest-priority))
13651 (setq new (upcase new)))
13652 (cond ((equal new ?\ ) (setq remove t))
13653 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13654 (user-error "Priority must be between `%c' and `%c'"
13655 org-highest-priority org-lowest-priority))))
13656 ((eq action 'up)
13657 (setq new (if have
13658 (1- current) ; normal cycling
13659 ;; last priority was empty
13660 (if (eq last-command this-command)
13661 org-lowest-priority ; wrap around empty to lowest
13662 ;; default
13663 (if org-priority-start-cycle-with-default
13664 org-default-priority
13665 (1- org-default-priority))))))
13666 ((eq action 'down)
13667 (setq new (if have
13668 (1+ current) ; normal cycling
13669 ;; last priority was empty
13670 (if (eq last-command this-command)
13671 org-highest-priority ; wrap around empty to highest
13672 ;; default
13673 (if org-priority-start-cycle-with-default
13674 org-default-priority
13675 (1+ org-default-priority))))))
13676 (t (user-error "Invalid action")))
13677 (if (or (< (upcase new) org-highest-priority)
13678 (> (upcase new) org-lowest-priority))
13679 (if (and (memq action '(up down))
13680 (not have) (not (eq last-command this-command)))
13681 ;; `new' is from default priority
13682 (error
13683 "The default can not be set, see `org-default-priority' why")
13684 ;; normal cycling: `new' is beyond highest/lowest priority
13685 ;; and is wrapped around to the empty priority
13686 (setq remove t)))
13687 (setq news (format "%c" new))
13688 (if have
13689 (if remove
13690 (replace-match "" t t nil 1)
13691 (replace-match news t t nil 2))
13692 (if remove
13693 (user-error "No priority cookie found in line")
13694 (let ((case-fold-search nil))
13695 (looking-at org-todo-line-regexp))
13696 (if (match-end 2)
13697 (progn
13698 (goto-char (match-end 2))
13699 (insert " [#" news "]"))
13700 (goto-char (match-beginning 3))
13701 (insert "[#" news "] "))))
13702 (org-preserve-lc (org-set-tags nil 'align)))
13703 (if remove
13704 (message "Priority removed")
13705 (message "Priority of current item set to %s" news)))))
13707 (defun org-show-priority ()
13708 "Show the priority of the current item.
13709 This priority is composed of the main priority given with the [#A] cookies,
13710 and by additional input from the age of a schedules or deadline entry."
13711 (interactive)
13712 (let ((pri (if (eq major-mode 'org-agenda-mode)
13713 (org-get-at-bol 'priority)
13714 (save-excursion
13715 (save-match-data
13716 (beginning-of-line)
13717 (and (looking-at org-heading-regexp)
13718 (org-get-priority (match-string 0))))))))
13719 (message "Priority is %d" (if pri pri -1000))))
13721 (defun org-get-priority (s)
13722 "Find priority cookie and return priority."
13723 (save-match-data
13724 (if (functionp org-get-priority-function)
13725 (funcall org-get-priority-function)
13726 (if (not (string-match org-priority-regexp s))
13727 (* 1000 (- org-lowest-priority org-default-priority))
13728 (* 1000 (- org-lowest-priority
13729 (string-to-char (match-string 2 s))))))))
13731 ;;;; Tags
13733 (defvar org-agenda-archives-mode)
13734 (defvar org-map-continue-from nil
13735 "Position from where mapping should continue.
13736 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13738 (defvar org-scanner-tags nil
13739 "The current tag list while the tags scanner is running.")
13740 (defvar org-trust-scanner-tags nil
13741 "Should `org-get-tags-at' use the tags for the scanner.
13742 This is for internal dynamical scoping only.
13743 When this is non-nil, the function `org-get-tags-at' will return the value
13744 of `org-scanner-tags' instead of building the list by itself. This
13745 can lead to large speed-ups when the tags scanner is used in a file with
13746 many entries, and when the list of tags is retrieved, for example to
13747 obtain a list of properties. Building the tags list for each entry in such
13748 a file becomes an N^2 operation - but with this variable set, it scales
13749 as N.")
13751 (defun org-scan-tags (action matcher todo-only &optional start-level)
13752 "Sca headline tags with inheritance and produce output ACTION.
13754 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13755 or `agenda' to produce an entry list for an agenda view. It can also be
13756 a Lisp form or a function that should be called at each matched headline, in
13757 this case the return value is a list of all return values from these calls.
13759 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13760 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13761 only lines with a not-done TODO keyword are included in the output.
13762 This should be the same variable that was scoped into
13763 and set by `org-make-tags-matcher' when it constructed MATCHER.
13765 START-LEVEL can be a string with asterisks, reducing the scope to
13766 headlines matching this string."
13767 (require 'org-agenda)
13768 (let* ((re (concat "^"
13769 (if start-level
13770 ;; Get the correct level to match
13771 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13772 org-outline-regexp)
13773 " *\\(\\<\\("
13774 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13775 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13776 (props (list 'face 'default
13777 'done-face 'org-agenda-done
13778 'undone-face 'default
13779 'mouse-face 'highlight
13780 'org-not-done-regexp org-not-done-regexp
13781 'org-todo-regexp org-todo-regexp
13782 'org-complex-heading-regexp org-complex-heading-regexp
13783 'help-echo
13784 (format "mouse-2 or RET jump to org file %s"
13785 (abbreviate-file-name
13786 (or (buffer-file-name (buffer-base-buffer))
13787 (buffer-name (buffer-base-buffer)))))))
13788 (org-map-continue-from nil)
13789 lspos tags tags-list
13790 (tags-alist (list (cons 0 org-file-tags)))
13791 (llast 0) rtn rtn1 level category i txt
13792 todo marker entry priority)
13793 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13794 (setq action (list 'lambda nil action)))
13795 (save-excursion
13796 (goto-char (point-min))
13797 (when (eq action 'sparse-tree)
13798 (org-overview)
13799 (org-remove-occur-highlights))
13800 (while (let (case-fold-search)
13801 (re-search-forward re nil t))
13802 (setq org-map-continue-from nil)
13803 (catch :skip
13804 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13805 tags (if (match-end 4) (org-match-string-no-properties 4)))
13806 (goto-char (setq lspos (match-beginning 0)))
13807 (setq level (org-reduced-level (org-outline-level))
13808 category (org-get-category))
13809 (setq i llast llast level)
13810 ;; remove tag lists from same and sublevels
13811 (while (>= i level)
13812 (when (setq entry (assoc i tags-alist))
13813 (setq tags-alist (delete entry tags-alist)))
13814 (setq i (1- i)))
13815 ;; add the next tags
13816 (when tags
13817 (setq tags (org-split-string tags ":")
13818 tags-alist
13819 (cons (cons level tags) tags-alist)))
13820 ;; compile tags for current headline
13821 (setq tags-list
13822 (if org-use-tag-inheritance
13823 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13824 tags)
13825 org-scanner-tags tags-list)
13826 (when org-use-tag-inheritance
13827 (setcdr (car tags-alist)
13828 (mapcar (lambda (x)
13829 (setq x (copy-sequence x))
13830 (org-add-prop-inherited x))
13831 (cdar tags-alist))))
13832 (when (and tags org-use-tag-inheritance
13833 (or (not (eq t org-use-tag-inheritance))
13834 org-tags-exclude-from-inheritance))
13835 ;; selective inheritance, remove uninherited ones
13836 (setcdr (car tags-alist)
13837 (org-remove-uninherited-tags (cdar tags-alist))))
13838 (when (and
13840 ;; eval matcher only when the todo condition is OK
13841 (and (or (not todo-only) (member todo org-not-done-keywords))
13842 (let ((case-fold-search t) (org-trust-scanner-tags t))
13843 (eval matcher)))
13845 ;; Call the skipper, but return t if it does not skip,
13846 ;; so that the `and' form continues evaluating
13847 (progn
13848 (unless (eq action 'sparse-tree) (org-agenda-skip))
13851 ;; Check if timestamps are deselecting this entry
13852 (or (not todo-only)
13853 (and (member todo org-not-done-keywords)
13854 (or (not org-agenda-tags-todo-honor-ignore-options)
13855 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13857 ;; select this headline
13858 (cond
13859 ((eq action 'sparse-tree)
13860 (and org-highlight-sparse-tree-matches
13861 (org-get-heading) (match-end 0)
13862 (org-highlight-new-match
13863 (match-beginning 1) (match-end 1)))
13864 (org-show-context 'tags-tree))
13865 ((eq action 'agenda)
13866 (setq txt (org-agenda-format-item
13868 (concat
13869 (if (eq org-tags-match-list-sublevels 'indented)
13870 (make-string (1- level) ?.) "")
13871 (org-get-heading))
13872 level category
13873 tags-list)
13874 priority (org-get-priority txt))
13875 (goto-char lspos)
13876 (setq marker (org-agenda-new-marker))
13877 (org-add-props txt props
13878 'org-marker marker 'org-hd-marker marker 'org-category category
13879 'todo-state todo
13880 'priority priority 'type "tagsmatch")
13881 (push txt rtn))
13882 ((functionp action)
13883 (setq org-map-continue-from nil)
13884 (save-excursion
13885 (setq rtn1 (funcall action))
13886 (push rtn1 rtn)))
13887 (t (user-error "Invalid action")))
13889 ;; if we are to skip sublevels, jump to end of subtree
13890 (unless org-tags-match-list-sublevels
13891 (org-end-of-subtree t)
13892 (backward-char 1))))
13893 ;; Get the correct position from where to continue
13894 (if org-map-continue-from
13895 (goto-char org-map-continue-from)
13896 (and (= (point) lspos) (end-of-line 1)))))
13897 (when (and (eq action 'sparse-tree)
13898 (not org-sparse-tree-open-archived-trees))
13899 (org-hide-archived-subtrees (point-min) (point-max)))
13900 (nreverse rtn)))
13902 (defun org-remove-uninherited-tags (tags)
13903 "Remove all tags that are not inherited from the list TAGS."
13904 (cond
13905 ((eq org-use-tag-inheritance t)
13906 (if org-tags-exclude-from-inheritance
13907 (org-delete-all org-tags-exclude-from-inheritance tags)
13908 tags))
13909 ((not org-use-tag-inheritance) nil)
13910 ((stringp org-use-tag-inheritance)
13911 (delq nil (mapcar
13912 (lambda (x)
13913 (if (and (string-match org-use-tag-inheritance x)
13914 (not (member x org-tags-exclude-from-inheritance)))
13915 x nil))
13916 tags)))
13917 ((listp org-use-tag-inheritance)
13918 (delq nil (mapcar
13919 (lambda (x)
13920 (if (member x org-use-tag-inheritance) x nil))
13921 tags)))))
13923 (defun org-match-sparse-tree (&optional todo-only match)
13924 "Create a sparse tree according to tags string MATCH.
13925 MATCH can contain positive and negative selection of tags, like
13926 \"+WORK+URGENT-WITHBOSS\".
13927 If optional argument TODO-ONLY is non-nil, only select lines that are
13928 also TODO lines."
13929 (interactive "P")
13930 (org-agenda-prepare-buffers (list (current-buffer)))
13931 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13933 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13935 (defvar org-cached-props nil)
13936 (defun org-cached-entry-get (pom property)
13937 (if (or (eq t org-use-property-inheritance)
13938 (and (stringp org-use-property-inheritance)
13939 (string-match org-use-property-inheritance property))
13940 (and (listp org-use-property-inheritance)
13941 (member property org-use-property-inheritance)))
13942 ;; Caching is not possible, check it directly
13943 (org-entry-get pom property 'inherit)
13944 ;; Get all properties, so that we can do complicated checks easily
13945 (cdr (assoc property (or org-cached-props
13946 (setq org-cached-props
13947 (org-entry-properties pom)))))))
13949 (defun org-global-tags-completion-table (&optional files)
13950 "Return the list of all tags in all agenda buffer/files.
13951 Optional FILES argument is a list of files which can be used
13952 instead of the agenda files."
13953 (save-excursion
13954 (org-uniquify
13955 (delq nil
13956 (apply 'append
13957 (mapcar
13958 (lambda (file)
13959 (set-buffer (find-file-noselect file))
13960 (append (org-get-buffer-tags)
13961 (mapcar (lambda (x) (if (stringp (car-safe x))
13962 (list (car-safe x)) nil))
13963 org-tag-alist)))
13964 (if (and files (car files))
13965 files
13966 (org-agenda-files))))))))
13968 (defun org-make-tags-matcher (match)
13969 "Create the TAGS/TODO matcher form for the selection string MATCH.
13971 The variable `todo-only' is scoped dynamically into this function.
13972 It will be set to t if the matcher restricts matching to TODO entries,
13973 otherwise will not be touched.
13975 Returns a cons of the selection string MATCH and the constructed
13976 lisp form implementing the matcher. The matcher is to be evaluated
13977 at an Org entry, with point on the headline, and returns t if the
13978 entry matches the selection string MATCH. The returned lisp form
13979 references two variables with information about the entry, which
13980 must be bound around the form's evaluation: todo, the TODO keyword
13981 at the entry (or nil of none); and tags-list, the list of all tags
13982 at the entry including inherited ones. Additionally, the category
13983 of the entry (if any) must be specified as the text property
13984 'org-category on the headline.
13986 See also `org-scan-tags'.
13988 (declare (special todo-only))
13989 (unless (boundp 'todo-only)
13990 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13991 (unless match
13992 ;; Get a new match request, with completion against the global
13993 ;; tags table and the local tags in current buffer
13994 (let ((org-last-tags-completion-table
13995 (org-uniquify
13996 (delq nil (append (org-get-buffer-tags)
13997 (org-global-tags-completion-table))))))
13998 (setq match (org-completing-read-no-i
13999 "Match: " 'org-tags-completion-function nil nil nil
14000 'org-tags-history))))
14002 ;; Parse the string and create a lisp form
14003 (let ((match0 match)
14004 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14005 minus tag mm
14006 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14007 orterms term orlist re-p str-p level-p level-op time-p
14008 prop-p pn pv po gv rest)
14009 ;; Expand group tags
14010 (setq match (org-tags-expand match))
14011 (if (string-match "/+" match)
14012 ;; match contains also a todo-matching request
14013 (progn
14014 (setq tagsmatch (substring match 0 (match-beginning 0))
14015 todomatch (substring match (match-end 0)))
14016 (if (string-match "^!" todomatch)
14017 (setq todo-only t todomatch (substring todomatch 1)))
14018 (if (string-match "^\\s-*$" todomatch)
14019 (setq todomatch nil)))
14020 ;; only matching tags
14021 (setq tagsmatch match todomatch nil))
14023 ;; Make the tags matcher
14024 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14025 (setq tagsmatcher t)
14026 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14027 (while (setq term (pop orterms))
14028 (while (and (equal (substring term -1) "\\") orterms)
14029 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14030 (while (string-match re term)
14031 (setq rest (substring term (match-end 0))
14032 minus (and (match-end 1)
14033 (equal (match-string 1 term) "-"))
14034 tag (save-match-data (replace-regexp-in-string
14035 "\\\\-" "-"
14036 (match-string 2 term)))
14037 re-p (equal (string-to-char tag) ?{)
14038 level-p (match-end 4)
14039 prop-p (match-end 5)
14040 mm (cond
14041 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14042 (level-p
14043 (setq level-op (org-op-to-function (match-string 3 term)))
14044 `(,level-op level ,(string-to-number
14045 (match-string 4 term))))
14046 (prop-p
14047 (setq pn (match-string 5 term)
14048 po (match-string 6 term)
14049 pv (match-string 7 term)
14050 re-p (equal (string-to-char pv) ?{)
14051 str-p (equal (string-to-char pv) ?\")
14052 time-p (save-match-data
14053 (string-match "^\"[[<].*[]>]\"$" pv))
14054 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14055 (if time-p (setq pv (org-matcher-time pv)))
14056 (setq po (org-op-to-function po (if time-p 'time str-p)))
14057 (cond
14058 ((equal pn "CATEGORY")
14059 (setq gv '(get-text-property (point) 'org-category)))
14060 ((equal pn "TODO")
14061 (setq gv 'todo))
14063 (setq gv `(org-cached-entry-get nil ,pn))))
14064 (if re-p
14065 (if (eq po 'org<>)
14066 `(not (string-match ,pv (or ,gv "")))
14067 `(string-match ,pv (or ,gv "")))
14068 (if str-p
14069 `(,po (or ,gv "") ,pv)
14070 `(,po (string-to-number (or ,gv ""))
14071 ,(string-to-number pv) ))))
14072 (t `(member ,tag tags-list)))
14073 mm (if minus (list 'not mm) mm)
14074 term rest)
14075 (push mm tagsmatcher))
14076 (push (if (> (length tagsmatcher) 1)
14077 (cons 'and tagsmatcher)
14078 (car tagsmatcher))
14079 orlist)
14080 (setq tagsmatcher nil))
14081 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14082 (setq tagsmatcher
14083 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14084 ;; Make the todo matcher
14085 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14086 (setq todomatcher t)
14087 (setq orterms (org-split-string todomatch "|") orlist nil)
14088 (while (setq term (pop orterms))
14089 (while (string-match re term)
14090 (setq minus (and (match-end 1)
14091 (equal (match-string 1 term) "-"))
14092 kwd (match-string 2 term)
14093 re-p (equal (string-to-char kwd) ?{)
14094 term (substring term (match-end 0))
14095 mm (if re-p
14096 `(string-match ,(substring kwd 1 -1) todo)
14097 (list 'equal 'todo kwd))
14098 mm (if minus (list 'not mm) mm))
14099 (push mm todomatcher))
14100 (push (if (> (length todomatcher) 1)
14101 (cons 'and todomatcher)
14102 (car todomatcher))
14103 orlist)
14104 (setq todomatcher nil))
14105 (setq todomatcher (if (> (length orlist) 1)
14106 (cons 'or orlist) (car orlist))))
14108 ;; Return the string and lisp forms of the matcher
14109 (setq matcher (if todomatcher
14110 (list 'and tagsmatcher todomatcher)
14111 tagsmatcher))
14112 (when todo-only
14113 (setq matcher (list 'and '(member todo org-not-done-keywords)
14114 matcher)))
14115 (cons match0 matcher)))
14117 (defun org-tags-expand (match &optional single-as-list downcased)
14118 "Expand group tags in MATCH.
14120 This replaces every group tag in MATCH with a regexp tag search.
14121 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14122 will be replaced like this:
14124 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14125 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14126 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14128 Replacing by a regexp preserves the structure of the match.
14129 E.g., this expansion
14131 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14133 will match anything tagged with \"Lab\" and \"Home\", or tagged
14134 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14136 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14137 assumed to be a single group tag, and the function will return
14138 the list of tags in this group.
14140 When DOWNCASE is non-nil, expand downcased TAGS."
14141 (if org-group-tags
14142 (let* ((case-fold-search t)
14143 (stable org-mode-syntax-table)
14144 (tal (or org-tag-groups-alist-for-agenda
14145 org-tag-groups-alist))
14146 (tal (if downcased
14147 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14148 (tml (mapcar 'car tal))
14149 (rtnmatch match) rpl)
14150 ;; @ and _ are allowed as word-components in tags
14151 (modify-syntax-entry ?@ "w" stable)
14152 (modify-syntax-entry ?_ "w" stable)
14153 (while (and tml
14154 (with-syntax-table stable
14155 (string-match
14156 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14157 (regexp-opt tml) "\\>\\)") rtnmatch)))
14158 (let* ((dir (match-string 1 rtnmatch))
14159 (tag (match-string 2 rtnmatch))
14160 (tag (if downcased (downcase tag) tag)))
14161 (setq tml (delete tag tml))
14162 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14163 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14164 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14165 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14166 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14167 (if single-as-list
14168 (or (reverse rpl) (list rtnmatch))
14169 rtnmatch))
14170 (if single-as-list (list (if downcased (downcase match) match))
14171 match)))
14173 (defun org-op-to-function (op &optional stringp)
14174 "Turn an operator into the appropriate function."
14175 (setq op
14176 (cond
14177 ((equal op "<" ) '(< string< org-time<))
14178 ((equal op ">" ) '(> org-string> org-time>))
14179 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14180 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14181 ((member op '("=" "==")) '(= string= org-time=))
14182 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14183 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14185 (defun org<> (a b) (not (= a b)))
14186 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14187 (defun org-string>= (a b) (not (string< a b)))
14188 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14189 (defun org-string<> (a b) (not (string= a b)))
14190 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14191 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14192 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14193 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14194 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14195 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14196 (defun org-2ft (s)
14197 "Convert S to a floating point time.
14198 If S is already a number, just return it. If it is a string, parse
14199 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14200 (cond
14201 ((numberp s) s)
14202 ((stringp s)
14203 (condition-case nil
14204 (float-time (apply 'encode-time (org-parse-time-string s)))
14205 (error 0.)))
14206 (t 0.)))
14208 (defun org-time-today ()
14209 "Time in seconds today at 0:00.
14210 Returns the float number of seconds since the beginning of the
14211 epoch to the beginning of today (00:00)."
14212 (float-time (apply 'encode-time
14213 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14215 (defun org-matcher-time (s)
14216 "Interpret a time comparison value."
14217 (save-match-data
14218 (cond
14219 ((string= s "<now>") (float-time))
14220 ((string= s "<today>") (org-time-today))
14221 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14222 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14223 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14224 (+ (org-time-today)
14225 (* (string-to-number (match-string 1 s))
14226 (cdr (assoc (match-string 2 s)
14227 '(("d" . 86400.0) ("w" . 604800.0)
14228 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14229 (t (org-2ft s)))))
14231 (defun org-match-any-p (re list)
14232 "Does re match any element of list?"
14233 (setq list (mapcar (lambda (x) (string-match re x)) list))
14234 (delq nil list))
14236 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14237 (defvar org-tags-overlay (make-overlay 1 1))
14238 (org-detach-overlay org-tags-overlay)
14240 (defun org-get-local-tags-at (&optional pos)
14241 "Get a list of tags defined in the current headline."
14242 (org-get-tags-at pos 'local))
14244 (defun org-get-local-tags ()
14245 "Get a list of tags defined in the current headline."
14246 (org-get-tags-at nil 'local))
14248 (defun org-get-tags-at (&optional pos local)
14249 "Get a list of all headline tags applicable at POS.
14250 POS defaults to point. If tags are inherited, the list contains
14251 the targets in the same sequence as the headlines appear, i.e.
14252 the tags of the current headline come last.
14253 When LOCAL is non-nil, only return tags from the current headline,
14254 ignore inherited ones."
14255 (interactive)
14256 (if (and org-trust-scanner-tags
14257 (or (not pos) (equal pos (point)))
14258 (not local))
14259 org-scanner-tags
14260 (let (tags ltags lastpos parent)
14261 (save-excursion
14262 (save-restriction
14263 (widen)
14264 (goto-char (or pos (point)))
14265 (save-match-data
14266 (catch 'done
14267 (condition-case nil
14268 (progn
14269 (org-back-to-heading t)
14270 (while (not (equal lastpos (point)))
14271 (setq lastpos (point))
14272 (when (looking-at
14273 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14274 (setq ltags (org-split-string
14275 (org-match-string-no-properties 1) ":"))
14276 (when parent
14277 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14278 (setq tags (append
14279 (if parent
14280 (org-remove-uninherited-tags ltags)
14281 ltags)
14282 tags)))
14283 (or org-use-tag-inheritance (throw 'done t))
14284 (if local (throw 'done t))
14285 (or (org-up-heading-safe) (error nil))
14286 (setq parent t)))
14287 (error nil)))))
14288 (if local
14289 tags
14290 (reverse (delete-dups
14291 (reverse (append
14292 (org-remove-uninherited-tags
14293 org-file-tags) tags)))))))))
14295 (defun org-add-prop-inherited (s)
14296 (add-text-properties 0 (length s) '(inherited t) s)
14299 (defun org-toggle-tag (tag &optional onoff)
14300 "Toggle the tag TAG for the current line.
14301 If ONOFF is `on' or `off', don't toggle but set to this state."
14302 (let (res current)
14303 (save-excursion
14304 (org-back-to-heading t)
14305 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14306 (point-at-eol) t)
14307 (progn
14308 (setq current (match-string 1))
14309 (replace-match ""))
14310 (setq current ""))
14311 (setq current (nreverse (org-split-string current ":")))
14312 (cond
14313 ((eq onoff 'on)
14314 (setq res t)
14315 (or (member tag current) (push tag current)))
14316 ((eq onoff 'off)
14317 (or (not (member tag current)) (setq current (delete tag current))))
14318 (t (if (member tag current)
14319 (setq current (delete tag current))
14320 (setq res t)
14321 (push tag current))))
14322 (end-of-line 1)
14323 (if current
14324 (progn
14325 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14326 (org-set-tags nil t))
14327 (delete-horizontal-space))
14328 (run-hooks 'org-after-tags-change-hook))
14329 res))
14331 (defun org-align-tags-here (to-col)
14332 ;; Assumes that this is a headline
14333 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14334 (beginning-of-line 1)
14335 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14336 (< pos (match-beginning 2)))
14337 (progn
14338 (setq tags-l (- (match-end 2) (match-beginning 2)))
14339 (goto-char (match-beginning 1))
14340 (insert " ")
14341 (delete-region (point) (1+ (match-beginning 2)))
14342 (setq ncol (max (current-column)
14343 (1+ col)
14344 (if (> to-col 0)
14345 to-col
14346 (- (abs to-col) tags-l))))
14347 (setq p (point))
14348 (insert (make-string (- ncol (current-column)) ?\ ))
14349 (setq ncol (current-column))
14350 (when indent-tabs-mode (tabify p (point-at-eol)))
14351 (org-move-to-column (min ncol col) t))
14352 (goto-char pos))))
14354 (defun org-set-tags-command (&optional arg just-align)
14355 "Call the set-tags command for the current entry."
14356 (interactive "P")
14357 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14358 (org-set-tags arg just-align)
14359 (save-excursion
14360 (unless (and (org-region-active-p)
14361 org-loop-over-headlines-in-active-region)
14362 (org-back-to-heading t))
14363 (org-set-tags arg just-align))))
14365 (defun org-set-tags-to (data)
14366 "Set the tags of the current entry to DATA, replacing the current tags.
14367 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14368 If DATA is nil or the empty string, any tags will be removed."
14369 (interactive "sTags: ")
14370 (setq data
14371 (cond
14372 ((eq data nil) "")
14373 ((equal data "") "")
14374 ((stringp data)
14375 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14376 ":"))
14377 ((listp data)
14378 (concat ":" (mapconcat 'identity data ":") ":"))))
14379 (when data
14380 (save-excursion
14381 (org-back-to-heading t)
14382 (when (looking-at org-complex-heading-regexp)
14383 (if (match-end 5)
14384 (progn
14385 (goto-char (match-beginning 5))
14386 (insert data)
14387 (delete-region (point) (point-at-eol))
14388 (org-set-tags nil 'align))
14389 (goto-char (point-at-eol))
14390 (insert " " data)
14391 (org-set-tags nil 'align)))
14392 (beginning-of-line 1)
14393 (if (looking-at ".*?\\([ \t]+\\)$")
14394 (delete-region (match-beginning 1) (match-end 1))))))
14396 (defun org-align-all-tags ()
14397 "Align the tags i all headings."
14398 (interactive)
14399 (save-excursion
14400 (or (ignore-errors (org-back-to-heading t))
14401 (outline-next-heading))
14402 (if (org-at-heading-p)
14403 (org-set-tags t)
14404 (message "No headings"))))
14406 (defvar org-indent-indentation-per-level)
14407 (defun org-set-tags (&optional arg just-align)
14408 "Set the tags for the current headline.
14409 With prefix ARG, realign all tags in headings in the current buffer."
14410 (interactive "P")
14411 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14412 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14413 'region-start-level 'region))
14414 org-loop-over-headlines-in-active-region)
14415 (org-map-entries
14416 ;; We don't use ARG and JUST-ALIGN here these args are not
14417 ;; useful when looping over headlines
14418 `(org-set-tags)
14419 org-loop-over-headlines-in-active-region
14420 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14421 (let* ((re org-outline-regexp-bol)
14422 (current (unless arg (org-get-tags-string)))
14423 (col (current-column))
14424 (org-setting-tags t)
14425 table current-tags inherited-tags ; computed below when needed
14426 tags p0 c0 c1 rpl di tc level)
14427 (if arg
14428 (save-excursion
14429 (goto-char (point-min))
14430 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14431 (while (re-search-forward re nil t)
14432 (org-set-tags nil t)
14433 (end-of-line 1)))
14434 (message "All tags realigned to column %d" org-tags-column))
14435 (if just-align
14436 (setq tags current)
14437 ;; Get a new set of tags from the user
14438 (save-excursion
14439 (setq table (append org-tag-persistent-alist
14440 (or org-tag-alist (org-get-buffer-tags))
14441 (and
14442 org-complete-tags-always-offer-all-agenda-tags
14443 (org-global-tags-completion-table
14444 (org-agenda-files))))
14445 org-last-tags-completion-table table
14446 current-tags (org-split-string current ":")
14447 inherited-tags (nreverse
14448 (nthcdr (length current-tags)
14449 (nreverse (org-get-tags-at))))
14450 tags
14451 (if (or (eq t org-use-fast-tag-selection)
14452 (and org-use-fast-tag-selection
14453 (delq nil (mapcar 'cdr table))))
14454 (org-fast-tag-selection
14455 current-tags inherited-tags table
14456 (if org-fast-tag-selection-include-todo
14457 org-todo-key-alist))
14458 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14459 (org-trim
14460 (org-icompleting-read "Tags: "
14461 'org-tags-completion-function
14462 nil nil current 'org-tags-history))))))
14463 (while (string-match "[-+&]+" tags)
14464 ;; No boolean logic, just a list
14465 (setq tags (replace-match ":" t t tags))))
14467 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14469 (if org-tags-sort-function
14470 (setq tags (mapconcat 'identity
14471 (sort (org-split-string
14472 tags (org-re "[^[:alnum:]_@#%]+"))
14473 org-tags-sort-function) ":")))
14475 (if (string-match "\\`[\t ]*\\'" tags)
14476 (setq tags "")
14477 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14478 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14480 ;; Insert new tags at the correct column
14481 (beginning-of-line 1)
14482 (setq level (or (and (looking-at org-outline-regexp)
14483 (- (match-end 0) (point) 1))
14485 (cond
14486 ((and (equal current "") (equal tags "")))
14487 ((re-search-forward
14488 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14489 (point-at-eol) t)
14490 (if (equal tags "")
14491 (setq rpl "")
14492 (goto-char (match-beginning 0))
14493 (setq c0 (current-column)
14494 ;; compute offset for the case of org-indent-mode active
14495 di (if org-indent-mode
14496 (* (1- org-indent-indentation-per-level) (1- level))
14498 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14499 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14500 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14501 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14502 (replace-match rpl t t)
14503 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14504 tags)
14505 (t (error "Tags alignment failed")))
14506 (org-move-to-column col)
14507 (unless just-align
14508 (run-hooks 'org-after-tags-change-hook))))))
14510 (defun org-change-tag-in-region (beg end tag off)
14511 "Add or remove TAG for each entry in the region.
14512 This works in the agenda, and also in an org-mode buffer."
14513 (interactive
14514 (list (region-beginning) (region-end)
14515 (let ((org-last-tags-completion-table
14516 (if (derived-mode-p 'org-mode)
14517 (org-uniquify
14518 (delq nil (append (org-get-buffer-tags)
14519 (org-global-tags-completion-table))))
14520 (org-global-tags-completion-table))))
14521 (org-icompleting-read
14522 "Tag: " 'org-tags-completion-function nil nil nil
14523 'org-tags-history))
14524 (progn
14525 (message "[s]et or [r]emove? ")
14526 (equal (read-char-exclusive) ?r))))
14527 (if (fboundp 'deactivate-mark) (deactivate-mark))
14528 (let ((agendap (equal major-mode 'org-agenda-mode))
14529 l1 l2 m buf pos newhead (cnt 0))
14530 (goto-char end)
14531 (setq l2 (1- (org-current-line)))
14532 (goto-char beg)
14533 (setq l1 (org-current-line))
14534 (loop for l from l1 to l2 do
14535 (org-goto-line l)
14536 (setq m (get-text-property (point) 'org-hd-marker))
14537 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14538 (and agendap m))
14539 (setq buf (if agendap (marker-buffer m) (current-buffer))
14540 pos (if agendap m (point)))
14541 (with-current-buffer buf
14542 (save-excursion
14543 (save-restriction
14544 (goto-char pos)
14545 (setq cnt (1+ cnt))
14546 (org-toggle-tag tag (if off 'off 'on))
14547 (setq newhead (org-get-heading)))))
14548 (and agendap (org-agenda-change-all-lines newhead m))))
14549 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14551 (defun org-tags-completion-function (string predicate &optional flag)
14552 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14553 (confirm (lambda (x) (stringp (car x)))))
14554 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14555 (setq s1 (match-string 1 string)
14556 s2 (match-string 2 string))
14557 (setq s1 "" s2 string))
14558 (cond
14559 ((eq flag nil)
14560 ;; try completion
14561 (setq rtn (try-completion s2 ctable confirm))
14562 (if (stringp rtn)
14563 (setq rtn
14564 (concat s1 s2 (substring rtn (length s2))
14565 (if (and org-add-colon-after-tag-completion
14566 (assoc rtn ctable))
14567 ":" ""))))
14568 rtn)
14569 ((eq flag t)
14570 ;; all-completions
14571 (all-completions s2 ctable confirm))
14572 ((eq flag 'lambda)
14573 ;; exact match?
14574 (assoc s2 ctable)))))
14576 (defun org-fast-tag-insert (kwd tags face &optional end)
14577 "Insert KDW, and the TAGS, the latter with face FACE.
14578 Also insert END."
14579 (insert (format "%-12s" (concat kwd ":"))
14580 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14581 (or end "")))
14583 (defun org-fast-tag-show-exit (flag)
14584 (save-excursion
14585 (org-goto-line 3)
14586 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14587 (replace-match ""))
14588 (when flag
14589 (end-of-line 1)
14590 (org-move-to-column (- (window-width) 19) t)
14591 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14593 (defun org-set-current-tags-overlay (current prefix)
14594 "Add an overlay to CURRENT tag with PREFIX."
14595 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14596 (if (featurep 'xemacs)
14597 (org-overlay-display org-tags-overlay (concat prefix s)
14598 'secondary-selection)
14599 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14600 (org-overlay-display org-tags-overlay (concat prefix s)))))
14602 (defvar org-last-tag-selection-key nil)
14603 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14604 "Fast tag selection with single keys.
14605 CURRENT is the current list of tags in the headline, INHERITED is the
14606 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14607 possibly with grouping information. TODO-TABLE is a similar table with
14608 TODO keywords, should these have keys assigned to them.
14609 If the keys are nil, a-z are automatically assigned.
14610 Returns the new tags string, or nil to not change the current settings."
14611 (let* ((fulltable (append table todo-table))
14612 (maxlen (apply 'max (mapcar
14613 (lambda (x)
14614 (if (stringp (car x)) (string-width (car x)) 0))
14615 fulltable)))
14616 (buf (current-buffer))
14617 (expert (eq org-fast-tag-selection-single-key 'expert))
14618 (buffer-tags nil)
14619 (fwidth (+ maxlen 3 1 3))
14620 (ncol (/ (- (window-width) 4) fwidth))
14621 (i-face 'org-done)
14622 (c-face 'org-todo)
14623 tg cnt e c char c1 c2 ntable tbl rtn
14624 ov-start ov-end ov-prefix
14625 (exit-after-next org-fast-tag-selection-single-key)
14626 (done-keywords org-done-keywords)
14627 groups ingroup)
14628 (save-excursion
14629 (beginning-of-line 1)
14630 (if (looking-at
14631 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14632 (setq ov-start (match-beginning 1)
14633 ov-end (match-end 1)
14634 ov-prefix "")
14635 (setq ov-start (1- (point-at-eol))
14636 ov-end (1+ ov-start))
14637 (skip-chars-forward "^\n\r")
14638 (setq ov-prefix
14639 (concat
14640 (buffer-substring (1- (point)) (point))
14641 (if (> (current-column) org-tags-column)
14643 (make-string (- org-tags-column (current-column)) ?\ ))))))
14644 (move-overlay org-tags-overlay ov-start ov-end)
14645 (save-window-excursion
14646 (if expert
14647 (set-buffer (get-buffer-create " *Org tags*"))
14648 (delete-other-windows)
14649 (split-window-vertically)
14650 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14651 (erase-buffer)
14652 (org-set-local 'org-done-keywords done-keywords)
14653 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14654 (org-fast-tag-insert "Current" current c-face "\n\n")
14655 (org-fast-tag-show-exit exit-after-next)
14656 (org-set-current-tags-overlay current ov-prefix)
14657 (setq tbl fulltable char ?a cnt 0)
14658 (while (setq e (pop tbl))
14659 (cond
14660 ((equal (car e) :startgroup)
14661 (push '() groups) (setq ingroup t)
14662 (when (not (= cnt 0))
14663 (setq cnt 0)
14664 (insert "\n"))
14665 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14666 ((equal (car e) :endgroup)
14667 (setq ingroup nil cnt 0)
14668 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14669 ((equal e '(:newline))
14670 (when (not (= cnt 0))
14671 (setq cnt 0)
14672 (insert "\n")
14673 (setq e (car tbl))
14674 (while (equal (car tbl) '(:newline))
14675 (insert "\n")
14676 (setq tbl (cdr tbl)))))
14677 ((equal e '(:grouptags)) nil)
14679 (setq tg (copy-sequence (car e)) c2 nil)
14680 (if (cdr e)
14681 (setq c (cdr e))
14682 ;; automatically assign a character.
14683 (setq c1 (string-to-char
14684 (downcase (substring
14685 tg (if (= (string-to-char tg) ?@) 1 0)))))
14686 (if (or (rassoc c1 ntable) (rassoc c1 table))
14687 (while (or (rassoc char ntable) (rassoc char table))
14688 (setq char (1+ char)))
14689 (setq c2 c1))
14690 (setq c (or c2 char)))
14691 (if ingroup (push tg (car groups)))
14692 (setq tg (org-add-props tg nil 'face
14693 (cond
14694 ((not (assoc tg table))
14695 (org-get-todo-face tg))
14696 ((member tg current) c-face)
14697 ((member tg inherited) i-face))))
14698 (if (equal (caar tbl) :grouptags)
14699 (org-add-props tg nil 'face 'org-tag-group))
14700 (if (and (= cnt 0) (not ingroup)) (insert " "))
14701 (insert "[" c "] " tg (make-string
14702 (- fwidth 4 (length tg)) ?\ ))
14703 (push (cons tg c) ntable)
14704 (when (= (setq cnt (1+ cnt)) ncol)
14705 (insert "\n")
14706 (if ingroup (insert " "))
14707 (setq cnt 0)))))
14708 (setq ntable (nreverse ntable))
14709 (insert "\n")
14710 (goto-char (point-min))
14711 (if (not expert) (org-fit-window-to-buffer))
14712 (setq rtn
14713 (catch 'exit
14714 (while t
14715 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14716 (if (not groups) "no " "")
14717 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14718 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14719 (setq org-last-tag-selection-key c)
14720 (cond
14721 ((= c ?\r) (throw 'exit t))
14722 ((= c ?!)
14723 (setq groups (not groups))
14724 (goto-char (point-min))
14725 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14726 ((= c ?\C-c)
14727 (if (not expert)
14728 (org-fast-tag-show-exit
14729 (setq exit-after-next (not exit-after-next)))
14730 (setq expert nil)
14731 (delete-other-windows)
14732 (set-window-buffer (split-window-vertically) " *Org tags*")
14733 (org-switch-to-buffer-other-window " *Org tags*")
14734 (org-fit-window-to-buffer)))
14735 ((or (= c ?\C-g)
14736 (and (= c ?q) (not (rassoc c ntable))))
14737 (org-detach-overlay org-tags-overlay)
14738 (setq quit-flag t))
14739 ((= c ?\ )
14740 (setq current nil)
14741 (if exit-after-next (setq exit-after-next 'now)))
14742 ((= c ?\t)
14743 (condition-case nil
14744 (setq tg (org-icompleting-read
14745 "Tag: "
14746 (or buffer-tags
14747 (with-current-buffer buf
14748 (org-get-buffer-tags)))))
14749 (quit (setq tg "")))
14750 (when (string-match "\\S-" tg)
14751 (add-to-list 'buffer-tags (list tg))
14752 (if (member tg current)
14753 (setq current (delete tg current))
14754 (push tg current)))
14755 (if exit-after-next (setq exit-after-next 'now)))
14756 ((setq e (rassoc c todo-table) tg (car e))
14757 (with-current-buffer buf
14758 (save-excursion (org-todo tg)))
14759 (if exit-after-next (setq exit-after-next 'now)))
14760 ((setq e (rassoc c ntable) tg (car e))
14761 (if (member tg current)
14762 (setq current (delete tg current))
14763 (loop for g in groups do
14764 (if (member tg g)
14765 (mapc (lambda (x)
14766 (setq current (delete x current)))
14767 g)))
14768 (push tg current))
14769 (if exit-after-next (setq exit-after-next 'now))))
14771 ;; Create a sorted list
14772 (setq current
14773 (sort current
14774 (lambda (a b)
14775 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14776 (if (eq exit-after-next 'now) (throw 'exit t))
14777 (goto-char (point-min))
14778 (beginning-of-line 2)
14779 (delete-region (point) (point-at-eol))
14780 (org-fast-tag-insert "Current" current c-face)
14781 (org-set-current-tags-overlay current ov-prefix)
14782 (while (re-search-forward
14783 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14784 (setq tg (match-string 1))
14785 (add-text-properties
14786 (match-beginning 1) (match-end 1)
14787 (list 'face
14788 (cond
14789 ((member tg current) c-face)
14790 ((member tg inherited) i-face)
14791 (t (get-text-property (match-beginning 1) 'face))))))
14792 (goto-char (point-min)))))
14793 (org-detach-overlay org-tags-overlay)
14794 (if rtn
14795 (mapconcat 'identity current ":")
14796 nil))))
14798 (defun org-get-tags-string ()
14799 "Get the TAGS string in the current headline."
14800 (unless (org-at-heading-p t)
14801 (user-error "Not on a heading"))
14802 (save-excursion
14803 (beginning-of-line 1)
14804 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14805 (org-match-string-no-properties 1)
14806 "")))
14808 (defun org-get-tags ()
14809 "Get the list of tags specified in the current headline."
14810 (org-split-string (org-get-tags-string) ":"))
14812 (defun org-get-buffer-tags ()
14813 "Get a table of all tags used in the buffer, for completion."
14814 (let (tags)
14815 (save-excursion
14816 (goto-char (point-min))
14817 (while (re-search-forward
14818 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14819 (when (equal (char-after (point-at-bol 0)) ?*)
14820 (mapc (lambda (x) (add-to-list 'tags x))
14821 (org-split-string (org-match-string-no-properties 1) ":")))))
14822 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14823 (mapcar 'list tags)))
14825 ;;;; The mapping API
14827 (defun org-map-entries (func &optional match scope &rest skip)
14828 "Call FUNC at each headline selected by MATCH in SCOPE.
14830 FUNC is a function or a lisp form. The function will be called without
14831 arguments, with the cursor positioned at the beginning of the headline.
14832 The return values of all calls to the function will be collected and
14833 returned as a list.
14835 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14836 does not need to preserve point. After evaluation, the cursor will be
14837 moved to the end of the line (presumably of the headline of the
14838 processed entry) and search continues from there. Under some
14839 circumstances, this may not produce the wanted results. For example,
14840 if you have removed (e.g. archived) the current (sub)tree it could
14841 mean that the next entry will be skipped entirely. In such cases, you
14842 can specify the position from where search should continue by making
14843 FUNC set the variable `org-map-continue-from' to the desired buffer
14844 position.
14846 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14847 Only headlines that are matched by this query will be considered during
14848 the iteration. When MATCH is nil or t, all headlines will be
14849 visited by the iteration.
14851 SCOPE determines the scope of this command. It can be any of:
14853 nil The current buffer, respecting the restriction if any
14854 tree The subtree started with the entry at point
14855 region The entries within the active region, if any
14856 region-start-level
14857 The entries within the active region, but only those at
14858 the same level than the first one.
14859 file The current buffer, without restriction
14860 file-with-archives
14861 The current buffer, and any archives associated with it
14862 agenda All agenda files
14863 agenda-with-archives
14864 All agenda files with any archive files associated with them
14865 \(file1 file2 ...)
14866 If this is a list, all files in the list will be scanned
14868 The remaining args are treated as settings for the skipping facilities of
14869 the scanner. The following items can be given here:
14871 archive skip trees with the archive tag
14872 comment skip trees with the COMMENT keyword
14873 function or Emacs Lisp form:
14874 will be used as value for `org-agenda-skip-function', so
14875 whenever the function returns a position, FUNC will not be
14876 called for that entry and search will continue from the
14877 position returned
14879 If your function needs to retrieve the tags including inherited tags
14880 at the *current* entry, you can use the value of the variable
14881 `org-scanner-tags' which will be much faster than getting the value
14882 with `org-get-tags-at'. If your function gets properties with
14883 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14884 to t around the call to `org-entry-properties' to get the same speedup.
14885 Note that if your function moves around to retrieve tags and properties at
14886 a *different* entry, you cannot use these techniques."
14887 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14888 (not (org-region-active-p)))
14889 (let* ((org-agenda-archives-mode nil) ; just to make sure
14890 (org-agenda-skip-archived-trees (memq 'archive skip))
14891 (org-agenda-skip-comment-trees (memq 'comment skip))
14892 (org-agenda-skip-function
14893 (car (org-delete-all '(comment archive) skip)))
14894 (org-tags-match-list-sublevels t)
14895 (start-level (eq scope 'region-start-level))
14896 matcher file res
14897 org-todo-keywords-for-agenda
14898 org-done-keywords-for-agenda
14899 org-todo-keyword-alist-for-agenda
14900 org-drawers-for-agenda
14901 org-tag-alist-for-agenda
14902 todo-only)
14904 (cond
14905 ((eq match t) (setq matcher t))
14906 ((eq match nil) (setq matcher t))
14907 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14909 (save-window-excursion
14910 (save-restriction
14911 (cond ((eq scope 'tree)
14912 (org-back-to-heading t)
14913 (org-narrow-to-subtree)
14914 (setq scope nil))
14915 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14916 (org-region-active-p))
14917 ;; If needed, set start-level to a string like "2"
14918 (when start-level
14919 (save-excursion
14920 (goto-char (region-beginning))
14921 (unless (org-at-heading-p) (outline-next-heading))
14922 (setq start-level (org-current-level))))
14923 (narrow-to-region (region-beginning)
14924 (save-excursion
14925 (goto-char (region-end))
14926 (unless (and (bolp) (org-at-heading-p))
14927 (outline-next-heading))
14928 (point)))
14929 (setq scope nil)))
14931 (if (not scope)
14932 (progn
14933 (org-agenda-prepare-buffers
14934 (list (buffer-file-name (current-buffer))))
14935 (setq res (org-scan-tags func matcher todo-only start-level)))
14936 ;; Get the right scope
14937 (cond
14938 ((and scope (listp scope) (symbolp (car scope)))
14939 (setq scope (eval scope)))
14940 ((eq scope 'agenda)
14941 (setq scope (org-agenda-files t)))
14942 ((eq scope 'agenda-with-archives)
14943 (setq scope (org-agenda-files t))
14944 (setq scope (org-add-archive-files scope)))
14945 ((eq scope 'file)
14946 (setq scope (list (buffer-file-name))))
14947 ((eq scope 'file-with-archives)
14948 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14949 (org-agenda-prepare-buffers scope)
14950 (while (setq file (pop scope))
14951 (with-current-buffer (org-find-base-buffer-visiting file)
14952 (save-excursion
14953 (save-restriction
14954 (widen)
14955 (goto-char (point-min))
14956 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14957 res)))
14959 ;;;; Properties
14961 ;;; Setting and retrieving properties
14963 (defconst org-special-properties
14964 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14965 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14966 "The special properties valid in Org-mode.
14968 These are properties that are not defined in the property drawer,
14969 but in some other way.")
14971 (defconst org-default-properties
14972 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14973 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14974 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14975 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14976 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14977 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14978 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14979 "Some properties that are used by Org-mode for various purposes.
14980 Being in this list makes sure that they are offered for completion.")
14982 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14983 "Regular expression matching the first line of a property drawer.")
14985 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14986 "Regular expression matching the last line of a property drawer.")
14988 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14989 "Regular expression matching the first line of a property drawer.")
14991 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14992 "Regular expression matching the first line of a property drawer.")
14994 (defconst org-property-drawer-re
14995 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14996 org-property-end-re "\\)\n?")
14997 "Matches an entire property drawer.")
14999 (defconst org-clock-drawer-re
15000 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15001 org-property-end-re "\\)\n?")
15002 "Matches an entire clock drawer.")
15004 (defsubst org-re-property (property)
15005 "Return a regexp matching a PROPERTY line.
15006 Match group 1 will be set to the value."
15007 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15009 (defsubst org-re-property-keyword (property)
15010 "Return a regexp matching a PROPERTY line, possibly with no
15011 value for the property."
15012 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15014 (defun org-property-action ()
15015 "Do an action on properties."
15016 (interactive)
15017 (let (c)
15018 (org-at-property-p)
15019 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15020 (setq c (read-char-exclusive))
15021 (cond
15022 ((equal c ?s)
15023 (call-interactively 'org-set-property))
15024 ((equal c ?d)
15025 (call-interactively 'org-delete-property))
15026 ((equal c ?D)
15027 (call-interactively 'org-delete-property-globally))
15028 ((equal c ?c)
15029 (call-interactively 'org-compute-property-at-point))
15030 (t (user-error "No such property action %c" c)))))
15032 (defun org-inc-effort ()
15033 "Increment the value of the effort property in the current entry."
15034 (interactive)
15035 (org-set-effort nil t))
15037 (defvar org-clock-effort) ;; Defined in org-clock.el
15038 (defvar org-clock-current-task) ;; Defined in org-clock.el
15039 (defun org-set-effort (&optional value increment)
15040 "Set the effort property of the current entry.
15041 With numerical prefix arg, use the nth allowed value, 0 stands for the
15042 10th allowed value.
15044 When INCREMENT is non-nil, set the property to the next allowed value."
15045 (interactive "P")
15046 (if (equal value 0) (setq value 10))
15047 (let* ((completion-ignore-case t)
15048 (prop org-effort-property)
15049 (cur (org-entry-get nil prop))
15050 (allowed (org-property-get-allowed-values nil prop 'table))
15051 (existing (mapcar 'list (org-property-values prop)))
15052 (heading (nth 4 (org-heading-components)))
15054 (val (cond
15055 ((stringp value) value)
15056 ((and allowed (integerp value))
15057 (or (car (nth (1- value) allowed))
15058 (car (org-last allowed))))
15059 ((and allowed increment)
15060 (or (caadr (member (list cur) allowed))
15061 (user-error "Allowed effort values are not set")))
15062 (allowed
15063 (message "Select 1-9,0, [RET%s]: %s"
15064 (if cur (concat "=" cur) "")
15065 (mapconcat 'car allowed " "))
15066 (setq rpl (read-char-exclusive))
15067 (if (equal rpl ?\r)
15069 (setq rpl (- rpl ?0))
15070 (if (equal rpl 0) (setq rpl 10))
15071 (if (and (> rpl 0) (<= rpl (length allowed)))
15072 (car (nth (1- rpl) allowed))
15073 (org-completing-read "Effort: " allowed nil))))
15075 (let (org-completion-use-ido org-completion-use-iswitchb)
15076 (org-completing-read
15077 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15078 (concat "[" cur "]") "")
15079 ": ")
15080 existing nil nil "" nil cur))))))
15081 (unless (equal (org-entry-get nil prop) val)
15082 (org-entry-put nil prop val))
15083 (save-excursion
15084 (org-back-to-heading t)
15085 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15086 (when (string= heading org-clock-current-task)
15087 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15088 (org-clock-update-mode-line))
15089 (message "%s is now %s" prop val)))
15091 (defun org-at-property-p ()
15092 "Is cursor inside a property drawer?"
15093 (save-excursion
15094 (beginning-of-line 1)
15095 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15096 (save-match-data ;; Used by calling procedures
15097 (let ((p (point))
15098 (range (unless (org-before-first-heading-p)
15099 (org-get-property-block))))
15100 (and range (<= (car range) p) (< p (cdr range))))))))
15102 (defun org-get-property-block (&optional beg end force)
15103 "Return the (beg . end) range of the body of the property drawer.
15104 BEG and END are the beginning and end of the current subtree, or of
15105 the part before the first headline. If they are not given, they will
15106 be found. If the drawer does not exist and FORCE is non-nil, create
15107 the drawer."
15108 (catch 'exit
15109 (save-excursion
15110 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15111 (progn (org-back-to-heading t) (point))))
15112 (end (or end (and (not (outline-next-heading)) (point-max))
15113 (point))))
15114 (goto-char beg)
15115 (if (re-search-forward org-property-start-re end t)
15116 (setq beg (1+ (match-end 0)))
15117 (if force
15118 (save-excursion
15119 (org-insert-property-drawer)
15120 (setq end (progn (outline-next-heading) (point))))
15121 (throw 'exit nil))
15122 (goto-char beg)
15123 (if (re-search-forward org-property-start-re end t)
15124 (setq beg (1+ (match-end 0)))))
15125 (if (re-search-forward org-property-end-re end t)
15126 (setq end (match-beginning 0))
15127 (or force (throw 'exit nil))
15128 (goto-char beg)
15129 (setq end beg)
15130 (org-indent-line)
15131 (insert ":END:\n"))
15132 (cons beg end)))))
15134 (defun org-entry-properties (&optional pom which specific)
15135 "Get all properties of the entry at point-or-marker POM.
15136 This includes the TODO keyword, the tags, time strings for deadline,
15137 scheduled, and clocking, and any additional properties defined in the
15138 entry. The return value is an alist, keys may occur multiple times
15139 if the property key was used several times.
15140 POM may also be nil, in which case the current entry is used.
15141 If WHICH is nil or `all', get all properties. If WHICH is
15142 `special' or `standard', only get that subclass. If WHICH
15143 is a string only get exactly this property. SPECIFIC can be a string, the
15144 specific property we are interested in. Specifying it can speed
15145 things up because then unnecessary parsing is avoided."
15146 (setq which (or which 'all))
15147 (org-with-point-at pom
15148 (let ((clockstr (substring org-clock-string 0 -1))
15149 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15150 (case-fold-search nil)
15151 beg end range props sum-props key key1 value string clocksum clocksumt)
15152 (save-excursion
15153 (when (condition-case nil
15154 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15155 (error nil))
15156 (setq beg (point))
15157 (setq sum-props (get-text-property (point) 'org-summaries))
15158 (setq clocksum (get-text-property (point) :org-clock-minutes)
15159 clocksumt (get-text-property (point) :org-clock-minutes-today))
15160 (outline-next-heading)
15161 (setq end (point))
15162 (when (memq which '(all special))
15163 ;; Get the special properties, like TODO and tags
15164 (goto-char beg)
15165 (when (and (or (not specific) (string= specific "TODO"))
15166 (looking-at org-todo-line-regexp) (match-end 2))
15167 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15168 (when (and (or (not specific) (string= specific "PRIORITY"))
15169 (looking-at org-priority-regexp))
15170 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15171 (when (or (not specific) (string= specific "FILE"))
15172 (push (cons "FILE" buffer-file-name) props))
15173 (when (and (or (not specific) (string= specific "TAGS"))
15174 (setq value (org-get-tags-string))
15175 (string-match "\\S-" value))
15176 (push (cons "TAGS" value) props))
15177 (when (and (or (not specific) (string= specific "ALLTAGS"))
15178 (setq value (org-get-tags-at)))
15179 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15180 ":"))
15181 props))
15182 (when (or (not specific) (string= specific "BLOCKED"))
15183 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15184 (when (or (not specific)
15185 (member specific
15186 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15187 "TIMESTAMP" "TIMESTAMP_IA")))
15188 (catch 'match
15189 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15190 (setq key (if (match-end 1)
15191 (substring (org-match-string-no-properties 1)
15192 0 -1))
15193 string (if (equal key clockstr)
15194 (org-trim
15195 (buffer-substring-no-properties
15196 (match-beginning 3) (goto-char
15197 (point-at-eol))))
15198 (substring (org-match-string-no-properties 3)
15199 1 -1)))
15200 ;; Get the correct property name from the key. This is
15201 ;; necessary if the user has configured time keywords.
15202 (setq key1 (concat key ":"))
15203 (cond
15204 ((not key)
15205 (setq key
15206 (if (= (char-after (match-beginning 3)) ?\[)
15207 "TIMESTAMP_IA" "TIMESTAMP")))
15208 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15209 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15210 ((equal key1 org-closed-string) (setq key "CLOSED"))
15211 ((equal key1 org-clock-string) (setq key "CLOCK")))
15212 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15213 (progn
15214 (push (cons key string) props)
15215 ;; no need to search further if match is found
15216 (throw 'match t))
15217 (when (or (equal key "CLOCK") (not (assoc key props)))
15218 (push (cons key string) props)))))))
15220 (when (memq which '(all standard))
15221 ;; Get the standard properties, like :PROP: ...
15222 (setq range (org-get-property-block beg end))
15223 (when range
15224 (goto-char (car range))
15225 (while (re-search-forward
15226 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15227 (cdr range) t)
15228 (setq key (org-match-string-no-properties 1)
15229 value (org-trim (or (org-match-string-no-properties 2) "")))
15230 (unless (member key excluded)
15231 (push (cons key (or value "")) props)))))
15232 (if clocksum
15233 (push (cons "CLOCKSUM"
15234 (org-columns-number-to-string (/ (float clocksum) 60.)
15235 'add_times))
15236 props))
15237 (if clocksumt
15238 (push (cons "CLOCKSUM_T"
15239 (org-columns-number-to-string (/ (float clocksumt) 60.)
15240 'add_times))
15241 props))
15242 (unless (assoc "CATEGORY" props)
15243 (push (cons "CATEGORY" (org-get-category)) props))
15244 (append sum-props (nreverse props)))))))
15246 (defun org-entry-get (pom property &optional inherit literal-nil)
15247 "Get value of PROPERTY for entry or content at point-or-marker POM.
15248 If INHERIT is non-nil and the entry does not have the property,
15249 then also check higher levels of the hierarchy.
15250 If INHERIT is the symbol `selective', use inheritance only if the setting
15251 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15252 If the property is present but empty, the return value is the empty string.
15253 If the property is not present at all, nil is returned.
15255 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15256 do not interpret it as the list atom nil. This is used for inheritance
15257 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15258 (org-with-point-at pom
15259 (if (and inherit (if (eq inherit 'selective)
15260 (org-property-inherit-p property)
15262 (org-entry-get-with-inheritance property literal-nil)
15263 (if (member property org-special-properties)
15264 ;; We need a special property. Use `org-entry-properties' to
15265 ;; retrieve it, but specify the wanted property
15266 (cdr (assoc property (org-entry-properties nil 'special property)))
15267 (let ((range (org-get-property-block)))
15268 (when (and range (not (eq (car range) (cdr range))))
15269 (let* ((props (list (or (assoc property org-file-properties)
15270 (assoc property org-global-properties)
15271 (assoc property org-global-properties-fixed))))
15272 (ap (lambda (key)
15273 (when (re-search-forward
15274 (org-re-property key) (cdr range) t)
15275 (setq props
15276 (org-update-property-plist
15278 (if (match-end 1)
15279 (org-match-string-no-properties 1) "")
15280 props)))))
15281 val)
15282 (goto-char (car range))
15283 (funcall ap property)
15284 (goto-char (car range))
15285 (while (funcall ap (concat property "+")))
15286 (setq val (cdr (assoc property props)))
15287 (when val (if literal-nil val (org-not-nil val))))))))))
15289 (defun org-property-or-variable-value (var &optional inherit)
15290 "Check if there is a property fixing the value of VAR.
15291 If yes, return this value. If not, return the current value of the variable."
15292 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15293 (if (and prop (stringp prop) (string-match "\\S-" prop))
15294 (read prop)
15295 (symbol-value var))))
15297 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15298 "Delete the property PROPERTY from entry at point-or-marker POM.
15299 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15300 an empty drawer to delete."
15301 (org-with-point-at pom
15302 (if (member property org-special-properties)
15303 nil ; cannot delete these properties.
15304 (let ((range (org-get-property-block)))
15305 (if (and range
15306 (goto-char (car range))
15307 (re-search-forward
15308 (org-re-property property)
15309 (cdr range) t))
15310 (progn
15311 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15312 (and delete-empty-drawer
15313 (org-remove-empty-drawer-at
15314 delete-empty-drawer (car range)))
15316 nil)))))
15318 ;; Multi-values properties are properties that contain multiple values
15319 ;; These values are assumed to be single words, separated by whitespace.
15320 (defun org-entry-add-to-multivalued-property (pom property value)
15321 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15322 (let* ((old (org-entry-get pom property))
15323 (values (and old (org-split-string old "[ \t]"))))
15324 (setq value (org-entry-protect-space value))
15325 (unless (member value values)
15326 (setq values (append values (list value)))
15327 (org-entry-put pom property
15328 (mapconcat 'identity values " ")))))
15330 (defun org-entry-remove-from-multivalued-property (pom property value)
15331 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15332 (let* ((old (org-entry-get pom property))
15333 (values (and old (org-split-string old "[ \t]"))))
15334 (setq value (org-entry-protect-space value))
15335 (when (member value values)
15336 (setq values (delete value values))
15337 (org-entry-put pom property
15338 (mapconcat 'identity values " ")))))
15340 (defun org-entry-member-in-multivalued-property (pom property value)
15341 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15342 (let* ((old (org-entry-get pom property))
15343 (values (and old (org-split-string old "[ \t]"))))
15344 (setq value (org-entry-protect-space value))
15345 (member value values)))
15347 (defun org-entry-get-multivalued-property (pom property)
15348 "Return a list of values in a multivalued property."
15349 (let* ((value (org-entry-get pom property))
15350 (values (and value (org-split-string value "[ \t]"))))
15351 (mapcar 'org-entry-restore-space values)))
15353 (defun org-entry-put-multivalued-property (pom property &rest values)
15354 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15355 VALUES should be a list of strings. Spaces will be protected."
15356 (org-entry-put pom property
15357 (mapconcat 'org-entry-protect-space values " "))
15358 (let* ((value (org-entry-get pom property))
15359 (values (and value (org-split-string value "[ \t]"))))
15360 (mapcar 'org-entry-restore-space values)))
15362 (defun org-entry-protect-space (s)
15363 "Protect spaces and newline in string S."
15364 (while (string-match " " s)
15365 (setq s (replace-match "%20" t t s)))
15366 (while (string-match "\n" s)
15367 (setq s (replace-match "%0A" t t s)))
15370 (defun org-entry-restore-space (s)
15371 "Restore spaces and newline in string S."
15372 (while (string-match "%20" s)
15373 (setq s (replace-match " " t t s)))
15374 (while (string-match "%0A" s)
15375 (setq s (replace-match "\n" t t s)))
15378 (defvar org-entry-property-inherited-from (make-marker)
15379 "Marker pointing to the entry from where a property was inherited.
15380 Each call to `org-entry-get-with-inheritance' will set this marker to the
15381 location of the entry where the inheritance search matched. If there was
15382 no match, the marker will point nowhere.
15383 Note that also `org-entry-get' calls this function, if the INHERIT flag
15384 is set.")
15386 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15387 "Get PROPERTY of entry or content at point, search higher levels if needed.
15388 The search will stop at the first ancestor which has the property defined.
15389 If the value found is \"nil\", return nil to show that the property
15390 should be considered as undefined (this is the meaning of nil here).
15391 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15392 (move-marker org-entry-property-inherited-from nil)
15393 (let (tmp)
15394 (save-excursion
15395 (save-restriction
15396 (widen)
15397 (catch 'ex
15398 (while t
15399 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15400 (or (ignore-errors (org-back-to-heading t))
15401 (goto-char (point-min)))
15402 (move-marker org-entry-property-inherited-from (point))
15403 (throw 'ex tmp))
15404 (or (ignore-errors (org-up-heading-safe))
15405 (throw 'ex nil))))))
15406 (setq tmp (or tmp
15407 (cdr (assoc property org-file-properties))
15408 (cdr (assoc property org-global-properties))
15409 (cdr (assoc property org-global-properties-fixed))))
15410 (if literal-nil tmp (org-not-nil tmp))))
15412 (defvar org-property-changed-functions nil
15413 "Hook called when the value of a property has changed.
15414 Each hook function should accept two arguments, the name of the property
15415 and the new value.")
15417 (defun org-entry-put (pom property value)
15418 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15419 (org-with-point-at pom
15420 (org-back-to-heading t)
15421 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15422 range)
15423 (cond
15424 ((equal property "TODO")
15425 (when (and (stringp value) (string-match "\\S-" value)
15426 (not (member value org-todo-keywords-1)))
15427 (user-error "\"%s\" is not a valid TODO state" value))
15428 (if (or (not value)
15429 (not (string-match "\\S-" value)))
15430 (setq value 'none))
15431 (org-todo value)
15432 (org-set-tags nil 'align))
15433 ((equal property "PRIORITY")
15434 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15435 (string-to-char value) ?\ ))
15436 (org-set-tags nil 'align))
15437 ((equal property "CLOCKSUM")
15438 (if (not (re-search-forward
15439 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15440 (error "Cannot find a clock log")
15441 (goto-char (- (match-end 1) 2))
15442 (cond
15443 ((eq value 'earlier) (org-timestamp-down))
15444 ((eq value 'later) (org-timestamp-up)))
15445 (org-clock-sum-current-item)))
15446 ((equal property "SCHEDULED")
15447 (if (re-search-forward org-scheduled-time-regexp end t)
15448 (cond
15449 ((eq value 'earlier) (org-timestamp-change -1 'day))
15450 ((eq value 'later) (org-timestamp-change 1 'day))
15451 (t (call-interactively 'org-schedule)))
15452 (call-interactively 'org-schedule)))
15453 ((equal property "DEADLINE")
15454 (if (re-search-forward org-deadline-time-regexp end t)
15455 (cond
15456 ((eq value 'earlier) (org-timestamp-change -1 'day))
15457 ((eq value 'later) (org-timestamp-change 1 'day))
15458 (t (call-interactively 'org-deadline)))
15459 (call-interactively 'org-deadline)))
15460 ((member property org-special-properties)
15461 (error "The %s property can not yet be set with `org-entry-put'"
15462 property))
15463 (t ; a non-special property
15464 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15465 (setq range (org-get-property-block beg end 'force))
15466 (goto-char (car range))
15467 (if (re-search-forward
15468 (org-re-property-keyword property) (cdr range) t)
15469 (progn
15470 (delete-region (match-beginning 0) (match-end 0))
15471 (goto-char (match-beginning 0)))
15472 (goto-char (cdr range))
15473 (insert "\n")
15474 (backward-char 1)
15475 (org-indent-line))
15476 (insert ":" property ":")
15477 (and value (insert " " value))
15478 (org-indent-line)))))
15479 (run-hook-with-args 'org-property-changed-functions property value)))
15481 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15482 "Get all property keys in the current buffer.
15483 With INCLUDE-SPECIALS, also list the special properties that reflect things
15484 like tags and TODO state.
15485 With INCLUDE-DEFAULTS, also include properties that has special meaning
15486 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15487 and others.
15488 With INCLUDE-COLUMNS, also include property names given in COLUMN
15489 formats in the current buffer."
15490 (let (rtn range cfmt s p)
15491 (save-excursion
15492 (save-restriction
15493 (widen)
15494 (goto-char (point-min))
15495 (while (re-search-forward org-property-start-re nil t)
15496 (setq range (org-get-property-block))
15497 (goto-char (car range))
15498 (while (re-search-forward
15499 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15500 (cdr range) t)
15501 (add-to-list 'rtn (org-match-string-no-properties 1)))
15502 (outline-next-heading))))
15504 (when include-specials
15505 (setq rtn (append org-special-properties rtn)))
15507 (when include-defaults
15508 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15509 (add-to-list 'rtn org-effort-property))
15511 (when include-columns
15512 (save-excursion
15513 (save-restriction
15514 (widen)
15515 (goto-char (point-min))
15516 (while (re-search-forward
15517 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15518 nil t)
15519 (setq cfmt (match-string 2) s 0)
15520 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15521 cfmt s)
15522 (setq s (match-end 0)
15523 p (match-string 1 cfmt))
15524 (unless (or (equal p "ITEM")
15525 (member p org-special-properties))
15526 (add-to-list 'rtn (match-string 1 cfmt))))))))
15528 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15530 (defun org-property-values (key)
15531 "Return a list of all values of property KEY in the current buffer."
15532 (save-excursion
15533 (save-restriction
15534 (widen)
15535 (goto-char (point-min))
15536 (let ((re (org-re-property key))
15537 values)
15538 (while (re-search-forward re nil t)
15539 (add-to-list 'values (org-trim (match-string 1))))
15540 (delete "" values)))))
15542 (defun org-insert-property-drawer ()
15543 "Insert a property drawer into the current entry."
15544 (org-back-to-heading t)
15545 (looking-at org-outline-regexp)
15546 (let ((indent (if org-adapt-indentation
15547 (- (match-end 0) (match-beginning 0))
15549 (beg (point))
15550 (re (concat "^[ \t]*" org-keyword-time-regexp))
15551 end hiddenp)
15552 (outline-next-heading)
15553 (setq end (point))
15554 (goto-char beg)
15555 (while (re-search-forward re end t))
15556 (setq hiddenp (outline-invisible-p))
15557 (end-of-line 1)
15558 (and (equal (char-after) ?\n) (forward-char 1))
15559 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15560 (if (member (match-string 1) '("CLOCK:" ":END:"))
15561 ;; just skip this line
15562 (beginning-of-line 2)
15563 ;; Drawer start, find the end
15564 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15565 (beginning-of-line 1)))
15566 (org-skip-over-state-notes)
15567 (skip-chars-backward " \t\n\r")
15568 (if (eq (char-before) ?*) (forward-char 1))
15569 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15570 (beginning-of-line 0)
15571 (org-indent-to-column indent)
15572 (beginning-of-line 2)
15573 (org-indent-to-column indent)
15574 (beginning-of-line 0)
15575 (if hiddenp
15576 (save-excursion
15577 (org-back-to-heading t)
15578 (hide-entry))
15579 (org-flag-drawer t))))
15581 (defun org-insert-drawer (&optional arg drawer)
15582 "Insert a drawer at point.
15584 Optional argument DRAWER, when non-nil, is a string representing
15585 drawer's name. Otherwise, the user is prompted for a name.
15587 If a region is active, insert the drawer around that region
15588 instead.
15590 Point is left between drawer's boundaries."
15591 (interactive "P")
15592 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15593 "LOGBOOK"))
15594 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15595 ;; internally by Org. They are meant to be inserted
15596 ;; automatically.
15597 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15598 ;; Remove system drawers from list. Note: For some reason,
15599 ;; `org-completing-read' ignores the predicate while
15600 ;; `completing-read' handles it fine.
15601 (drawer (if arg "PROPERTIES"
15602 (or drawer
15603 (completing-read
15604 "Drawer: " org-drawers
15605 (lambda (d) (not (member d system-drawers))))))))
15606 (cond
15607 ;; With C-u, fall back on `org-insert-property-drawer'
15608 (arg (org-insert-property-drawer))
15609 ;; With an active region, insert a drawer at point.
15610 ((not (org-region-active-p))
15611 (progn
15612 (unless (bolp) (insert "\n"))
15613 (insert (format ":%s:\n\n:END:\n" drawer))
15614 (forward-line -2)))
15615 ;; Otherwise, insert the drawer at point
15617 (let ((rbeg (region-beginning))
15618 (rend (copy-marker (region-end))))
15619 (unwind-protect
15620 (progn
15621 (goto-char rbeg)
15622 (beginning-of-line)
15623 (when (save-excursion
15624 (re-search-forward org-outline-regexp-bol rend t))
15625 (user-error "Drawers cannot contain headlines"))
15626 ;; Position point at the beginning of the first
15627 ;; non-blank line in region. Insert drawer's opening
15628 ;; there, then indent it.
15629 (org-skip-whitespace)
15630 (beginning-of-line)
15631 (insert ":" drawer ":\n")
15632 (forward-line -1)
15633 (indent-for-tab-command)
15634 ;; Move point to the beginning of the first blank line
15635 ;; after the last non-blank line in region. Insert
15636 ;; drawer's closing, then indent it.
15637 (goto-char rend)
15638 (skip-chars-backward " \r\t\n")
15639 (insert "\n:END:")
15640 (deactivate-mark t)
15641 (indent-for-tab-command)
15642 (unless (eolp) (insert "\n")))
15643 ;; Clear marker, whatever the outcome of insertion is.
15644 (set-marker rend nil)))))))
15646 (defvar org-property-set-functions-alist nil
15647 "Property set function alist.
15648 Each entry should have the following format:
15650 (PROPERTY . READ-FUNCTION)
15652 The read function will be called with the same argument as
15653 `org-completing-read'.")
15655 (defun org-set-property-function (property)
15656 "Get the function that should be used to set PROPERTY.
15657 This is computed according to `org-property-set-functions-alist'."
15658 (or (cdr (assoc property org-property-set-functions-alist))
15659 'org-completing-read))
15661 (defun org-read-property-value (property)
15662 "Read PROPERTY value from user."
15663 (let* ((completion-ignore-case t)
15664 (allowed (org-property-get-allowed-values nil property 'table))
15665 (cur (org-entry-get nil property))
15666 (prompt (concat property " value"
15667 (if (and cur (string-match "\\S-" cur))
15668 (concat " [" cur "]") "") ": "))
15669 (set-function (org-set-property-function property))
15670 (val (if allowed
15671 (funcall set-function prompt allowed nil
15672 (not (get-text-property 0 'org-unrestricted
15673 (caar allowed))))
15674 (let (org-completion-use-ido org-completion-use-iswitchb)
15675 (funcall set-function prompt
15676 (mapcar 'list (org-property-values property))
15677 nil nil "" nil cur)))))
15678 (if (equal val "")
15680 val)))
15682 (defvar org-last-set-property nil)
15683 (defvar org-last-set-property-value nil)
15684 (defun org-read-property-name ()
15685 "Read a property name."
15686 (let* ((completion-ignore-case t)
15687 (keys (org-buffer-property-keys nil t t))
15688 (default-prop (or (save-excursion
15689 (save-match-data
15690 (beginning-of-line)
15691 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15692 (null (string= (match-string 1) "END"))
15693 (match-string 1))))
15694 org-last-set-property))
15695 (property (org-icompleting-read
15696 (concat "Property"
15697 (if default-prop (concat " [" default-prop "]") "")
15698 ": ")
15699 (mapcar 'list keys)
15700 nil nil nil nil
15701 default-prop)))
15702 (if (member property keys)
15703 property
15704 (or (cdr (assoc (downcase property)
15705 (mapcar (lambda (x) (cons (downcase x) x))
15706 keys)))
15707 property))))
15709 (defun org-set-property-and-value (use-last)
15710 "Allow to set [PROPERTY]: [value] direction from prompt.
15711 When use-default, don't even ask, just use the last
15712 \"[PROPERTY]: [value]\" string from the history."
15713 (interactive "P")
15714 (let* ((completion-ignore-case t)
15715 (pv (or (and use-last org-last-set-property-value)
15716 (org-completing-read
15717 "Enter a \"[Property]: [value]\" pair: "
15718 nil nil nil nil nil
15719 org-last-set-property-value)))
15720 prop val)
15721 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15722 (setq prop (match-string 1 pv)
15723 val (match-string 2 pv))
15724 (org-set-property prop val))))
15726 (defun org-set-property (property value)
15727 "In the current entry, set PROPERTY to VALUE.
15728 When called interactively, this will prompt for a property name, offering
15729 completion on existing and default properties. And then it will prompt
15730 for a value, offering completion either on allowed values (via an inherited
15731 xxx_ALL property) or on existing values in other instances of this property
15732 in the current file."
15733 (interactive (list nil nil))
15734 (let* ((property (or property (org-read-property-name)))
15735 (value (or value (org-read-property-value property)))
15736 (fn (cdr (assoc property org-properties-postprocess-alist))))
15737 (setq org-last-set-property property)
15738 (setq org-last-set-property-value (concat property ": " value))
15739 ;; Possibly postprocess the inserted value:
15740 (when fn (setq value (funcall fn value)))
15741 (unless (equal (org-entry-get nil property) value)
15742 (org-entry-put nil property value))))
15744 (defun org-delete-property (property &optional delete-empty-drawer)
15745 "In the current entry, delete PROPERTY.
15746 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15747 an empty drawer to delete."
15748 (interactive
15749 (let* ((completion-ignore-case t)
15750 (prop (org-icompleting-read "Property: "
15751 (org-entry-properties nil 'standard))))
15752 (list prop)))
15753 (message "Property %s %s" property
15754 (if (org-entry-delete nil property delete-empty-drawer)
15755 "deleted"
15756 "was not present in the entry")))
15758 (defun org-delete-property-globally (property)
15759 "Remove PROPERTY globally, from all entries."
15760 (interactive
15761 (let* ((completion-ignore-case t)
15762 (prop (org-icompleting-read
15763 "Globally remove property: "
15764 (mapcar 'list (org-buffer-property-keys)))))
15765 (list prop)))
15766 (save-excursion
15767 (save-restriction
15768 (widen)
15769 (goto-char (point-min))
15770 (let ((cnt 0))
15771 (while (re-search-forward
15772 (org-re-property property)
15773 nil t)
15774 (setq cnt (1+ cnt))
15775 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15776 (message "Property \"%s\" removed from %d entries" property cnt)))))
15778 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15780 (defun org-compute-property-at-point ()
15781 "Compute the property at point.
15782 This looks for an enclosing column format, extracts the operator and
15783 then applies it to the property in the column format's scope."
15784 (interactive)
15785 (unless (org-at-property-p)
15786 (user-error "Not at a property"))
15787 (let ((prop (org-match-string-no-properties 2)))
15788 (org-columns-get-format-and-top-level)
15789 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15790 (user-error "No operator defined for property %s" prop))
15791 (org-columns-compute prop)))
15793 (defvar org-property-allowed-value-functions nil
15794 "Hook for functions supplying allowed values for a specific property.
15795 The functions must take a single argument, the name of the property, and
15796 return a flat list of allowed values. If \":ETC\" is one of
15797 the values, this means that these values are intended as defaults for
15798 completion, but that other values should be allowed too.
15799 The functions must return nil if they are not responsible for this
15800 property.")
15802 (defun org-property-get-allowed-values (pom property &optional table)
15803 "Get allowed values for the property PROPERTY.
15804 When TABLE is non-nil, return an alist that can directly be used for
15805 completion."
15806 (let (vals)
15807 (cond
15808 ((equal property "TODO")
15809 (setq vals (org-with-point-at pom
15810 (append org-todo-keywords-1 '("")))))
15811 ((equal property "PRIORITY")
15812 (let ((n org-lowest-priority))
15813 (while (>= n org-highest-priority)
15814 (push (char-to-string n) vals)
15815 (setq n (1- n)))))
15816 ((member property org-special-properties))
15817 ((setq vals (run-hook-with-args-until-success
15818 'org-property-allowed-value-functions property)))
15820 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15821 (when (and vals (string-match "\\S-" vals))
15822 (setq vals (car (read-from-string (concat "(" vals ")"))))
15823 (setq vals (mapcar (lambda (x)
15824 (cond ((stringp x) x)
15825 ((numberp x) (number-to-string x))
15826 ((symbolp x) (symbol-name x))
15827 (t "???")))
15828 vals)))))
15829 (when (member ":ETC" vals)
15830 (setq vals (remove ":ETC" vals))
15831 (org-add-props (car vals) '(org-unrestricted t)))
15832 (if table (mapcar 'list vals) vals)))
15834 (defun org-property-previous-allowed-value (&optional previous)
15835 "Switch to the next allowed value for this property."
15836 (interactive)
15837 (org-property-next-allowed-value t))
15839 (defun org-property-next-allowed-value (&optional previous)
15840 "Switch to the next allowed value for this property."
15841 (interactive)
15842 (unless (org-at-property-p)
15843 (user-error "Not at a property"))
15844 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15845 (key (match-string 2))
15846 (value (match-string 3))
15847 (allowed (or (org-property-get-allowed-values (point) key)
15848 (and (member value '("[ ]" "[-]" "[X]"))
15849 '("[ ]" "[X]"))))
15850 (heading (save-match-data (nth 4 (org-heading-components))))
15851 nval)
15852 (unless allowed
15853 (user-error "Allowed values for this property have not been defined"))
15854 (if previous (setq allowed (reverse allowed)))
15855 (if (member value allowed)
15856 (setq nval (car (cdr (member value allowed)))))
15857 (setq nval (or nval (car allowed)))
15858 (if (equal nval value)
15859 (user-error "Only one allowed value for this property"))
15860 (org-at-property-p)
15861 (replace-match (concat " :" key ": " nval) t t)
15862 (org-indent-line)
15863 (beginning-of-line 1)
15864 (skip-chars-forward " \t")
15865 (when (equal prop org-effort-property)
15866 (save-excursion
15867 (org-back-to-heading t)
15868 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15869 (when (string= org-clock-current-task heading)
15870 (setq org-clock-effort nval)
15871 (org-clock-update-mode-line)))
15872 (run-hook-with-args 'org-property-changed-functions key nval)))
15874 (defun org-find-olp (path &optional this-buffer)
15875 "Return a marker pointing to the entry at outline path OLP.
15876 If anything goes wrong, throw an error.
15877 You can wrap this call to catch the error like this:
15879 (condition-case msg
15880 (org-mobile-locate-entry (match-string 4))
15881 (error (nth 1 msg)))
15883 The return value will then be either a string with the error message,
15884 or a marker if everything is OK.
15886 If THIS-BUFFER is set, the outline path does not contain a file,
15887 only headings."
15888 (let* ((file (if this-buffer buffer-file-name (pop path)))
15889 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15890 (level 1)
15891 (lmin 1)
15892 (lmax 1)
15893 limit re end found pos heading cnt flevel)
15894 (unless buffer (error "File not found :%s" file))
15895 (with-current-buffer buffer
15896 (save-excursion
15897 (save-restriction
15898 (widen)
15899 (setq limit (point-max))
15900 (goto-char (point-min))
15901 (while (setq heading (pop path))
15902 (setq re (format org-complex-heading-regexp-format
15903 (regexp-quote heading)))
15904 (setq cnt 0 pos (point))
15905 (while (re-search-forward re end t)
15906 (setq level (- (match-end 1) (match-beginning 1)))
15907 (if (and (>= level lmin) (<= level lmax))
15908 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15909 (when (= cnt 0) (error "Heading not found on level %d: %s"
15910 lmax heading))
15911 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15912 lmax heading))
15913 (goto-char found)
15914 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15915 (setq end (save-excursion (org-end-of-subtree t t))))
15916 (when (org-at-heading-p)
15917 (point-marker)))))))
15919 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15920 "Find node HEADING in BUFFER.
15921 Return a marker to the heading if it was found, or nil if not.
15922 If POS-ONLY is set, return just the position instead of a marker.
15924 The heading text must match exact, but it may have a TODO keyword,
15925 a priority cookie and tags in the standard locations."
15926 (with-current-buffer (or buffer (current-buffer))
15927 (save-excursion
15928 (save-restriction
15929 (widen)
15930 (goto-char (point-min))
15931 (let (case-fold-search)
15932 (if (re-search-forward
15933 (format org-complex-heading-regexp-format
15934 (regexp-quote heading)) nil t)
15935 (if pos-only
15936 (match-beginning 0)
15937 (move-marker (make-marker) (match-beginning 0)))))))))
15939 (defun org-find-exact-heading-in-directory (heading &optional dir)
15940 "Find Org node headline HEADING in all .org files in directory DIR.
15941 When the target headline is found, return a marker to this location."
15942 (let ((files (directory-files (or dir default-directory)
15943 nil "\\`[^.#].*\\.org\\'"))
15944 file visiting m buffer)
15945 (catch 'found
15946 (while (setq file (pop files))
15947 (message "trying %s" file)
15948 (setq visiting (org-find-base-buffer-visiting file))
15949 (setq buffer (or visiting (find-file-noselect file)))
15950 (setq m (org-find-exact-headline-in-buffer
15951 heading buffer))
15952 (when (and (not m) (not visiting)) (kill-buffer buffer))
15953 (and m (throw 'found m))))))
15955 (defun org-find-entry-with-id (ident)
15956 "Locate the entry that contains the ID property with exact value IDENT.
15957 IDENT can be a string, a symbol or a number, this function will search for
15958 the string representation of it.
15959 Return the position where this entry starts, or nil if there is no such entry."
15960 (interactive "sID: ")
15961 (let ((id (cond
15962 ((stringp ident) ident)
15963 ((symbol-name ident) (symbol-name ident))
15964 ((numberp ident) (number-to-string ident))
15965 (t (error "IDENT %s must be a string, symbol or number" ident))))
15966 (case-fold-search nil))
15967 (save-excursion
15968 (save-restriction
15969 (widen)
15970 (goto-char (point-min))
15971 (when (re-search-forward
15972 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15973 nil t)
15974 (org-back-to-heading t)
15975 (point))))))
15977 ;;;; Timestamps
15979 (defvar org-last-changed-timestamp nil)
15980 (defvar org-last-inserted-timestamp nil
15981 "The last time stamp inserted with `org-insert-time-stamp'.")
15982 (defvar org-time-was-given) ; dynamically scoped parameter
15983 (defvar org-end-time-was-given) ; dynamically scoped parameter
15984 (defvar org-ts-what) ; dynamically scoped parameter
15986 (defun org-time-stamp (arg &optional inactive)
15987 "Prompt for a date/time and insert a time stamp.
15988 If the user specifies a time like HH:MM or if this command is
15989 called with at least one prefix argument, the time stamp contains
15990 the date and the time. Otherwise, only the date is be included.
15992 All parts of a date not specified by the user is filled in from
15993 the current date/time. So if you just press return without
15994 typing anything, the time stamp will represent the current
15995 date/time.
15997 If there is already a timestamp at the cursor, it will be
15998 modified.
16000 With two universal prefix arguments, insert an active timestamp
16001 with the current time without prompting the user."
16002 (interactive "P")
16003 (let* ((ts nil)
16004 (default-time
16005 ;; Default time is either today, or, when entering a range,
16006 ;; the range start.
16007 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16008 (save-excursion
16009 (re-search-backward
16010 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16011 (- (point) 20) t)))
16012 (apply 'encode-time (org-parse-time-string (match-string 1)))
16013 (current-time)))
16014 (default-input (and ts (org-get-compact-tod ts)))
16015 (repeater (save-excursion
16016 (save-match-data
16017 (beginning-of-line)
16018 (when (re-search-forward
16019 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16020 (save-excursion (progn (end-of-line) (point))) t)
16021 (match-string 0)))))
16022 org-time-was-given org-end-time-was-given time)
16023 (cond
16024 ((and (org-at-timestamp-p t)
16025 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16026 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16027 (insert "--")
16028 (setq time (let ((this-command this-command))
16029 (org-read-date arg 'totime nil nil
16030 default-time default-input inactive)))
16031 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16032 ((org-at-timestamp-p t)
16033 (setq time (let ((this-command this-command))
16034 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16035 (when (org-at-timestamp-p t) ; just to get the match data
16036 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16037 (replace-match "")
16038 (setq org-last-changed-timestamp
16039 (org-insert-time-stamp
16040 time (or org-time-was-given arg)
16041 inactive nil nil (list org-end-time-was-given)))
16042 (when repeater (goto-char (1- (point))) (insert " " repeater)
16043 (setq org-last-changed-timestamp
16044 (concat (substring org-last-inserted-timestamp 0 -1)
16045 " " repeater ">"))))
16046 (message "Timestamp updated"))
16047 ((equal arg '(16))
16048 (org-insert-time-stamp (current-time) t))
16050 (setq time (let ((this-command this-command))
16051 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16052 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16053 nil nil (list org-end-time-was-given))))))
16055 ;; FIXME: can we use this for something else, like computing time differences?
16056 (defun org-get-compact-tod (s)
16057 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16058 (let* ((t1 (match-string 1 s))
16059 (h1 (string-to-number (match-string 2 s)))
16060 (m1 (string-to-number (match-string 3 s)))
16061 (t2 (and (match-end 4) (match-string 5 s)))
16062 (h2 (and t2 (string-to-number (match-string 6 s))))
16063 (m2 (and t2 (string-to-number (match-string 7 s))))
16064 dh dm)
16065 (if (not t2)
16067 (setq dh (- h2 h1) dm (- m2 m1))
16068 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16069 (concat t1 "+" (number-to-string dh)
16070 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16072 (defun org-time-stamp-inactive (&optional arg)
16073 "Insert an inactive time stamp.
16074 An inactive time stamp is enclosed in square brackets instead of angle
16075 brackets. It is inactive in the sense that it does not trigger agenda entries,
16076 does not link to the calendar and cannot be changed with the S-cursor keys.
16077 So these are more for recording a certain time/date."
16078 (interactive "P")
16079 (org-time-stamp arg 'inactive))
16081 (defvar org-date-ovl (make-overlay 1 1))
16082 (overlay-put org-date-ovl 'face 'org-date-selected)
16083 (org-detach-overlay org-date-ovl)
16085 (defvar org-ans1) ; dynamically scoped parameter
16086 (defvar org-ans2) ; dynamically scoped parameter
16088 (defvar org-plain-time-of-day-regexp) ; defined below
16090 (defvar org-overriding-default-time nil) ; dynamically scoped
16091 (defvar org-read-date-overlay nil)
16092 (defvar org-dcst nil) ; dynamically scoped
16093 (defvar org-read-date-history nil)
16094 (defvar org-read-date-final-answer nil)
16095 (defvar org-read-date-analyze-futurep nil)
16096 (defvar org-read-date-analyze-forced-year nil)
16097 (defvar org-read-date-inactive)
16099 (defvar org-read-date-minibuffer-local-map
16100 (let ((map (make-sparse-keymap)))
16101 (set-keymap-parent map minibuffer-local-map)
16102 (org-defkey map (kbd ".")
16103 (lambda () (interactive)
16104 ;; Are we at the beginning of the prompt?
16105 (if (looking-back "^[^:]+: ")
16106 (org-eval-in-calendar '(calendar-goto-today))
16107 (insert "."))))
16108 (org-defkey map (kbd "C-.")
16109 (lambda () (interactive)
16110 (org-eval-in-calendar '(calendar-goto-today))))
16111 (org-defkey map [(meta shift left)]
16112 (lambda () (interactive)
16113 (org-eval-in-calendar '(calendar-backward-month 1))))
16114 (org-defkey map [(meta shift right)]
16115 (lambda () (interactive)
16116 (org-eval-in-calendar '(calendar-forward-month 1))))
16117 (org-defkey map [(meta shift up)]
16118 (lambda () (interactive)
16119 (org-eval-in-calendar '(calendar-backward-year 1))))
16120 (org-defkey map [(meta shift down)]
16121 (lambda () (interactive)
16122 (org-eval-in-calendar '(calendar-forward-year 1))))
16123 (org-defkey map [?\e (shift left)]
16124 (lambda () (interactive)
16125 (org-eval-in-calendar '(calendar-backward-month 1))))
16126 (org-defkey map [?\e (shift right)]
16127 (lambda () (interactive)
16128 (org-eval-in-calendar '(calendar-forward-month 1))))
16129 (org-defkey map [?\e (shift up)]
16130 (lambda () (interactive)
16131 (org-eval-in-calendar '(calendar-backward-year 1))))
16132 (org-defkey map [?\e (shift down)]
16133 (lambda () (interactive)
16134 (org-eval-in-calendar '(calendar-forward-year 1))))
16135 (org-defkey map [(shift up)]
16136 (lambda () (interactive)
16137 (org-eval-in-calendar '(calendar-backward-week 1))))
16138 (org-defkey map [(shift down)]
16139 (lambda () (interactive)
16140 (org-eval-in-calendar '(calendar-forward-week 1))))
16141 (org-defkey map [(shift left)]
16142 (lambda () (interactive)
16143 (org-eval-in-calendar '(calendar-backward-day 1))))
16144 (org-defkey map [(shift right)]
16145 (lambda () (interactive)
16146 (org-eval-in-calendar '(calendar-forward-day 1))))
16147 (org-defkey map "!"
16148 (lambda () (interactive)
16149 (org-eval-in-calendar '(diary-view-entries))
16150 (message "")))
16151 (org-defkey map ">"
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(scroll-calendar-left 1))))
16154 (org-defkey map "<"
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(scroll-calendar-right 1))))
16157 (org-defkey map "\C-v"
16158 (lambda () (interactive)
16159 (org-eval-in-calendar
16160 '(calendar-scroll-left-three-months 1))))
16161 (org-defkey map "\M-v"
16162 (lambda () (interactive)
16163 (org-eval-in-calendar
16164 '(calendar-scroll-right-three-months 1))))
16165 map)
16166 "Keymap for minibuffer commands when using `org-read-date'.")
16168 (defun org-read-date (&optional org-with-time to-time from-string prompt
16169 default-time default-input inactive)
16170 "Read a date, possibly a time, and make things smooth for the user.
16171 The prompt will suggest to enter an ISO date, but you can also enter anything
16172 which will at least partially be understood by `parse-time-string'.
16173 Unrecognized parts of the date will default to the current day, month, year,
16174 hour and minute. If this command is called to replace a timestamp at point,
16175 or to enter the second timestamp of a range, the default time is taken
16176 from the existing stamp. Furthermore, the command prefers the future,
16177 so if you are giving a date where the year is not given, and the day-month
16178 combination is already past in the current year, it will assume you
16179 mean next year. For details, see the manual. A few examples:
16181 3-2-5 --> 2003-02-05
16182 feb 15 --> currentyear-02-15
16183 2/15 --> currentyear-02-15
16184 sep 12 9 --> 2009-09-12
16185 12:45 --> today 12:45
16186 22 sept 0:34 --> currentyear-09-22 0:34
16187 12 --> currentyear-currentmonth-12
16188 Fri --> nearest Friday after today
16189 -Tue --> last Tuesday
16190 etc.
16192 Furthermore you can specify a relative date by giving, as the *first* thing
16193 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16194 change in days weeks, months, years.
16195 With a single plus or minus, the date is relative to today. With a double
16196 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16197 +4d --> four days from today
16198 +4 --> same as above
16199 +2w --> two weeks from today
16200 ++5 --> five days from default date
16202 The function understands only English month and weekday abbreviations.
16204 While prompting, a calendar is popped up - you can also select the
16205 date with the mouse (button 1). The calendar shows a period of three
16206 months. To scroll it to other months, use the keys `>' and `<'.
16207 If you don't like the calendar, turn it off with
16208 \(setq org-read-date-popup-calendar nil)
16210 With optional argument TO-TIME, the date will immediately be converted
16211 to an internal time.
16212 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16213 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16214 still enter a time, and this function will inform the calling routine
16215 about this change. The calling routine may then choose to change the
16216 format used to insert the time stamp into the buffer to include the time.
16217 With optional argument FROM-STRING, read from this string instead from
16218 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16219 the time/date that is used for everything that is not specified by the
16220 user."
16221 (require 'parse-time)
16222 (let* ((org-time-stamp-rounding-minutes
16223 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16224 (org-dcst org-display-custom-times)
16225 (ct (org-current-time))
16226 (org-def (or org-overriding-default-time default-time ct))
16227 (org-defdecode (decode-time org-def))
16228 (dummy (progn
16229 (when (< (nth 2 org-defdecode) org-extend-today-until)
16230 (setcar (nthcdr 2 org-defdecode) -1)
16231 (setcar (nthcdr 1 org-defdecode) 59)
16232 (setq org-def (apply 'encode-time org-defdecode)
16233 org-defdecode (decode-time org-def)))))
16234 (mouse-autoselect-window nil) ; Don't let the mouse jump
16235 (calendar-frame-setup nil)
16236 (calendar-setup nil)
16237 (calendar-move-hook nil)
16238 (calendar-view-diary-initially-flag nil)
16239 (calendar-view-holidays-initially-flag nil)
16240 (timestr (format-time-string
16241 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16242 (prompt (concat (if prompt (concat prompt " ") "")
16243 (format "Date+time [%s]: " timestr)))
16244 ans (org-ans0 "") org-ans1 org-ans2 final)
16246 (cond
16247 (from-string (setq ans from-string))
16248 (org-read-date-popup-calendar
16249 (save-excursion
16250 (save-window-excursion
16251 (calendar)
16252 (org-eval-in-calendar '(setq cursor-type nil) t)
16253 (unwind-protect
16254 (progn
16255 (calendar-forward-day (- (time-to-days org-def)
16256 (calendar-absolute-from-gregorian
16257 (calendar-current-date))))
16258 (org-eval-in-calendar nil t)
16259 (let* ((old-map (current-local-map))
16260 (map (copy-keymap calendar-mode-map))
16261 (minibuffer-local-map
16262 (copy-keymap org-read-date-minibuffer-local-map)))
16263 (org-defkey map (kbd "RET") 'org-calendar-select)
16264 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16265 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16266 (unwind-protect
16267 (progn
16268 (use-local-map map)
16269 (setq org-read-date-inactive inactive)
16270 (add-hook 'post-command-hook 'org-read-date-display)
16271 (setq org-ans0 (read-string prompt default-input
16272 'org-read-date-history nil))
16273 ;; org-ans0: from prompt
16274 ;; org-ans1: from mouse click
16275 ;; org-ans2: from calendar motion
16276 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16277 (remove-hook 'post-command-hook 'org-read-date-display)
16278 (use-local-map old-map)
16279 (when org-read-date-overlay
16280 (delete-overlay org-read-date-overlay)
16281 (setq org-read-date-overlay nil)))))
16282 (bury-buffer "*Calendar*")))))
16284 (t ; Naked prompt only
16285 (unwind-protect
16286 (setq ans (read-string prompt default-input
16287 'org-read-date-history timestr))
16288 (when org-read-date-overlay
16289 (delete-overlay org-read-date-overlay)
16290 (setq org-read-date-overlay nil)))))
16292 (setq final (org-read-date-analyze ans org-def org-defdecode))
16294 (when org-read-date-analyze-forced-year
16295 (message "Year was forced into %s"
16296 (if org-read-date-force-compatible-dates
16297 "compatible range (1970-2037)"
16298 "range representable on this machine"))
16299 (ding))
16301 ;; One round trip to get rid of 34th of August and stuff like that....
16302 (setq final (decode-time (apply 'encode-time final)))
16304 (setq org-read-date-final-answer ans)
16306 (if to-time
16307 (apply 'encode-time final)
16308 (if (and (boundp 'org-time-was-given) org-time-was-given)
16309 (format "%04d-%02d-%02d %02d:%02d"
16310 (nth 5 final) (nth 4 final) (nth 3 final)
16311 (nth 2 final) (nth 1 final))
16312 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16314 (defvar org-def)
16315 (defvar org-defdecode)
16316 (defvar org-with-time)
16317 (defun org-read-date-display ()
16318 "Display the current date prompt interpretation in the minibuffer."
16319 (when org-read-date-display-live
16320 (when org-read-date-overlay
16321 (delete-overlay org-read-date-overlay))
16322 (when (minibufferp (current-buffer))
16323 (save-excursion
16324 (end-of-line 1)
16325 (while (not (equal (buffer-substring
16326 (max (point-min) (- (point) 4)) (point))
16327 " "))
16328 (insert " ")))
16329 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16330 " " (or org-ans1 org-ans2)))
16331 (org-end-time-was-given nil)
16332 (f (org-read-date-analyze ans org-def org-defdecode))
16333 (fmts (if org-dcst
16334 org-time-stamp-custom-formats
16335 org-time-stamp-formats))
16336 (fmt (if (or org-with-time
16337 (and (boundp 'org-time-was-given) org-time-was-given))
16338 (cdr fmts)
16339 (car fmts)))
16340 (txt (format-time-string fmt (apply 'encode-time f)))
16341 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16342 (txt (concat "=> " txt)))
16343 (when (and org-end-time-was-given
16344 (string-match org-plain-time-of-day-regexp txt))
16345 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16346 org-end-time-was-given
16347 (substring txt (match-end 0)))))
16348 (when org-read-date-analyze-futurep
16349 (setq txt (concat txt " (=>F)")))
16350 (setq org-read-date-overlay
16351 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16352 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16354 (defun org-read-date-analyze (ans org-def org-defdecode)
16355 "Analyze the combined answer of the date prompt."
16356 ;; FIXME: cleanup and comment
16357 (let ((nowdecode (decode-time (current-time)))
16358 delta deltan deltaw deltadef year month day
16359 hour minute second wday pm h2 m2 tl wday1
16360 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16361 (setq org-read-date-analyze-futurep nil
16362 org-read-date-analyze-forced-year nil)
16363 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16364 (setq ans "+0"))
16366 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16367 (setq ans (replace-match "" t t ans)
16368 deltan (car delta)
16369 deltaw (nth 1 delta)
16370 deltadef (nth 2 delta)))
16372 ;; Check if there is an iso week date in there. If yes, store the
16373 ;; info and postpone interpreting it until the rest of the parsing
16374 ;; is done.
16375 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16376 (setq iso-year (if (match-end 1)
16377 (org-small-year-to-year
16378 (string-to-number (match-string 1 ans))))
16379 iso-weekday (if (match-end 3)
16380 (string-to-number (match-string 3 ans)))
16381 iso-week (string-to-number (match-string 2 ans)))
16382 (setq ans (replace-match "" t t ans)))
16384 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16385 (when (string-match
16386 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16387 (setq year (if (match-end 2)
16388 (string-to-number (match-string 2 ans))
16389 (progn (setq kill-year t)
16390 (string-to-number (format-time-string "%Y"))))
16391 month (string-to-number (match-string 3 ans))
16392 day (string-to-number (match-string 4 ans)))
16393 (if (< year 100) (setq year (+ 2000 year)))
16394 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16395 t nil ans)))
16397 ;; Help matching dotted european dates
16398 (when (string-match
16399 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16400 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16401 (setq kill-year t)
16402 (string-to-number (format-time-string "%Y")))
16403 day (string-to-number (match-string 1 ans))
16404 month (string-to-number (match-string 2 ans))
16405 ans (replace-match (format "%04d-%02d-%02d" year month day)
16406 t nil ans)))
16408 ;; Help matching american dates, like 5/30 or 5/30/7
16409 (when (string-match
16410 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16411 (setq year (if (match-end 4)
16412 (string-to-number (match-string 4 ans))
16413 (progn (setq kill-year t)
16414 (string-to-number (format-time-string "%Y"))))
16415 month (string-to-number (match-string 1 ans))
16416 day (string-to-number (match-string 2 ans)))
16417 (if (< year 100) (setq year (+ 2000 year)))
16418 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16419 t nil ans)))
16420 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16421 ;; If there is a time with am/pm, and *no* time without it, we convert
16422 ;; so that matching will be successful.
16423 (loop for i from 1 to 2 do ; twice, for end time as well
16424 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16425 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16426 (setq hour (string-to-number (match-string 1 ans))
16427 minute (if (match-end 3)
16428 (string-to-number (match-string 3 ans))
16430 pm (equal ?p
16431 (string-to-char (downcase (match-string 4 ans)))))
16432 (if (and (= hour 12) (not pm))
16433 (setq hour 0)
16434 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16435 (setq ans (replace-match (format "%02d:%02d" hour minute)
16436 t t ans))))
16438 ;; Check if a time range is given as a duration
16439 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16440 (setq hour (string-to-number (match-string 1 ans))
16441 h2 (+ hour (string-to-number (match-string 3 ans)))
16442 minute (string-to-number (match-string 2 ans))
16443 m2 (+ minute (if (match-end 5) (string-to-number
16444 (match-string 5 ans))0)))
16445 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16446 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16447 t t ans)))
16449 ;; Check if there is a time range
16450 (when (boundp 'org-end-time-was-given)
16451 (setq org-time-was-given nil)
16452 (when (and (string-match org-plain-time-of-day-regexp ans)
16453 (match-end 8))
16454 (setq org-end-time-was-given (match-string 8 ans))
16455 (setq ans (concat (substring ans 0 (match-beginning 7))
16456 (substring ans (match-end 7))))))
16458 (setq tl (parse-time-string ans)
16459 day (or (nth 3 tl) (nth 3 org-defdecode))
16460 month (or (nth 4 tl)
16461 (if (and org-read-date-prefer-future
16462 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16463 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16464 (nth 4 org-defdecode)))
16465 year (or (and (not kill-year) (nth 5 tl))
16466 (if (and org-read-date-prefer-future
16467 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16468 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16469 (nth 5 org-defdecode)))
16470 hour (or (nth 2 tl) (nth 2 org-defdecode))
16471 minute (or (nth 1 tl) (nth 1 org-defdecode))
16472 second (or (nth 0 tl) 0)
16473 wday (nth 6 tl))
16475 (when (and (eq org-read-date-prefer-future 'time)
16476 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16477 (equal day (nth 3 nowdecode))
16478 (equal month (nth 4 nowdecode))
16479 (equal year (nth 5 nowdecode))
16480 (nth 2 tl)
16481 (or (< (nth 2 tl) (nth 2 nowdecode))
16482 (and (= (nth 2 tl) (nth 2 nowdecode))
16483 (nth 1 tl)
16484 (< (nth 1 tl) (nth 1 nowdecode)))))
16485 (setq day (1+ day)
16486 futurep t))
16488 ;; Special date definitions below
16489 (cond
16490 (iso-week
16491 ;; There was an iso week
16492 (require 'cal-iso)
16493 (setq futurep nil)
16494 (setq year (or iso-year year)
16495 day (or iso-weekday wday 1)
16496 wday nil ; to make sure that the trigger below does not match
16497 iso-date (calendar-gregorian-from-absolute
16498 (calendar-absolute-from-iso
16499 (list iso-week day year))))
16500 ; FIXME: Should we also push ISO weeks into the future?
16501 ; (when (and org-read-date-prefer-future
16502 ; (not iso-year)
16503 ; (< (calendar-absolute-from-gregorian iso-date)
16504 ; (time-to-days (current-time))))
16505 ; (setq year (1+ year)
16506 ; iso-date (calendar-gregorian-from-absolute
16507 ; (calendar-absolute-from-iso
16508 ; (list iso-week day year)))))
16509 (setq month (car iso-date)
16510 year (nth 2 iso-date)
16511 day (nth 1 iso-date)))
16512 (deltan
16513 (setq futurep nil)
16514 (unless deltadef
16515 (let ((now (decode-time (current-time))))
16516 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16517 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16518 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16519 ((equal deltaw "m") (setq month (+ month deltan)))
16520 ((equal deltaw "y") (setq year (+ year deltan)))))
16521 ((and wday (not (nth 3 tl)))
16522 ;; Weekday was given, but no day, so pick that day in the week
16523 ;; on or after the derived date.
16524 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16525 (unless (equal wday wday1)
16526 (setq day (+ day (% (- wday wday1 -7) 7))))))
16527 (if (and (boundp 'org-time-was-given)
16528 (nth 2 tl))
16529 (setq org-time-was-given t))
16530 (if (< year 100) (setq year (+ 2000 year)))
16531 ;; Check of the date is representable
16532 (if org-read-date-force-compatible-dates
16533 (progn
16534 (if (< year 1970)
16535 (setq year 1970 org-read-date-analyze-forced-year t))
16536 (if (> year 2037)
16537 (setq year 2037 org-read-date-analyze-forced-year t)))
16538 (condition-case nil
16539 (ignore (encode-time second minute hour day month year))
16540 (error
16541 (setq year (nth 5 org-defdecode))
16542 (setq org-read-date-analyze-forced-year t))))
16543 (setq org-read-date-analyze-futurep futurep)
16544 (list second minute hour day month year)))
16546 (defvar parse-time-weekdays)
16547 (defun org-read-date-get-relative (s today default)
16548 "Check string S for special relative date string.
16549 TODAY and DEFAULT are internal times, for today and for a default.
16550 Return shift list (N what def-flag)
16551 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16552 N is the number of WHATs to shift.
16553 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16554 the DEFAULT date rather than TODAY."
16555 (require 'parse-time)
16556 (when (and
16557 (string-match
16558 (concat
16559 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16560 "\\([0-9]+\\)?"
16561 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16562 "\\([ \t]\\|$\\)") s)
16563 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16564 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16565 (string-to-char (substring (match-string 1 s) -1))
16566 ?+))
16567 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16568 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16569 (what (if (match-end 3) (match-string 3 s) "d"))
16570 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16571 (date (if rel default today))
16572 (wday (nth 6 (decode-time date)))
16573 delta)
16574 (if wday1
16575 (progn
16576 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16577 (if (= delta 0) (setq delta 7))
16578 (if (= dir ?-)
16579 (progn
16580 (setq delta (- delta 7))
16581 (if (= delta 0) (setq delta -7))))
16582 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16583 (list delta "d" rel))
16584 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16586 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16587 "Turn a user-specified date into the internal representation.
16588 The internal representation needed by the calendar is (month day year).
16589 This is a wrapper to handle the brain-dead convention in calendar that
16590 user function argument order change dependent on argument order."
16591 (if (boundp 'calendar-date-style)
16592 (cond
16593 ((eq calendar-date-style 'american)
16594 (list arg1 arg2 arg3))
16595 ((eq calendar-date-style 'european)
16596 (list arg2 arg1 arg3))
16597 ((eq calendar-date-style 'iso)
16598 (list arg2 arg3 arg1)))
16599 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16600 (if (org-bound-and-true-p european-calendar-style)
16601 (list arg2 arg1 arg3)
16602 (list arg1 arg2 arg3)))))
16604 (defun org-eval-in-calendar (form &optional keepdate)
16605 "Eval FORM in the calendar window and return to current window.
16606 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16607 otherwise stick to the current value of `org-ans2'."
16608 (let ((sf (selected-frame))
16609 (sw (selected-window)))
16610 (select-window (get-buffer-window "*Calendar*" t))
16611 (eval form)
16612 (when (and (not keepdate) (calendar-cursor-to-date))
16613 (let* ((date (calendar-cursor-to-date))
16614 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16615 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16616 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16617 (select-window sw)
16618 (org-select-frame-set-input-focus sf)))
16620 (defun org-calendar-select ()
16621 "Return to `org-read-date' with the date currently selected.
16622 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16623 (interactive)
16624 (when (calendar-cursor-to-date)
16625 (let* ((date (calendar-cursor-to-date))
16626 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16627 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16628 (if (active-minibuffer-window) (exit-minibuffer))))
16630 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16631 "Insert a date stamp for the date given by the internal TIME.
16632 WITH-HM means use the stamp format that includes the time of the day.
16633 INACTIVE means use square brackets instead of angular ones, so that the
16634 stamp will not contribute to the agenda.
16635 PRE and POST are optional strings to be inserted before and after the
16636 stamp.
16637 The command returns the inserted time stamp."
16638 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16639 stamp)
16640 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16641 (insert-before-markers (or pre ""))
16642 (when (listp extra)
16643 (setq extra (car extra))
16644 (if (and (stringp extra)
16645 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16646 (setq extra (format "-%02d:%02d"
16647 (string-to-number (match-string 1 extra))
16648 (string-to-number (match-string 2 extra))))
16649 (setq extra nil)))
16650 (when extra
16651 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16652 (insert-before-markers (setq stamp (format-time-string fmt time)))
16653 (insert-before-markers (or post ""))
16654 (setq org-last-inserted-timestamp stamp)))
16656 (defun org-toggle-time-stamp-overlays ()
16657 "Toggle the use of custom time stamp formats."
16658 (interactive)
16659 (setq org-display-custom-times (not org-display-custom-times))
16660 (unless org-display-custom-times
16661 (let ((p (point-min)) (bmp (buffer-modified-p)))
16662 (while (setq p (next-single-property-change p 'display))
16663 (if (and (get-text-property p 'display)
16664 (eq (get-text-property p 'face) 'org-date))
16665 (remove-text-properties
16666 p (setq p (next-single-property-change p 'display))
16667 '(display t))))
16668 (set-buffer-modified-p bmp)))
16669 (if (featurep 'xemacs)
16670 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16671 (org-restart-font-lock)
16672 (setq org-table-may-need-update t)
16673 (if org-display-custom-times
16674 (message "Time stamps are overlaid with custom format")
16675 (message "Time stamp overlays removed")))
16677 (defun org-display-custom-time (beg end)
16678 "Overlay modified time stamp format over timestamp between BEG and END."
16679 (let* ((ts (buffer-substring beg end))
16680 t1 w1 with-hm tf time str w2 (off 0))
16681 (save-match-data
16682 (setq t1 (org-parse-time-string ts t))
16683 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16684 (setq off (- (match-end 0) (match-beginning 0)))))
16685 (setq end (- end off))
16686 (setq w1 (- end beg)
16687 with-hm (and (nth 1 t1) (nth 2 t1))
16688 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16689 time (org-fix-decoded-time t1)
16690 str (org-add-props
16691 (format-time-string
16692 (substring tf 1 -1) (apply 'encode-time time))
16693 nil 'mouse-face 'highlight)
16694 w2 (length str))
16695 (if (not (= w2 w1))
16696 (add-text-properties (1+ beg) (+ 2 beg)
16697 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16698 (if (featurep 'xemacs)
16699 (progn
16700 (put-text-property beg end 'invisible t)
16701 (put-text-property beg end 'end-glyph (make-glyph str)))
16702 (put-text-property beg end 'display str))))
16704 (defun org-translate-time (string)
16705 "Translate all timestamps in STRING to custom format.
16706 But do this only if the variable `org-display-custom-times' is set."
16707 (when org-display-custom-times
16708 (save-match-data
16709 (let* ((start 0)
16710 (re org-ts-regexp-both)
16711 t1 with-hm inactive tf time str beg end)
16712 (while (setq start (string-match re string start))
16713 (setq beg (match-beginning 0)
16714 end (match-end 0)
16715 t1 (save-match-data
16716 (org-parse-time-string (substring string beg end) t))
16717 with-hm (and (nth 1 t1) (nth 2 t1))
16718 inactive (equal (substring string beg (1+ beg)) "[")
16719 tf (funcall (if with-hm 'cdr 'car)
16720 org-time-stamp-custom-formats)
16721 time (org-fix-decoded-time t1)
16722 str (format-time-string
16723 (concat
16724 (if inactive "[" "<") (substring tf 1 -1)
16725 (if inactive "]" ">"))
16726 (apply 'encode-time time))
16727 string (replace-match str t t string)
16728 start (+ start (length str)))))))
16729 string)
16731 (defun org-fix-decoded-time (time)
16732 "Set 0 instead of nil for the first 6 elements of time.
16733 Don't touch the rest."
16734 (let ((n 0))
16735 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16737 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16739 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16740 "Difference between TIMESTAMP-STRING and now in days.
16741 If SECONDS is non-nil, return the difference in seconds."
16742 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16743 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16744 (funcall fdiff (current-time)))))
16746 (defun org-deadline-close (timestamp-string &optional ndays)
16747 "Is the time in TIMESTAMP-STRING close to the current date?"
16748 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16749 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16750 (not (org-entry-is-done-p))))
16752 (defun org-get-wdays (ts &optional delay zero-delay)
16753 "Get the deadline lead time appropriate for timestring TS.
16754 When DELAY is non-nil, get the delay time for scheduled items
16755 instead of the deadline lead time. When ZERO-DELAY is non-nil
16756 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16757 don't try to find the delay cookie in the scheduled timestamp."
16758 (let ((tv (if delay org-scheduled-delay-days
16759 org-deadline-warning-days)))
16760 (cond
16761 ((or (and delay (< tv 0))
16762 (and delay zero-delay (<= tv 0))
16763 (and (not delay) (<= tv 0)))
16764 ;; Enforce this value no matter what
16765 (- tv))
16766 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16767 ;; lead time is specified.
16768 (floor (* (string-to-number (match-string 1 ts))
16769 (cdr (assoc (match-string 2 ts)
16770 '(("d" . 1) ("w" . 7)
16771 ("m" . 30.4) ("y" . 365.25)
16772 ("h" . 0.041667)))))))
16773 ;; go for the default.
16774 (t tv))))
16776 (defun org-calendar-select-mouse (ev)
16777 "Return to `org-read-date' with the date currently selected.
16778 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16779 (interactive "e")
16780 (mouse-set-point ev)
16781 (when (calendar-cursor-to-date)
16782 (let* ((date (calendar-cursor-to-date))
16783 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16784 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16785 (if (active-minibuffer-window) (exit-minibuffer))))
16787 (defun org-check-deadlines (ndays)
16788 "Check if there are any deadlines due or past due.
16789 A deadline is considered due if it happens within `org-deadline-warning-days'
16790 days from today's date. If the deadline appears in an entry marked DONE,
16791 it is not shown. The prefix arg NDAYS can be used to test that many
16792 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16793 (interactive "P")
16794 (let* ((org-warn-days
16795 (cond
16796 ((equal ndays '(4)) 100000)
16797 (ndays (prefix-numeric-value ndays))
16798 (t (abs org-deadline-warning-days))))
16799 (case-fold-search nil)
16800 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16801 (callback
16802 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16804 (message "%d deadlines past-due or due within %d days"
16805 (org-occur regexp nil callback)
16806 org-warn-days)))
16808 (defsubst org-re-timestamp (type)
16809 "Return a regexp for timestamp TYPE.
16810 Allowed values for TYPE are:
16812 all: all timestamps
16813 active: only active timestamps (<...>)
16814 inactive: only inactive timestamps ([...])
16815 scheduled: only scheduled timestamps
16816 deadline: only deadline timestamps
16817 closed: only closed time-stamps
16819 When TYPE is nil, fall back on returning a regexp that matches
16820 both scheduled and deadline timestamps."
16821 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16822 ((eq type 'active) org-ts-regexp)
16823 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16824 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16825 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16826 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16827 ((eq type 'scheduled-or-deadline)
16828 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16830 (defun org-check-before-date (date)
16831 "Check if there are deadlines or scheduled entries before DATE."
16832 (interactive (list (org-read-date)))
16833 (let ((case-fold-search nil)
16834 (regexp (org-re-timestamp org-ts-type))
16835 (callback
16836 (lambda () (time-less-p
16837 (org-time-string-to-time (match-string 1))
16838 (org-time-string-to-time date)))))
16839 (message "%d entries before %s"
16840 (org-occur regexp nil callback) date)))
16842 (defun org-check-after-date (date)
16843 "Check if there are deadlines or scheduled entries after DATE."
16844 (interactive (list (org-read-date)))
16845 (let ((case-fold-search nil)
16846 (regexp (org-re-timestamp org-ts-type))
16847 (callback
16848 (lambda () (not
16849 (time-less-p
16850 (org-time-string-to-time (match-string 1))
16851 (org-time-string-to-time date))))))
16852 (message "%d entries after %s"
16853 (org-occur regexp nil callback) date)))
16855 (defun org-check-dates-range (start-date end-date)
16856 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16857 (interactive (list (org-read-date nil nil nil "Range starts")
16858 (org-read-date nil nil nil "Range end")))
16859 (let ((case-fold-search nil)
16860 (regexp (org-re-timestamp org-ts-type))
16861 (callback
16862 (lambda ()
16863 (let ((match (match-string 1)))
16864 (and
16865 (not (time-less-p
16866 (org-time-string-to-time match)
16867 (org-time-string-to-time start-date)))
16868 (time-less-p
16869 (org-time-string-to-time match)
16870 (org-time-string-to-time end-date)))))))
16871 (message "%d entries between %s and %s"
16872 (org-occur regexp nil callback) start-date end-date)))
16874 (defun org-evaluate-time-range (&optional to-buffer)
16875 "Evaluate a time range by computing the difference between start and end.
16876 Normally the result is just printed in the echo area, but with prefix arg
16877 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16878 If the time range is actually in a table, the result is inserted into the
16879 next column.
16880 For time difference computation, a year is assumed to be exactly 365
16881 days in order to avoid rounding problems."
16882 (interactive "P")
16884 (org-clock-update-time-maybe)
16885 (save-excursion
16886 (unless (org-at-date-range-p t)
16887 (goto-char (point-at-bol))
16888 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16889 (if (not (org-at-date-range-p t))
16890 (user-error "Not at a time-stamp range, and none found in current line")))
16891 (let* ((ts1 (match-string 1))
16892 (ts2 (match-string 2))
16893 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16894 (match-end (match-end 0))
16895 (time1 (org-time-string-to-time ts1))
16896 (time2 (org-time-string-to-time ts2))
16897 (t1 (org-float-time time1))
16898 (t2 (org-float-time time2))
16899 (diff (abs (- t2 t1)))
16900 (negative (< (- t2 t1) 0))
16901 ;; (ys (floor (* 365 24 60 60)))
16902 (ds (* 24 60 60))
16903 (hs (* 60 60))
16904 (fy "%dy %dd %02d:%02d")
16905 (fy1 "%dy %dd")
16906 (fd "%dd %02d:%02d")
16907 (fd1 "%dd")
16908 (fh "%02d:%02d")
16909 y d h m align)
16910 (if havetime
16911 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16913 d (floor (/ diff ds)) diff (mod diff ds)
16914 h (floor (/ diff hs)) diff (mod diff hs)
16915 m (floor (/ diff 60)))
16916 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16918 d (floor (+ (/ diff ds) 0.5))
16919 h 0 m 0))
16920 (if (not to-buffer)
16921 (message "%s" (org-make-tdiff-string y d h m))
16922 (if (org-at-table-p)
16923 (progn
16924 (goto-char match-end)
16925 (setq align t)
16926 (and (looking-at " *|") (goto-char (match-end 0))))
16927 (goto-char match-end))
16928 (if (looking-at
16929 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16930 (replace-match ""))
16931 (if negative (insert " -"))
16932 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16933 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16934 (insert " " (format fh h m))))
16935 (if align (org-table-align))
16936 (message "Time difference inserted")))))
16938 (defun org-make-tdiff-string (y d h m)
16939 (let ((fmt "")
16940 (l nil))
16941 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16942 l (push y l)))
16943 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16944 l (push d l)))
16945 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16946 l (push h l)))
16947 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16948 l (push m l)))
16949 (apply 'format fmt (nreverse l))))
16951 (defun org-time-string-to-time (s &optional buffer pos)
16952 "Convert a timestamp string into internal time."
16953 (condition-case errdata
16954 (apply 'encode-time (org-parse-time-string s))
16955 (error (error "Bad timestamp `%s'%s\nError was: %s"
16956 s (if (not (and buffer pos))
16958 (format " at %d in buffer `%s'" pos buffer))
16959 (cdr errdata)))))
16961 (defun org-time-string-to-seconds (s)
16962 "Convert a timestamp string to a number of seconds."
16963 (org-float-time (org-time-string-to-time s)))
16965 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16966 "Convert a time stamp to an absolute day number.
16967 If there is a specifier for a cyclic time stamp, get the closest
16968 date to DAYNR.
16969 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16970 The variable `date' is bound by the calendar when this is called."
16971 (cond
16972 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16973 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16974 daynr
16975 (+ daynr 1000)))
16976 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16977 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16978 (time-to-days (current-time))) (match-string 0 s)
16979 prefer show-all))
16980 (t (time-to-days
16981 (condition-case errdata
16982 (apply 'encode-time (org-parse-time-string s))
16983 (error (error "Bad timestamp `%s'%s\nError was: %s"
16984 s (if (not (and buffer pos))
16986 (format " at %d in buffer `%s'" pos buffer))
16987 (cdr errdata))))))))
16989 (defun org-days-to-iso-week (days)
16990 "Return the iso week number."
16991 (require 'cal-iso)
16992 (car (calendar-iso-from-absolute days)))
16994 (defun org-small-year-to-year (year)
16995 "Convert 2-digit years into 4-digit years.
16996 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
16997 The year 2000 cannot be abbreviated. Any year larger than 99
16998 is returned unchanged."
16999 (if (< year 38)
17000 (setq year (+ 2000 year))
17001 (if (< year 100)
17002 (setq year (+ 1900 year))))
17003 year)
17005 (defun org-time-from-absolute (d)
17006 "Return the time corresponding to date D.
17007 D may be an absolute day number, or a calendar-type list (month day year)."
17008 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17009 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17011 (defun org-calendar-holiday ()
17012 "List of holidays, for Diary display in Org-mode."
17013 (require 'holidays)
17014 (let ((hl (funcall
17015 (if (fboundp 'calendar-check-holidays)
17016 'calendar-check-holidays 'check-calendar-holidays) date)))
17017 (if hl (mapconcat 'identity hl "; "))))
17019 (defun org-diary-sexp-entry (sexp entry date)
17020 "Process a SEXP diary ENTRY for DATE."
17021 (require 'diary-lib)
17022 (let ((result (if calendar-debug-sexp
17023 (let ((stack-trace-on-error t))
17024 (eval (car (read-from-string sexp))))
17025 (condition-case nil
17026 (eval (car (read-from-string sexp)))
17027 (error
17028 (beep)
17029 (message "Bad sexp at line %d in %s: %s"
17030 (org-current-line)
17031 (buffer-file-name) sexp)
17032 (sleep-for 2))))))
17033 (cond ((stringp result) (split-string result "; "))
17034 ((and (consp result)
17035 (not (consp (cdr result)))
17036 (stringp (cdr result))) (cdr result))
17037 ((and (consp result)
17038 (stringp (car result))) result)
17039 (result entry))))
17041 (defun org-diary-to-ical-string (frombuf)
17042 "Get iCalendar entries from diary entries in buffer FROMBUF.
17043 This uses the icalendar.el library."
17044 (let* ((tmpdir (if (featurep 'xemacs)
17045 (temp-directory)
17046 temporary-file-directory))
17047 (tmpfile (make-temp-name
17048 (expand-file-name "orgics" tmpdir)))
17049 buf rtn b e)
17050 (with-current-buffer frombuf
17051 (icalendar-export-region (point-min) (point-max) tmpfile)
17052 (setq buf (find-buffer-visiting tmpfile))
17053 (set-buffer buf)
17054 (goto-char (point-min))
17055 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17056 (setq b (match-beginning 0)))
17057 (goto-char (point-max))
17058 (if (re-search-backward "^END:VEVENT" nil t)
17059 (setq e (match-end 0)))
17060 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17061 (kill-buffer buf)
17062 (delete-file tmpfile)
17063 rtn))
17065 (defun org-closest-date (start current change prefer show-all)
17066 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17067 When PREFER is `past', return a date that is either CURRENT or past.
17068 When PREFER is `future', return a date that is either CURRENT or future.
17069 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17070 ;; Make the proper lists from the dates
17071 (catch 'exit
17072 (let ((a1 '(("h" . hour)
17073 ("d" . day)
17074 ("w" . week)
17075 ("m" . month)
17076 ("y" . year)))
17077 (shour (nth 2 (org-parse-time-string start)))
17078 dn dw sday cday n1 n2 n0
17079 d m y y1 y2 date1 date2 nmonths nm ny m2)
17081 (setq start (org-date-to-gregorian start)
17082 current (org-date-to-gregorian
17083 (if show-all
17084 current
17085 (time-to-days (current-time))))
17086 sday (calendar-absolute-from-gregorian start)
17087 cday (calendar-absolute-from-gregorian current))
17089 (if (<= cday sday) (throw 'exit sday))
17091 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17092 (setq dn (string-to-number (match-string 1 change))
17093 dw (cdr (assoc (match-string 2 change) a1)))
17094 (user-error "Invalid change specifier: %s" change))
17095 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17096 (cond
17097 ((eq dw 'hour)
17098 (let ((missing-hours
17099 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17100 dn)))
17101 (setq n1 (if (zerop missing-hours) cday
17102 (- cday (1+ (floor (/ missing-hours 24)))))
17103 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17104 ((eq dw 'day)
17105 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17106 n2 (+ n1 dn)))
17107 ((eq dw 'year)
17108 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17109 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17110 (setq date1 (list m d y1)
17111 n1 (calendar-absolute-from-gregorian date1)
17112 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17113 n2 (calendar-absolute-from-gregorian date2)))
17114 ((eq dw 'month)
17115 ;; approx number of month between the two dates
17116 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17117 ;; How often does dn fit in there?
17118 (setq d (nth 1 start) m (car start) y (nth 2 start)
17119 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17120 m (+ m nm)
17121 ny (floor (/ m 12))
17122 y (+ y ny)
17123 m (- m (* ny 12)))
17124 (while (> m 12) (setq m (- m 12) y (1+ y)))
17125 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17126 (setq m2 (+ m dn) y2 y)
17127 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17128 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17129 (while (<= n2 cday)
17130 (setq n1 n2 m m2 y y2)
17131 (setq m2 (+ m dn) y2 y)
17132 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17133 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17134 ;; Make sure n1 is the earlier date
17135 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17136 (if show-all
17137 (cond
17138 ((eq prefer 'past) (if (= cday n2) n2 n1))
17139 ((eq prefer 'future) (if (= cday n1) n1 n2))
17140 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17141 (cond
17142 ((eq prefer 'past) (if (= cday n2) n2 n1))
17143 ((eq prefer 'future) (if (= cday n1) n1 n2))
17144 (t (if (= cday n1) n1 n2)))))))
17146 (defun org-date-to-gregorian (date)
17147 "Turn any specification of DATE into a Gregorian date for the calendar."
17148 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17149 ((and (listp date) (= (length date) 3)) date)
17150 ((stringp date)
17151 (setq date (org-parse-time-string date))
17152 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17153 ((listp date)
17154 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17156 (defun org-parse-time-string (s &optional nodefault)
17157 "Parse the standard Org-mode time string.
17158 This should be a lot faster than the normal `parse-time-string'.
17159 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17160 hour and minute fields will be nil if not given."
17161 (cond ((string-match org-ts-regexp0 s)
17162 (list 0
17163 (if (or (match-beginning 8) (not nodefault))
17164 (string-to-number (or (match-string 8 s) "0")))
17165 (if (or (match-beginning 7) (not nodefault))
17166 (string-to-number (or (match-string 7 s) "0")))
17167 (string-to-number (match-string 4 s))
17168 (string-to-number (match-string 3 s))
17169 (string-to-number (match-string 2 s))
17170 nil nil nil))
17171 ((string-match "^<[^>]+>$" s)
17172 (decode-time (seconds-to-time (org-matcher-time s))))
17173 (t (error "Not a standard Org-mode time string: %s" s))))
17175 (defun org-timestamp-up (&optional arg)
17176 "Increase the date item at the cursor by one.
17177 If the cursor is on the year, change the year. If it is on the month,
17178 the day or the time, change that.
17179 With prefix ARG, change by that many units."
17180 (interactive "p")
17181 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17183 (defun org-timestamp-down (&optional arg)
17184 "Decrease 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-up-day (&optional arg)
17192 "Increase the date in the time stamp by one day.
17193 With prefix ARG, change that many days."
17194 (interactive "p")
17195 (if (and (not (org-at-timestamp-p t))
17196 (org-at-heading-p))
17197 (org-todo 'up)
17198 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17200 (defun org-timestamp-down-day (&optional arg)
17201 "Decrease the date in the time stamp by one day.
17202 With prefix ARG, change that many days."
17203 (interactive "p")
17204 (if (and (not (org-at-timestamp-p t))
17205 (org-at-heading-p))
17206 (org-todo 'down)
17207 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17209 (defun org-at-timestamp-p (&optional inactive-ok)
17210 "Determine if the cursor is in or at a timestamp."
17211 (interactive)
17212 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17213 (pos (point))
17214 (ans (or (looking-at tsr)
17215 (save-excursion
17216 (skip-chars-backward "^[<\n\r\t")
17217 (if (> (point) (point-min)) (backward-char 1))
17218 (and (looking-at tsr)
17219 (> (- (match-end 0) pos) -1))))))
17220 (and ans
17221 (boundp 'org-ts-what)
17222 (setq org-ts-what
17223 (cond
17224 ((= pos (match-beginning 0)) 'bracket)
17225 ;; Point is considered to be "on the bracket" whether
17226 ;; it's really on it or right after it.
17227 ((= pos (1- (match-end 0))) 'bracket)
17228 ((= pos (match-end 0)) 'after)
17229 ((org-pos-in-match-range pos 2) 'year)
17230 ((org-pos-in-match-range pos 3) 'month)
17231 ((org-pos-in-match-range pos 7) 'hour)
17232 ((org-pos-in-match-range pos 8) 'minute)
17233 ((or (org-pos-in-match-range pos 4)
17234 (org-pos-in-match-range pos 5)) 'day)
17235 ((and (> pos (or (match-end 8) (match-end 5)))
17236 (< pos (match-end 0)))
17237 (- pos (or (match-end 8) (match-end 5))))
17238 (t 'day))))
17239 ans))
17241 (defun org-toggle-timestamp-type ()
17242 "Toggle the type (<active> or [inactive]) of a time stamp."
17243 (interactive)
17244 (when (org-at-timestamp-p t)
17245 (let ((beg (match-beginning 0)) (end (match-end 0))
17246 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17247 (save-excursion
17248 (goto-char beg)
17249 (while (re-search-forward "[][<>]" end t)
17250 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17251 t t)))
17252 (message "Timestamp is now %sactive"
17253 (if (equal (char-after beg) ?<) "" "in")))))
17255 (defun org-at-clock-log-p nil
17256 "Is the cursor on the clock log line?"
17257 (save-excursion
17258 (move-beginning-of-line 1)
17259 (looking-at "^[ \t]*CLOCK:")))
17261 (defvar org-clock-history) ; defined in org-clock.el
17262 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17263 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17264 "Change the date in the time stamp at point.
17265 The date will be changed by N times WHAT. WHAT can be `day', `month',
17266 `year', `minute', `second'. If WHAT is not given, the cursor position
17267 in the timestamp determines what will be changed.
17268 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17269 (let ((origin (point)) origin-cat
17270 with-hm inactive
17271 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17272 org-ts-what
17273 extra rem
17274 ts time time0 fixnext clrgx)
17275 (if (not (org-at-timestamp-p t))
17276 (user-error "Not at a timestamp"))
17277 (if (and (not what) (eq org-ts-what 'bracket))
17278 (org-toggle-timestamp-type)
17279 ;; Point isn't on brackets. Remember the part of the time-stamp
17280 ;; the point was in. Indeed, size of time-stamps may change,
17281 ;; but point must be kept in the same category nonetheless.
17282 (setq origin-cat org-ts-what)
17283 (if (and (not what) (not (eq org-ts-what 'day))
17284 org-display-custom-times
17285 (get-text-property (point) 'display)
17286 (not (get-text-property (1- (point)) 'display)))
17287 (setq org-ts-what 'day))
17288 (setq org-ts-what (or what org-ts-what)
17289 inactive (= (char-after (match-beginning 0)) ?\[)
17290 ts (match-string 0))
17291 (replace-match "")
17292 (when (string-match
17293 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17295 (setq extra (match-string 1 ts))
17296 (if suppress-tmp-delay
17297 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17298 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17299 (setq with-hm t))
17300 (setq time0 (org-parse-time-string ts))
17301 (when (and updown
17302 (eq org-ts-what 'minute)
17303 (not current-prefix-arg))
17304 ;; This looks like s-up and s-down. Change by one rounding step.
17305 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17306 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17307 (setcar (cdr time0) (+ (nth 1 time0)
17308 (if (> n 0) (- rem) (- dm rem))))))
17309 (setq time
17310 (encode-time (or (car time0) 0)
17311 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17312 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17313 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17314 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17315 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17316 (nthcdr 6 time0)))
17317 (when (and (member org-ts-what '(hour minute))
17318 extra
17319 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17320 (setq extra (org-modify-ts-extra
17321 extra
17322 (if (eq org-ts-what 'hour) 2 5)
17323 n dm)))
17324 (when (integerp org-ts-what)
17325 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17326 (if (eq what 'calendar)
17327 (let ((cal-date (org-get-date-from-calendar)))
17328 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17329 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17330 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17331 (setcar time0 (or (car time0) 0))
17332 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17333 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17334 (setq time (apply 'encode-time time0))))
17335 ;; Insert the new time-stamp, and ensure point stays in the same
17336 ;; category as before (i.e. not after the last position in that
17337 ;; category).
17338 (let ((pos (point)))
17339 ;; Stay before inserted string. `save-excursion' is of no use.
17340 (setq org-last-changed-timestamp
17341 (org-insert-time-stamp time with-hm inactive nil nil extra))
17342 (goto-char pos))
17343 (save-match-data
17344 (looking-at org-ts-regexp3)
17345 (goto-char (cond
17346 ;; `day' category ends before `hour' if any, or at
17347 ;; the end of the day name.
17348 ((eq origin-cat 'day)
17349 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17350 ((eq origin-cat 'hour) (min (match-end 7) origin))
17351 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17352 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17353 ;; `year' and `month' have both fixed size: point
17354 ;; couldn't have moved into another part.
17355 (t origin))))
17356 ;; Update clock if on a CLOCK line.
17357 (org-clock-update-time-maybe)
17358 ;; Maybe adjust the closest clock in `org-clock-history'
17359 (when org-clock-adjust-closest
17360 (if (not (and (org-at-clock-log-p)
17361 (< 1 (length (delq nil (mapcar 'marker-position
17362 org-clock-history))))))
17363 (message "No clock to adjust")
17364 (cond ((save-excursion ; fix previous clock?
17365 (re-search-backward org-ts-regexp0 nil t)
17366 (org-looking-back (concat org-clock-string " \\[")))
17367 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17368 ((save-excursion ; fix next clock?
17369 (re-search-backward org-ts-regexp0 nil t)
17370 (looking-at (concat org-ts-regexp0 "\\] =>")))
17371 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17372 (save-window-excursion
17373 ;; Find closest clock to point, adjust the previous/next one in history
17374 (let* ((p (save-excursion (org-back-to-heading t)))
17375 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17376 (clfixnth
17377 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17378 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17379 (if (not clfixpos)
17380 (message "No clock to adjust")
17381 (save-excursion
17382 (org-goto-marker-or-bmk clfixpos)
17383 (org-show-subtree)
17384 (when (re-search-forward clrgx nil t)
17385 (goto-char (match-beginning 1))
17386 (let (org-clock-adjust-closest)
17387 (org-timestamp-change n org-ts-what updown))
17388 (message "Clock adjusted in %s for heading: %s"
17389 (file-name-nondirectory (buffer-file-name))
17390 (org-get-heading t t)))))))))
17391 ;; Try to recenter the calendar window, if any.
17392 (if (and org-calendar-follow-timestamp-change
17393 (get-buffer-window "*Calendar*" t)
17394 (memq org-ts-what '(day month year)))
17395 (org-recenter-calendar (time-to-days time))))))
17397 (defun org-modify-ts-extra (s pos n dm)
17398 "Change the different parts of the lead-time and repeat fields in timestamp."
17399 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17400 ng h m new rem)
17401 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17402 (cond
17403 ((or (org-pos-in-match-range pos 2)
17404 (org-pos-in-match-range pos 3))
17405 (setq m (string-to-number (match-string 3 s))
17406 h (string-to-number (match-string 2 s)))
17407 (if (org-pos-in-match-range pos 2)
17408 (setq h (+ h n))
17409 (setq n (* dm (org-no-warnings (signum n))))
17410 (when (not (= 0 (setq rem (% m dm))))
17411 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17412 (setq m (+ m n)))
17413 (if (< m 0) (setq m (+ m 60) h (1- h)))
17414 (if (> m 59) (setq m (- m 60) h (1+ h)))
17415 (setq h (min 24 (max 0 h)))
17416 (setq ng 1 new (format "-%02d:%02d" h m)))
17417 ((org-pos-in-match-range pos 6)
17418 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17419 ((org-pos-in-match-range pos 5)
17420 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17422 ((org-pos-in-match-range pos 9)
17423 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17424 ((org-pos-in-match-range pos 8)
17425 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17427 (when ng
17428 (setq s (concat
17429 (substring s 0 (match-beginning ng))
17431 (substring s (match-end ng))))))
17434 (defun org-recenter-calendar (date)
17435 "If the calendar is visible, recenter it to DATE."
17436 (let ((cwin (get-buffer-window "*Calendar*" t)))
17437 (when cwin
17438 (let ((calendar-move-hook nil))
17439 (with-selected-window cwin
17440 (calendar-goto-date (if (listp date) date
17441 (calendar-gregorian-from-absolute date))))))))
17443 (defun org-goto-calendar (&optional arg)
17444 "Go to the Emacs calendar at the current date.
17445 If there is a time stamp in the current line, go to that date.
17446 A prefix ARG can be used to force the current date."
17447 (interactive "P")
17448 (let ((tsr org-ts-regexp) diff
17449 (calendar-move-hook nil)
17450 (calendar-view-holidays-initially-flag nil)
17451 (calendar-view-diary-initially-flag nil))
17452 (if (or (org-at-timestamp-p)
17453 (save-excursion
17454 (beginning-of-line 1)
17455 (looking-at (concat ".*" tsr))))
17456 (let ((d1 (time-to-days (current-time)))
17457 (d2 (time-to-days
17458 (org-time-string-to-time (match-string 1)))))
17459 (setq diff (- d2 d1))))
17460 (calendar)
17461 (calendar-goto-today)
17462 (if (and diff (not arg)) (calendar-forward-day diff))))
17464 (defun org-get-date-from-calendar ()
17465 "Return a list (month day year) of date at point in calendar."
17466 (with-current-buffer "*Calendar*"
17467 (save-match-data
17468 (calendar-cursor-to-date))))
17470 (defun org-date-from-calendar ()
17471 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17472 If there is already a time stamp at the cursor position, update it."
17473 (interactive)
17474 (if (org-at-timestamp-p t)
17475 (org-timestamp-change 0 'calendar)
17476 (let ((cal-date (org-get-date-from-calendar)))
17477 (org-insert-time-stamp
17478 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17480 (defcustom org-effort-durations
17481 `(("h" . 60)
17482 ("d" . ,(* 60 8))
17483 ("w" . ,(* 60 8 5))
17484 ("m" . ,(* 60 8 5 4))
17485 ("y" . ,(* 60 8 5 40)))
17486 "Conversion factor to minutes for an effort modifier.
17488 Each entry has the form (MODIFIER . MINUTES).
17490 In an effort string, a number followed by MODIFIER is multiplied
17491 by the specified number of MINUTES to obtain an effort in
17492 minutes.
17494 For example, if the value of this variable is ((\"hours\" . 60)), then an
17495 effort string \"2hours\" is equivalent to 120 minutes."
17496 :group 'org-agenda
17497 :version "24.1"
17498 :type '(alist :key-type (string :tag "Modifier")
17499 :value-type (number :tag "Minutes")))
17501 (defun org-minutes-to-clocksum-string (m)
17502 "Format number of minutes as a clocksum string.
17503 The format is determined by `org-time-clocksum-format',
17504 `org-time-clocksum-use-fractional' and
17505 `org-time-clocksum-fractional-format' and
17506 `org-time-clocksum-use-effort-durations'."
17507 (let ((clocksum "")
17508 (m (round m)) ; Don't allow fractions of minutes
17509 h d w mo y fmt n)
17510 (setq h (if org-time-clocksum-use-effort-durations
17511 (cdr (assoc "h" org-effort-durations)) 60)
17512 d (if org-time-clocksum-use-effort-durations
17513 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17514 w (if org-time-clocksum-use-effort-durations
17515 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17516 mo (if org-time-clocksum-use-effort-durations
17517 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17518 y (if org-time-clocksum-use-effort-durations
17519 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17520 ;; fractional format
17521 (if org-time-clocksum-use-fractional
17522 (cond
17523 ;; single format string
17524 ((stringp org-time-clocksum-fractional-format)
17525 (format org-time-clocksum-fractional-format (/ m (float h))))
17526 ;; choice of fractional formats for different time units
17527 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17528 (> (/ (truncate m) (* y d h)) 0))
17529 (format fmt (/ m (* y d (float h)))))
17530 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17531 (> (/ (truncate m) (* mo d h)) 0))
17532 (format fmt (/ m (* mo d (float h)))))
17533 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17534 (> (/ (truncate m) (* w d h)) 0))
17535 (format fmt (/ m (* w d (float h)))))
17536 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17537 (> (/ (truncate m) (* d h)) 0))
17538 (format fmt (/ m (* d (float h)))))
17539 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17540 (> (/ (truncate m) h) 0))
17541 (format fmt (/ m (float h))))
17542 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17543 (format fmt m))
17544 ;; fall back to smallest time unit with a format
17545 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17546 (format fmt (/ m (float h))))
17547 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17548 (format fmt (/ m (* d (float h)))))
17549 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17550 (format fmt (/ m (* w d (float h)))))
17551 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17552 (format fmt (/ m (* mo d (float h)))))
17553 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17554 (format fmt (/ m (* y d (float h))))))
17555 ;; standard (non-fractional) format, with single format string
17556 (if (stringp org-time-clocksum-format)
17557 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17558 ;; separate formats components
17559 (and (setq fmt (plist-get org-time-clocksum-format :years))
17560 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17561 (plist-get org-time-clocksum-format :require-years))
17562 (setq clocksum (concat clocksum (format fmt n))
17563 m (- m (* n y d h))))
17564 (and (setq fmt (plist-get org-time-clocksum-format :months))
17565 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17566 (plist-get org-time-clocksum-format :require-months))
17567 (setq clocksum (concat clocksum (format fmt n))
17568 m (- m (* n mo d h))))
17569 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17570 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17571 (plist-get org-time-clocksum-format :require-weeks))
17572 (setq clocksum (concat clocksum (format fmt n))
17573 m (- m (* n w d h))))
17574 (and (setq fmt (plist-get org-time-clocksum-format :days))
17575 (or (> (setq n (/ (truncate m) (* d h))) 0)
17576 (plist-get org-time-clocksum-format :require-days))
17577 (setq clocksum (concat clocksum (format fmt n))
17578 m (- m (* n d h))))
17579 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17580 (or (> (setq n (/ (truncate m) h)) 0)
17581 (plist-get org-time-clocksum-format :require-hours))
17582 (setq clocksum (concat clocksum (format fmt n))
17583 m (- m (* n h))))
17584 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17585 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17586 (setq clocksum (concat clocksum (format fmt m))))
17587 ;; return formatted time duration
17588 clocksum))))
17590 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17591 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17592 "Org mode version 8.0")
17594 (defun org-hours-to-clocksum-string (n)
17595 (org-minutes-to-clocksum-string (* n 60)))
17597 (defun org-hh:mm-string-to-minutes (s)
17598 "Convert a string H:MM to a number of minutes.
17599 If the string is just a number, interpret it as minutes.
17600 In fact, the first hh:mm or number in the string will be taken,
17601 there can be extra stuff in the string.
17602 If no number is found, the return value is 0."
17603 (cond
17604 ((integerp s) s)
17605 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17606 (+ (* (string-to-number (match-string 1 s)) 60)
17607 (string-to-number (match-string 2 s))))
17608 ((string-match "\\([0-9]+\\)" s)
17609 (string-to-number (match-string 1 s)))
17610 (t 0)))
17612 (defcustom org-image-actual-width t
17613 "Should we use the actual width of images when inlining them?
17615 When set to `t', always use the image width.
17617 When set to a number, use imagemagick (when available) to set
17618 the image's width to this value.
17620 When set to a number in a list, try to get the width from any
17621 #+ATTR.* keyword if it matches a width specification like
17623 #+ATTR_HTML: :width 300px
17625 and fall back on that number if none is found.
17627 When set to nil, try to get the width from an #+ATTR.* keyword
17628 and fall back on the original width if none is found.
17630 This requires Emacs >= 24.1, build with imagemagick support."
17631 :group 'org-appearance
17632 :version "24.4"
17633 :package-version '(Org . "8.0")
17634 :type '(choice
17635 (const :tag "Use the image width" t)
17636 (integer :tag "Use a number of pixels")
17637 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17638 (const :tag "Use #+ATTR* or don't resize" nil)))
17640 (defcustom org-agenda-inhibit-startup nil
17641 "Inhibit startup when preparing agenda buffers.
17642 When this variable is `t' (the default), the initialization of
17643 the Org agenda buffers is inhibited: e.g. the visibility state
17644 is not set, the tables are not re-aligned, etc."
17645 :type 'boolean
17646 :version "24.3"
17647 :group 'org-agenda)
17649 (defun org-duration-string-to-minutes (s &optional output-to-string)
17650 "Convert a duration string S to minutes.
17652 A bare number is interpreted as minutes, modifiers can be set by
17653 customizing `org-effort-durations' (which see).
17655 Entries containing a colon are interpreted as H:MM by
17656 `org-hh:mm-string-to-minutes'."
17657 (let ((result 0)
17658 (re (concat "\\([0-9.]+\\) *\\("
17659 (regexp-opt (mapcar 'car org-effort-durations))
17660 "\\)")))
17661 (while (string-match re s)
17662 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17663 (string-to-number (match-string 1 s))))
17664 (setq s (replace-match "" nil t s)))
17665 (setq result (floor result))
17666 (incf result (org-hh:mm-string-to-minutes s))
17667 (if output-to-string (number-to-string result) result)))
17669 ;;;; Files
17671 (defun org-save-all-org-buffers ()
17672 "Save all Org-mode buffers without user confirmation."
17673 (interactive)
17674 (message "Saving all Org-mode buffers...")
17675 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17676 (when (featurep 'org-id) (org-id-locations-save))
17677 (message "Saving all Org-mode buffers... done"))
17679 (defun org-revert-all-org-buffers ()
17680 "Revert all Org-mode buffers.
17681 Prompt for confirmation when there are unsaved changes.
17682 Be sure you know what you are doing before letting this function
17683 overwrite your changes.
17685 This function is useful in a setup where one tracks org files
17686 with a version control system, to revert on one machine after pulling
17687 changes from another. I believe the procedure must be like this:
17689 1. M-x org-save-all-org-buffers
17690 2. Pull changes from the other machine, resolve conflicts
17691 3. M-x org-revert-all-org-buffers"
17692 (interactive)
17693 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17694 (user-error "Abort"))
17695 (save-excursion
17696 (save-window-excursion
17697 (mapc
17698 (lambda (b)
17699 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17700 (with-current-buffer b buffer-file-name))
17701 (org-pop-to-buffer-same-window b)
17702 (revert-buffer t 'no-confirm)))
17703 (buffer-list))
17704 (when (and (featurep 'org-id) org-id-track-globally)
17705 (org-id-locations-load)))))
17707 ;;;; Agenda files
17709 ;;;###autoload
17710 (defun org-switchb (&optional arg)
17711 "Switch between Org buffers.
17712 With one prefix argument, restrict available buffers to files.
17713 With two prefix arguments, restrict available buffers to agenda files.
17715 Defaults to `iswitchb' for buffer name completion.
17716 Set `org-completion-use-ido' to make it use ido instead."
17717 (interactive "P")
17718 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17719 ((equal arg '(16)) (org-buffer-list 'agenda))
17720 (t (org-buffer-list))))
17721 (org-completion-use-iswitchb org-completion-use-iswitchb)
17722 (org-completion-use-ido org-completion-use-ido))
17723 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17724 (setq org-completion-use-iswitchb t))
17725 (org-pop-to-buffer-same-window
17726 (org-icompleting-read "Org buffer: "
17727 (mapcar 'list (mapcar 'buffer-name blist))
17728 nil t))))
17730 ;;; Define some older names previously used for this functionality
17731 ;;;###autoload
17732 (defalias 'org-ido-switchb 'org-switchb)
17733 ;;;###autoload
17734 (defalias 'org-iswitchb 'org-switchb)
17736 (defun org-buffer-list (&optional predicate exclude-tmp)
17737 "Return a list of Org buffers.
17738 PREDICATE can be `export', `files' or `agenda'.
17740 export restrict the list to Export buffers.
17741 files restrict the list to buffers visiting Org files.
17742 agenda restrict the list to buffers visiting agenda files.
17744 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17745 (let* ((bfn nil)
17746 (agenda-files (and (eq predicate 'agenda)
17747 (mapcar 'file-truename (org-agenda-files t))))
17748 (filter
17749 (cond
17750 ((eq predicate 'files)
17751 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17752 ((eq predicate 'export)
17753 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17754 ((eq predicate 'agenda)
17755 (lambda (b)
17756 (with-current-buffer b
17757 (and (derived-mode-p 'org-mode)
17758 (setq bfn (buffer-file-name b))
17759 (member (file-truename bfn) agenda-files)))))
17760 (t (lambda (b) (with-current-buffer b
17761 (or (derived-mode-p 'org-mode)
17762 (string-match "\*Org .*Export"
17763 (buffer-name b)))))))))
17764 (delq nil
17765 (mapcar
17766 (lambda(b)
17767 (if (and (funcall filter b)
17768 (or (not exclude-tmp)
17769 (not (string-match "tmp" (buffer-name b)))))
17771 nil))
17772 (buffer-list)))))
17774 (defun org-agenda-files (&optional unrestricted archives)
17775 "Get the list of agenda files.
17776 Optional UNRESTRICTED means return the full list even if a restriction
17777 is currently in place.
17778 When ARCHIVES is t, include all archive files that are really being
17779 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17780 `org-agenda-archives-mode' is t."
17781 (let ((files
17782 (cond
17783 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17784 ((stringp org-agenda-files) (org-read-agenda-file-list))
17785 ((listp org-agenda-files) org-agenda-files)
17786 (t (error "Invalid value of `org-agenda-files'")))))
17787 (setq files (apply 'append
17788 (mapcar (lambda (f)
17789 (if (file-directory-p f)
17790 (directory-files
17791 f t org-agenda-file-regexp)
17792 (list f)))
17793 files)))
17794 (when org-agenda-skip-unavailable-files
17795 (setq files (delq nil
17796 (mapcar (function
17797 (lambda (file)
17798 (and (file-readable-p file) file)))
17799 files))))
17800 (when (or (eq archives t)
17801 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17802 (setq files (org-add-archive-files files)))
17803 files))
17805 (defun org-agenda-file-p (&optional file)
17806 "Return non-nil, if FILE is an agenda file.
17807 If FILE is omitted, use the file associated with the current
17808 buffer."
17809 (member (or file (buffer-file-name))
17810 (org-agenda-files t)))
17812 (defun org-edit-agenda-file-list ()
17813 "Edit the list of agenda files.
17814 Depending on setup, this either uses customize to edit the variable
17815 `org-agenda-files', or it visits the file that is holding the list. In the
17816 latter case, the buffer is set up in a way that saving it automatically kills
17817 the buffer and restores the previous window configuration."
17818 (interactive)
17819 (if (stringp org-agenda-files)
17820 (let ((cw (current-window-configuration)))
17821 (find-file org-agenda-files)
17822 (org-set-local 'org-window-configuration cw)
17823 (org-add-hook 'after-save-hook
17824 (lambda ()
17825 (set-window-configuration
17826 (prog1 org-window-configuration
17827 (kill-buffer (current-buffer))))
17828 (org-install-agenda-files-menu)
17829 (message "New agenda file list installed"))
17830 nil 'local)
17831 (message "%s" (substitute-command-keys
17832 "Edit list and finish with \\[save-buffer]")))
17833 (customize-variable 'org-agenda-files)))
17835 (defun org-store-new-agenda-file-list (list)
17836 "Set new value for the agenda file list and save it correctly."
17837 (if (stringp org-agenda-files)
17838 (let ((fe (org-read-agenda-file-list t)) b u)
17839 (while (setq b (find-buffer-visiting org-agenda-files))
17840 (kill-buffer b))
17841 (with-temp-file org-agenda-files
17842 (insert
17843 (mapconcat
17844 (lambda (f) ;; Keep un-expanded entries.
17845 (if (setq u (assoc f fe))
17846 (cdr u)
17848 list "\n")
17849 "\n")))
17850 (let ((org-mode-hook nil) (org-inhibit-startup t)
17851 (org-insert-mode-line-in-empty-file nil))
17852 (setq org-agenda-files list)
17853 (customize-save-variable 'org-agenda-files org-agenda-files))))
17855 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17856 "Read the list of agenda files from a file.
17857 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17858 filenames, used by `org-store-new-agenda-file-list' to write back
17859 un-expanded file names."
17860 (when (file-directory-p org-agenda-files)
17861 (error "`org-agenda-files' cannot be a single directory"))
17862 (when (stringp org-agenda-files)
17863 (with-temp-buffer
17864 (insert-file-contents org-agenda-files)
17865 (mapcar
17866 (lambda (f)
17867 (let ((e (expand-file-name (substitute-in-file-name f)
17868 org-directory)))
17869 (if pair-with-expansion
17870 (cons e f)
17871 e)))
17872 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17874 ;;;###autoload
17875 (defun org-cycle-agenda-files ()
17876 "Cycle through the files in `org-agenda-files'.
17877 If the current buffer visits an agenda file, find the next one in the list.
17878 If the current buffer does not, find the first agenda file."
17879 (interactive)
17880 (let* ((fs (org-agenda-files t))
17881 (files (append fs (list (car fs))))
17882 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17883 file)
17884 (unless files (user-error "No agenda files"))
17885 (catch 'exit
17886 (while (setq file (pop files))
17887 (if (equal (file-truename file) tcf)
17888 (when (car files)
17889 (find-file (car files))
17890 (throw 'exit t))))
17891 (find-file (car fs)))
17892 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17894 (defun org-agenda-file-to-front (&optional to-end)
17895 "Move/add the current file to the top of the agenda file list.
17896 If the file is not present in the list, it is added to the front. If it is
17897 present, it is moved there. With optional argument TO-END, add/move to the
17898 end of the list."
17899 (interactive "P")
17900 (let ((org-agenda-skip-unavailable-files nil)
17901 (file-alist (mapcar (lambda (x)
17902 (cons (file-truename x) x))
17903 (org-agenda-files t)))
17904 (ctf (file-truename
17905 (or buffer-file-name
17906 (user-error "Please save the current buffer to a file"))))
17907 x had)
17908 (setq x (assoc ctf file-alist) had x)
17910 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17911 (if to-end
17912 (setq file-alist (append (delq x file-alist) (list x)))
17913 (setq file-alist (cons x (delq x file-alist))))
17914 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17915 (org-install-agenda-files-menu)
17916 (message "File %s to %s of agenda file list"
17917 (if had "moved" "added") (if to-end "end" "front"))))
17919 (defun org-remove-file (&optional file)
17920 "Remove current file from the list of files in variable `org-agenda-files'.
17921 These are the files which are being checked for agenda entries.
17922 Optional argument FILE means use this file instead of the current."
17923 (interactive)
17924 (let* ((org-agenda-skip-unavailable-files nil)
17925 (file (or file buffer-file-name
17926 (user-error "Current buffer does not visit a file")))
17927 (true-file (file-truename file))
17928 (afile (abbreviate-file-name file))
17929 (files (delq nil (mapcar
17930 (lambda (x)
17931 (if (equal true-file
17932 (file-truename x))
17933 nil x))
17934 (org-agenda-files t)))))
17935 (if (not (= (length files) (length (org-agenda-files t))))
17936 (progn
17937 (org-store-new-agenda-file-list files)
17938 (org-install-agenda-files-menu)
17939 (message "Removed file: %s" afile))
17940 (message "File was not in list: %s (not removed)" afile))))
17942 (defun org-file-menu-entry (file)
17943 (vector file (list 'find-file file) t))
17945 (defun org-check-agenda-file (file)
17946 "Make sure FILE exists. If not, ask user what to do."
17947 (when (not (file-exists-p file))
17948 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17949 (abbreviate-file-name file))
17950 (let ((r (downcase (read-char-exclusive))))
17951 (cond
17952 ((equal r ?r)
17953 (org-remove-file file)
17954 (throw 'nextfile t))
17955 (t (error "Abort"))))))
17957 (defun org-get-agenda-file-buffer (file)
17958 "Get a buffer visiting FILE. If the buffer needs to be created, add
17959 it to the list of buffers which might be released later."
17960 (let ((buf (org-find-base-buffer-visiting file)))
17961 (if buf
17962 buf ; just return it
17963 ;; Make a new buffer and remember it
17964 (setq buf (find-file-noselect file))
17965 (if buf (push buf org-agenda-new-buffers))
17966 buf)))
17968 (defun org-release-buffers (blist)
17969 "Release all buffers in list, asking the user for confirmation when needed.
17970 When a buffer is unmodified, it is just killed. When modified, it is saved
17971 \(if the user agrees) and then killed."
17972 (let (buf file)
17973 (while (setq buf (pop blist))
17974 (setq file (buffer-file-name buf))
17975 (when (and (buffer-modified-p buf)
17976 file
17977 (y-or-n-p (format "Save file %s? " file)))
17978 (with-current-buffer buf (save-buffer)))
17979 (kill-buffer buf))))
17981 (defun org-agenda-prepare-buffers (files)
17982 "Create buffers for all agenda files, protect archived trees and comments."
17983 (interactive)
17984 (let ((pa '(:org-archived t))
17985 (pc '(:org-comment t))
17986 (pall '(:org-archived t :org-comment t))
17987 (inhibit-read-only t)
17988 (org-inhibit-startup org-agenda-inhibit-startup)
17989 (rea (concat ":" org-archive-tag ":"))
17990 file re)
17991 (setq org-tag-alist-for-agenda nil
17992 org-tag-groups-alist-for-agenda nil)
17993 (save-excursion
17994 (save-restriction
17995 (while (setq file (pop files))
17996 (catch 'nextfile
17997 (if (bufferp file)
17998 (set-buffer file)
17999 (org-check-agenda-file file)
18000 (set-buffer (org-get-agenda-file-buffer file)))
18001 (widen)
18002 (org-set-regexps-and-options-for-tags)
18003 (goto-char (point-min))
18004 (let ((case-fold-search t))
18005 (when (search-forward "#+setupfile" nil t)
18006 ;; Don't set all regexps and options systematically as
18007 ;; this is only run for setting agenda tags from setup
18008 ;; file
18009 (org-set-regexps-and-options)))
18010 (org-refresh-category-properties)
18011 (org-refresh-properties org-effort-property 'org-effort)
18012 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18013 (setq org-todo-keywords-for-agenda
18014 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18015 (setq org-done-keywords-for-agenda
18016 (append org-done-keywords-for-agenda org-done-keywords))
18017 (setq org-todo-keyword-alist-for-agenda
18018 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18019 (setq org-drawers-for-agenda
18020 (append org-drawers-for-agenda org-drawers))
18021 (setq org-tag-alist-for-agenda
18022 (org-uniquify
18023 (append org-tag-alist-for-agenda
18024 org-tag-alist
18025 org-tag-persistent-alist)))
18026 (if org-group-tags
18027 (setq org-tag-groups-alist-for-agenda
18028 (org-uniquify-alist
18029 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18030 (org-with-silent-modifications
18031 (save-excursion
18032 (remove-text-properties (point-min) (point-max) pall)
18033 (when org-agenda-skip-archived-trees
18034 (goto-char (point-min))
18035 (while (re-search-forward rea nil t)
18036 (if (org-at-heading-p t)
18037 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18038 (goto-char (point-min))
18039 (setq re (format org-heading-keyword-regexp-format
18040 org-comment-string))
18041 (while (re-search-forward re nil t)
18042 (add-text-properties
18043 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18044 (setq org-todo-keywords-for-agenda
18045 (org-uniquify org-todo-keywords-for-agenda))
18046 (setq org-todo-keyword-alist-for-agenda
18047 (org-uniquify org-todo-keyword-alist-for-agenda))))
18050 ;;;; CDLaTeX minor mode
18052 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18053 "Keymap for the minor `org-cdlatex-mode'.")
18055 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18056 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18057 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18058 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18059 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18061 (defvar org-cdlatex-texmathp-advice-is-done nil
18062 "Flag remembering if we have applied the advice to texmathp already.")
18064 (define-minor-mode org-cdlatex-mode
18065 "Toggle the minor `org-cdlatex-mode'.
18066 This mode supports entering LaTeX environment and math in LaTeX fragments
18067 in Org-mode.
18068 \\{org-cdlatex-mode-map}"
18069 nil " OCDL" nil
18070 (when org-cdlatex-mode
18071 (require 'cdlatex)
18072 (run-hooks 'cdlatex-mode-hook)
18073 (cdlatex-compute-tables))
18074 (unless org-cdlatex-texmathp-advice-is-done
18075 (setq org-cdlatex-texmathp-advice-is-done t)
18076 (defadvice texmathp (around org-math-always-on activate)
18077 "Always return t in org-mode buffers.
18078 This is because we want to insert math symbols without dollars even outside
18079 the LaTeX math segments. If Orgmode thinks that point is actually inside
18080 an embedded LaTeX fragment, let texmathp do its job.
18081 \\[org-cdlatex-mode-map]"
18082 (interactive)
18083 (let (p)
18084 (cond
18085 ((not (derived-mode-p 'org-mode)) ad-do-it)
18086 ((eq this-command 'cdlatex-math-symbol)
18087 (setq ad-return-value t
18088 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18090 (let ((p (org-inside-LaTeX-fragment-p)))
18091 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18092 (setq ad-return-value t
18093 texmathp-why '("Org-mode embedded math" . 0))
18094 (if p ad-do-it)))))))))
18096 (defun turn-on-org-cdlatex ()
18097 "Unconditionally turn on `org-cdlatex-mode'."
18098 (org-cdlatex-mode 1))
18100 (defun org-try-cdlatex-tab ()
18101 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18102 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18103 - inside a LaTeX fragment, or
18104 - after the first word in a line, where an abbreviation expansion could
18105 insert a LaTeX environment."
18106 (when org-cdlatex-mode
18107 (cond
18108 ;; Before any word on the line: No expansion possible.
18109 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18110 ;; Just after first word on the line: Expand it. Make sure it
18111 ;; cannot happen on headlines, though.
18112 ((save-excursion
18113 (skip-chars-backward "a-zA-Z0-9*")
18114 (skip-chars-backward " \t")
18115 (and (bolp) (not (org-at-heading-p))))
18116 (cdlatex-tab) t)
18117 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18119 (defun org-cdlatex-underscore-caret (&optional arg)
18120 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18121 Revert to the normal definition outside of these fragments."
18122 (interactive "P")
18123 (if (org-inside-LaTeX-fragment-p)
18124 (call-interactively 'cdlatex-sub-superscript)
18125 (let (org-cdlatex-mode)
18126 (call-interactively (key-binding (vector last-input-event))))))
18128 (defun org-cdlatex-math-modify (&optional arg)
18129 "Execute `cdlatex-math-modify' in LaTeX fragments.
18130 Revert to the normal definition outside of these fragments."
18131 (interactive "P")
18132 (if (org-inside-LaTeX-fragment-p)
18133 (call-interactively 'cdlatex-math-modify)
18134 (let (org-cdlatex-mode)
18135 (call-interactively (key-binding (vector last-input-event))))))
18139 ;;;; LaTeX fragments
18141 (defvar org-latex-regexps
18142 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18143 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18144 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18145 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18146 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18147 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18148 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18149 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18150 "Regular expressions for matching embedded LaTeX.")
18152 (defun org-inside-LaTeX-fragment-p ()
18153 "Test if point is inside a LaTeX fragment.
18154 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18155 sequence appearing also before point.
18156 Even though the matchers for math are configurable, this function assumes
18157 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18158 delimiters are skipped when they have been removed by customization.
18159 The return value is nil, or a cons cell with the delimiter and the
18160 position of this delimiter.
18162 This function does a reasonably good job, but can locally be fooled by
18163 for example currency specifications. For example it will assume being in
18164 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18165 fragments that are properly closed, but during editing, we have to live
18166 with the uncertainty caused by missing closing delimiters. This function
18167 looks only before point, not after."
18168 (catch 'exit
18169 (let ((pos (point))
18170 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18171 (lim (progn
18172 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18173 (point)))
18174 dd-on str (start 0) m re)
18175 (goto-char pos)
18176 (when dodollar
18177 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18178 re (nth 1 (assoc "$" org-latex-regexps)))
18179 (while (string-match re str start)
18180 (cond
18181 ((= (match-end 0) (length str))
18182 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18183 ((= (match-end 0) (- (length str) 5))
18184 (throw 'exit nil))
18185 (t (setq start (match-end 0))))))
18186 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18187 (goto-char pos)
18188 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18189 (and (match-beginning 2) (throw 'exit nil))
18190 ;; count $$
18191 (while (re-search-backward "\\$\\$" lim t)
18192 (setq dd-on (not dd-on)))
18193 (goto-char pos)
18194 (if dd-on (cons "$$" m))))))
18196 (defun org-inside-latex-macro-p ()
18197 "Is point inside a LaTeX macro or its arguments?"
18198 (save-match-data
18199 (org-in-regexp
18200 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18202 (defvar org-latex-fragment-image-overlays nil
18203 "List of overlays carrying the images of latex fragments.")
18204 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18206 (defun org-remove-latex-fragment-image-overlays ()
18207 "Remove all overlays with LaTeX fragment images in current buffer."
18208 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18209 (setq org-latex-fragment-image-overlays nil))
18211 (defun org-preview-latex-fragment (&optional subtree)
18212 "Preview the LaTeX fragment at point, or all locally or globally.
18213 If the cursor is in a LaTeX fragment, create the image and overlay
18214 it over the source code. If there is no fragment at point, display
18215 all fragments in the current text, from one headline to the next. With
18216 prefix SUBTREE, display all fragments in the current subtree. With a
18217 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18218 the cursor is before the first headline,
18219 display all fragments in the buffer.
18220 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18221 (interactive "P")
18222 (unless buffer-file-name
18223 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18224 (org-remove-latex-fragment-image-overlays)
18225 (save-excursion
18226 (save-restriction
18227 (let (beg end at msg)
18228 (cond
18229 ((or (equal subtree '(16))
18230 (not (save-excursion
18231 (re-search-backward org-outline-regexp-bol nil t))))
18232 (setq beg (point-min) end (point-max)
18233 msg "Creating images for buffer...%s"))
18234 ((equal subtree '(4))
18235 (org-back-to-heading)
18236 (setq beg (point) end (org-end-of-subtree t)
18237 msg "Creating images for subtree...%s"))
18239 (if (setq at (org-inside-LaTeX-fragment-p))
18240 (goto-char (max (point-min) (- (cdr at) 2)))
18241 (org-back-to-heading))
18242 (setq beg (point) end (progn (outline-next-heading) (point))
18243 msg (if at "Creating image...%s"
18244 "Creating images for entry...%s"))))
18245 (message msg "")
18246 (narrow-to-region beg end)
18247 (goto-char beg)
18248 (org-format-latex
18249 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18250 (file-name-nondirectory
18251 buffer-file-name)))
18252 default-directory 'overlays msg at 'forbuffer
18253 org-latex-create-formula-image-program)
18254 (message msg "done. Use `C-c C-c' to remove images.")))))
18256 (defun org-format-latex (prefix &optional dir overlays msg at
18257 forbuffer processing-type)
18258 "Replace LaTeX fragments with links to an image, and produce images.
18259 Some of the options can be changed using the variable
18260 `org-format-latex-options'."
18261 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18262 (let* ((prefixnodir (file-name-nondirectory prefix))
18263 (absprefix (expand-file-name prefix dir))
18264 (todir (file-name-directory absprefix))
18265 (opt org-format-latex-options)
18266 (optnew org-format-latex-options)
18267 (matchers (plist-get opt :matchers))
18268 (re-list org-latex-regexps)
18269 (cnt 0) txt hash link beg end re e checkdir
18270 string
18271 m n block-type block linkfile movefile ov)
18272 ;; Check the different regular expressions
18273 (while (setq e (pop re-list))
18274 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18275 block (if block-type "\n\n" ""))
18276 (when (member m matchers)
18277 (goto-char (point-min))
18278 (while (re-search-forward re nil t)
18279 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18280 (or (not overlays)
18281 (not (eq (get-char-property (match-beginning n)
18282 'org-overlay-type)
18283 'org-latex-overlay))))
18284 (cond
18285 ((eq processing-type 'verbatim))
18286 ((eq processing-type 'mathjax)
18287 ;; Prepare for MathJax processing.
18288 (setq string (match-string n))
18289 (when (member m '("$" "$1"))
18290 (save-excursion
18291 (delete-region (match-beginning n) (match-end n))
18292 (goto-char (match-beginning n))
18293 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18294 ((or (eq processing-type 'dvipng)
18295 (eq processing-type 'imagemagick))
18296 ;; Process to an image.
18297 (setq txt (match-string n)
18298 beg (match-beginning n) end (match-end n)
18299 cnt (1+ cnt))
18300 (let ((face (face-at-point))
18301 (fg (plist-get opt :foreground))
18302 (bg (plist-get opt :background))
18303 ;; Ensure full list is printed.
18304 print-length print-level)
18305 (when forbuffer
18306 ;; Get the colors from the face at point.
18307 (goto-char beg)
18308 (when (eq fg 'auto)
18309 (setq fg (face-attribute face :foreground nil 'default)))
18310 (when (eq bg 'auto)
18311 (setq bg (face-attribute face :background nil 'default)))
18312 (setq optnew (copy-sequence opt))
18313 (plist-put optnew :foreground fg)
18314 (plist-put optnew :background bg))
18315 (setq hash (sha1 (prin1-to-string
18316 (list org-format-latex-header
18317 org-latex-default-packages-alist
18318 org-latex-packages-alist
18319 org-format-latex-options
18320 forbuffer txt fg bg)))
18321 linkfile (format "%s_%s.png" prefix hash)
18322 movefile (format "%s_%s.png" absprefix hash)))
18323 (setq link (concat block "[[file:" linkfile "]]" block))
18324 (if msg (message msg cnt))
18325 (goto-char beg)
18326 (unless checkdir ; Ensure the directory exists.
18327 (setq checkdir t)
18328 (or (file-directory-p todir) (make-directory todir t)))
18329 (unless (file-exists-p movefile)
18330 (org-create-formula-image
18331 txt movefile optnew forbuffer processing-type))
18332 (if overlays
18333 (progn
18334 (mapc (lambda (o)
18335 (if (eq (overlay-get o 'org-overlay-type)
18336 'org-latex-overlay)
18337 (delete-overlay o)))
18338 (overlays-in beg end))
18339 (setq ov (make-overlay beg end))
18340 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18341 (if (featurep 'xemacs)
18342 (progn
18343 (overlay-put ov 'invisible t)
18344 (overlay-put
18345 ov 'end-glyph
18346 (make-glyph (vector 'png :file movefile))))
18347 (overlay-put
18348 ov 'display
18349 (list 'image :type 'png :file movefile :ascent 'center)))
18350 (push ov org-latex-fragment-image-overlays)
18351 (goto-char end))
18352 (delete-region beg end)
18353 (insert (org-add-props link
18354 (list 'org-latex-src
18355 (replace-regexp-in-string
18356 "\"" "" txt)
18357 'org-latex-src-embed-type
18358 (if block-type 'paragraph 'character))))))
18359 ((eq processing-type 'mathml)
18360 ;; Process to MathML
18361 (unless (save-match-data (org-format-latex-mathml-available-p))
18362 (user-error "LaTeX to MathML converter not configured"))
18363 (setq txt (match-string n)
18364 beg (match-beginning n) end (match-end n)
18365 cnt (1+ cnt))
18366 (if msg (message msg cnt))
18367 (goto-char beg)
18368 (delete-region beg end)
18369 (insert (org-format-latex-as-mathml
18370 txt block-type prefix dir)))
18372 (error "Unknown conversion type %s for LaTeX fragments"
18373 processing-type)))))))))
18375 (defun org-create-math-formula (latex-frag &optional mathml-file)
18376 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18377 Use `org-latex-to-mathml-convert-command'. If the conversion is
18378 sucessful, return the portion between \"<math...> </math>\"
18379 elements otherwise return nil. When MATHML-FILE is specified,
18380 write the results in to that file. When invoked as an
18381 interactive command, prompt for LATEX-FRAG, with initial value
18382 set to the current active region and echo the results for user
18383 inspection."
18384 (interactive (list (let ((frag (when (org-region-active-p)
18385 (buffer-substring-no-properties
18386 (region-beginning) (region-end)))))
18387 (read-string "LaTeX Fragment: " frag nil frag))))
18388 (unless latex-frag (error "Invalid LaTeX fragment"))
18389 (let* ((tmp-in-file (file-relative-name
18390 (make-temp-name (expand-file-name "ltxmathml-in"))))
18391 (ignore (write-region latex-frag nil tmp-in-file))
18392 (tmp-out-file (file-relative-name
18393 (make-temp-name (expand-file-name "ltxmathml-out"))))
18394 (cmd (format-spec
18395 org-latex-to-mathml-convert-command
18396 `((?j . ,(shell-quote-argument
18397 (expand-file-name org-latex-to-mathml-jar-file)))
18398 (?I . ,(shell-quote-argument tmp-in-file))
18399 (?o . ,(shell-quote-argument tmp-out-file)))))
18400 mathml shell-command-output)
18401 (when (org-called-interactively-p 'any)
18402 (unless (org-format-latex-mathml-available-p)
18403 (user-error "LaTeX to MathML converter not configured")))
18404 (message "Running %s" cmd)
18405 (setq shell-command-output (shell-command-to-string cmd))
18406 (setq mathml
18407 (when (file-readable-p tmp-out-file)
18408 (with-current-buffer (find-file-noselect tmp-out-file t)
18409 (goto-char (point-min))
18410 (when (re-search-forward
18411 (concat
18412 (regexp-quote
18413 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18414 "\\(.\\|\n\\)*"
18415 (regexp-quote "</math>")) nil t)
18416 (prog1 (match-string 0) (kill-buffer))))))
18417 (cond
18418 (mathml
18419 (setq mathml
18420 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18421 (when mathml-file
18422 (write-region mathml nil mathml-file))
18423 (when (org-called-interactively-p 'any)
18424 (message mathml)))
18425 ((message "LaTeX to MathML conversion failed")
18426 (message shell-command-output)))
18427 (delete-file tmp-in-file)
18428 (when (file-exists-p tmp-out-file)
18429 (delete-file tmp-out-file))
18430 mathml))
18432 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18433 prefix &optional dir)
18434 "Use `org-create-math-formula' but check local cache first."
18435 (let* ((absprefix (expand-file-name prefix dir))
18436 (print-length nil) (print-level nil)
18437 (formula-id (concat
18438 "formula-"
18439 (sha1
18440 (prin1-to-string
18441 (list latex-frag
18442 org-latex-to-mathml-convert-command)))))
18443 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18444 (formula-cache-dir (file-name-directory formula-cache)))
18446 (unless (file-directory-p formula-cache-dir)
18447 (make-directory formula-cache-dir t))
18449 (unless (file-exists-p formula-cache)
18450 (org-create-math-formula latex-frag formula-cache))
18452 (if (file-exists-p formula-cache)
18453 ;; Successful conversion. Return the link to MathML file.
18454 (org-add-props
18455 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18456 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18457 'org-latex-src-embed-type (if latex-frag-type
18458 'paragraph 'character)))
18459 ;; Failed conversion. Return the LaTeX fragment verbatim
18460 latex-frag)))
18462 (defun org-create-formula-image (string tofile options buffer &optional type)
18463 "Create an image from LaTeX source using dvipng or convert.
18464 This function calls either `org-create-formula-image-with-dvipng'
18465 or `org-create-formula-image-with-imagemagick' depending on the
18466 value of `org-latex-create-formula-image-program' or on the value
18467 of the optional TYPE variable.
18469 Note: ultimately these two function should be combined as they
18470 share a good deal of logic."
18471 (org-check-external-command
18472 "latex" "needed to convert LaTeX fragments to images")
18473 (funcall
18474 (case (or type org-latex-create-formula-image-program)
18475 ('dvipng
18476 (org-check-external-command
18477 "dvipng" "needed to convert LaTeX fragments to images")
18478 #'org-create-formula-image-with-dvipng)
18479 ('imagemagick
18480 (org-check-external-command
18481 "convert" "you need to install imagemagick")
18482 #'org-create-formula-image-with-imagemagick)
18483 (t (error
18484 "Invalid value of `org-latex-create-formula-image-program'")))
18485 string tofile options buffer))
18487 (declare-function org-export--get-global-options "ox" (&optional backend))
18488 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18489 (defun org-create-formula--latex-header ()
18490 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18491 (org-latex-guess-inputenc
18492 (org-splice-latex-header
18493 org-format-latex-header
18494 org-latex-default-packages-alist
18495 org-latex-packages-alist t
18496 (plist-get
18497 (org-combine-plists
18498 (org-export--get-global-options 'latex)
18499 (org-export--get-inbuffer-options 'latex))
18500 :latex-header))))
18502 ;; This function borrows from Ganesh Swami's latex2png.el
18503 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18504 "This calls dvipng."
18505 (require 'ox-latex)
18506 (let* ((tmpdir (if (featurep 'xemacs)
18507 (temp-directory)
18508 temporary-file-directory))
18509 (texfilebase (make-temp-name
18510 (expand-file-name "orgtex" tmpdir)))
18511 (texfile (concat texfilebase ".tex"))
18512 (dvifile (concat texfilebase ".dvi"))
18513 (pngfile (concat texfilebase ".png"))
18514 (fnh (if (featurep 'xemacs)
18515 (font-height (face-font 'default))
18516 (face-attribute 'default :height nil)))
18517 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18518 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18519 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18520 "Black"))
18521 (bg (or (plist-get options (if buffer :background :html-background))
18522 "Transparent")))
18523 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18524 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18525 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18526 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18527 (let ((latex-header (org-create-formula--latex-header)))
18528 (with-temp-file texfile
18529 (insert latex-header)
18530 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18531 (let ((dir default-directory))
18532 (condition-case nil
18533 (progn
18534 (cd tmpdir)
18535 (call-process "latex" nil nil nil texfile))
18536 (error nil))
18537 (cd dir))
18538 (if (not (file-exists-p dvifile))
18539 (progn (message "Failed to create dvi file from %s" texfile) nil)
18540 (condition-case nil
18541 (if (featurep 'xemacs)
18542 (call-process "dvipng" nil nil nil
18543 "-fg" fg "-bg" bg
18544 "-T" "tight"
18545 "-o" pngfile
18546 dvifile)
18547 (call-process "dvipng" nil nil nil
18548 "-fg" fg "-bg" bg
18549 "-D" dpi
18550 ;;"-x" scale "-y" scale
18551 "-T" "tight"
18552 "-o" pngfile
18553 dvifile))
18554 (error nil))
18555 (if (not (file-exists-p pngfile))
18556 (if org-format-latex-signal-error
18557 (error "Failed to create png file from %s" texfile)
18558 (message "Failed to create png file from %s" texfile)
18559 nil)
18560 ;; Use the requested file name and clean up
18561 (copy-file pngfile tofile 'replace)
18562 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18563 (if (file-exists-p (concat texfilebase e))
18564 (delete-file (concat texfilebase e))))
18565 pngfile))))
18567 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18568 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18569 "This calls convert, which is included into imagemagick."
18570 (require 'ox-latex)
18571 (let* ((tmpdir (if (featurep 'xemacs)
18572 (temp-directory)
18573 temporary-file-directory))
18574 (texfilebase (make-temp-name
18575 (expand-file-name "orgtex" tmpdir)))
18576 (texfile (concat texfilebase ".tex"))
18577 (pdffile (concat texfilebase ".pdf"))
18578 (pngfile (concat texfilebase ".png"))
18579 (fnh (if (featurep 'xemacs)
18580 (font-height (face-font 'default))
18581 (face-attribute 'default :height nil)))
18582 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18583 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18584 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18585 "black"))
18586 (bg (or (plist-get options (if buffer :background :html-background))
18587 "white")))
18588 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18589 (setq fg (org-latex-color-format fg)))
18590 (if (eq bg 'default) (setq bg (org-latex-color :background))
18591 (setq bg (org-latex-color-format
18592 (if (string= bg "Transparent") "white" bg))))
18593 (let ((latex-header (org-create-formula--latex-header)))
18594 (with-temp-file texfile
18595 (insert latex-header)
18596 (insert "\n\\begin{document}\n"
18597 "\\definecolor{fg}{rgb}{" fg "}\n"
18598 "\\definecolor{bg}{rgb}{" bg "}\n"
18599 "\n\\pagecolor{bg}\n"
18600 "\n{\\color{fg}\n"
18601 string
18602 "\n}\n"
18603 "\n\\end{document}\n")))
18604 (org-latex-compile texfile t)
18605 (if (not (file-exists-p pdffile))
18606 (progn (message "Failed to create pdf file from %s" texfile) nil)
18607 (condition-case nil
18608 (if (featurep 'xemacs)
18609 (call-process "convert" nil nil nil
18610 "-density" "96"
18611 "-trim"
18612 "-antialias"
18613 pdffile
18614 "-quality" "100"
18615 ;; "-sharpen" "0x1.0"
18616 pngfile)
18617 (call-process "convert" nil nil nil
18618 "-density" dpi
18619 "-trim"
18620 "-antialias"
18621 pdffile
18622 "-quality" "100"
18623 ;; "-sharpen" "0x1.0"
18624 pngfile))
18625 (error nil))
18626 (if (not (file-exists-p pngfile))
18627 (if org-format-latex-signal-error
18628 (error "Failed to create png file from %s" texfile)
18629 (message "Failed to create png file from %s" texfile)
18630 nil)
18631 ;; Use the requested file name and clean up
18632 (copy-file pngfile tofile 'replace)
18633 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18634 (if (file-exists-p (concat texfilebase e))
18635 (delete-file (concat texfilebase e))))
18636 pngfile))))
18638 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18639 "Fill a LaTeX header template TPL.
18640 In the template, the following place holders will be recognized:
18642 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18643 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18644 [PACKAGES] \\usepackage statements for PKG
18645 [NO-PACKAGES] do not include PKG
18646 [EXTRA] the string EXTRA
18647 [NO-EXTRA] do not include EXTRA
18649 For backward compatibility, if both the positive and the negative place
18650 holder is missing, the positive one (without the \"NO-\") will be
18651 assumed to be present at the end of the template.
18652 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18653 EXTRA is a string.
18654 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18655 (let (rpl (end ""))
18656 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18657 (setq rpl (if (or (match-end 1) (not def-pkg))
18658 "" (org-latex-packages-to-string def-pkg snippets-p t))
18659 tpl (replace-match rpl t t tpl))
18660 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18662 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18663 (setq rpl (if (or (match-end 1) (not pkg))
18664 "" (org-latex-packages-to-string pkg snippets-p t))
18665 tpl (replace-match rpl t t tpl))
18666 (if pkg (setq end
18667 (concat end "\n"
18668 (org-latex-packages-to-string pkg snippets-p)))))
18670 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18671 (setq rpl (if (or (match-end 1) (not extra))
18672 "" (concat extra "\n"))
18673 tpl (replace-match rpl t t tpl))
18674 (if (and extra (string-match "\\S-" extra))
18675 (setq end (concat end "\n" extra))))
18677 (if (string-match "\\S-" end)
18678 (concat tpl "\n" end)
18679 tpl)))
18681 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18682 "Turn an alist of packages into a string with the \\usepackage macros."
18683 (setq pkg (mapconcat (lambda(p)
18684 (cond
18685 ((stringp p) p)
18686 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18687 (format "%% Package %s omitted" (cadr p)))
18688 ((equal "" (car p))
18689 (format "\\usepackage{%s}" (cadr p)))
18691 (format "\\usepackage[%s]{%s}"
18692 (car p) (cadr p)))))
18694 "\n"))
18695 (if newline (concat pkg "\n") pkg))
18697 (defun org-dvipng-color (attr)
18698 "Return a RGB color specification for dvipng."
18699 (apply 'format "rgb %s %s %s"
18700 (mapcar 'org-normalize-color
18701 (if (featurep 'xemacs)
18702 (color-rgb-components
18703 (face-property 'default
18704 (cond ((eq attr :foreground) 'foreground)
18705 ((eq attr :background) 'background))))
18706 (color-values (face-attribute 'default attr nil))))))
18708 (defun org-dvipng-color-format (color-name)
18709 "Convert COLOR-NAME to a RGB color value for dvipng."
18710 (apply 'format "rgb %s %s %s"
18711 (mapcar 'org-normalize-color
18712 (color-values color-name))))
18714 (defun org-latex-color (attr)
18715 "Return a RGB color for the LaTeX color package."
18716 (apply 'format "%s,%s,%s"
18717 (mapcar 'org-normalize-color
18718 (if (featurep 'xemacs)
18719 (color-rgb-components
18720 (face-property 'default
18721 (cond ((eq attr :foreground) 'foreground)
18722 ((eq attr :background) 'background))))
18723 (color-values (face-attribute 'default attr nil))))))
18725 (defun org-latex-color-format (color-name)
18726 "Convert COLOR-NAME to a RGB color value."
18727 (apply 'format "%s,%s,%s"
18728 (mapcar 'org-normalize-color
18729 (color-values color-name))))
18731 (defun org-normalize-color (value)
18732 "Return string to be used as color value for an RGB component."
18733 (format "%g" (/ value 65535.0)))
18737 ;; Image display
18739 (defvar org-inline-image-overlays nil)
18740 (make-variable-buffer-local 'org-inline-image-overlays)
18742 (defun org-toggle-inline-images (&optional include-linked)
18743 "Toggle the display of inline images.
18744 INCLUDE-LINKED is passed to `org-display-inline-images'."
18745 (interactive "P")
18746 (if org-inline-image-overlays
18747 (progn
18748 (org-remove-inline-images)
18749 (message "Inline image display turned off"))
18750 (org-display-inline-images include-linked)
18751 (if (and (org-called-interactively-p)
18752 org-inline-image-overlays)
18753 (message "%d images displayed inline"
18754 (length org-inline-image-overlays))
18755 (message "No images to display inline"))))
18757 (defun org-redisplay-inline-images ()
18758 "Refresh the display of inline images."
18759 (interactive)
18760 (if (not org-inline-image-overlays)
18761 (org-toggle-inline-images)
18762 (org-toggle-inline-images)
18763 (org-toggle-inline-images)))
18765 (defun org-display-inline-images (&optional include-linked refresh beg end)
18766 "Display inline images.
18767 Normally only links without a description part are inlined, because this
18768 is how it will work for export. When INCLUDE-LINKED is set, also links
18769 with a description part will be inlined. This can be nice for a quick
18770 look at those images, but it does not reflect what exported files will look
18771 like.
18772 When REFRESH is set, refresh existing images between BEG and END.
18773 This will create new image displays only if necessary.
18774 BEG and END default to the buffer boundaries."
18775 (interactive "P")
18776 (unless refresh
18777 (org-remove-inline-images)
18778 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18779 (save-excursion
18780 (save-restriction
18781 (widen)
18782 (setq beg (or beg (point-min)) end (or end (point-max)))
18783 (goto-char beg)
18784 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18785 (substring (org-image-file-name-regexp) 0 -2)
18786 "\\)\\]" (if include-linked "" "\\]")))
18787 (case-fold-search t)
18788 old file ov img type attrwidth width)
18789 (while (re-search-forward re end t)
18790 (setq old (get-char-property-and-overlay (match-beginning 1)
18791 'org-image-overlay)
18792 file (expand-file-name
18793 (concat (or (match-string 3) "") (match-string 4))))
18794 (when (image-type-available-p 'imagemagick)
18795 (setq attrwidth (if (or (listp org-image-actual-width)
18796 (null org-image-actual-width))
18797 (save-excursion
18798 (save-match-data
18799 (when (re-search-backward
18800 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18801 (save-excursion
18802 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18803 (string-to-number (match-string 1))))))
18804 width (cond ((eq org-image-actual-width t) nil)
18805 ((null org-image-actual-width) attrwidth)
18806 ((numberp org-image-actual-width)
18807 org-image-actual-width)
18808 ((listp org-image-actual-width)
18809 (or attrwidth (car org-image-actual-width))))
18810 type (if width 'imagemagick)))
18811 (when (file-exists-p file)
18812 (if (and (car-safe old) refresh)
18813 (image-refresh (overlay-get (cdr old) 'display))
18814 (setq img (save-match-data (create-image file type nil :width width)))
18815 (when img
18816 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18817 (overlay-put ov 'display img)
18818 (overlay-put ov 'face 'default)
18819 (overlay-put ov 'org-image-overlay t)
18820 (overlay-put ov 'modification-hooks
18821 (list 'org-display-inline-remove-overlay))
18822 (push ov org-inline-image-overlays)))))))))
18824 (define-obsolete-function-alias
18825 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18827 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18828 "Remove inline-display overlay if a corresponding region is modified."
18829 (let ((inhibit-modification-hooks t))
18830 (when (and ov after)
18831 (delete ov org-inline-image-overlays)
18832 (delete-overlay ov))))
18834 (defun org-remove-inline-images ()
18835 "Remove inline display of images."
18836 (interactive)
18837 (mapc 'delete-overlay org-inline-image-overlays)
18838 (setq org-inline-image-overlays nil))
18840 ;;;; Key bindings
18842 ;; Outline functions from `outline-mode-prefix-map'
18843 ;; that can be remapped in Org:
18844 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18845 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18846 (define-key org-mode-map [remap outline-forward-same-level]
18847 'org-forward-heading-same-level)
18848 (define-key org-mode-map [remap outline-backward-same-level]
18849 'org-backward-heading-same-level)
18850 (define-key org-mode-map [remap show-branches]
18851 'org-kill-note-or-show-branches)
18852 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18853 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18854 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18856 ;; Outline functions from `outline-mode-prefix-map' that can not
18857 ;; be remapped in Org:
18859 ;; - the column "key binding" shows whether the Outline function is still
18860 ;; available in Org mode on the same key that it has been bound to in
18861 ;; Outline mode:
18862 ;; - "overridden": key used for a different functionality in Org mode
18863 ;; - else: key still bound to the same Outline function in Org mode
18865 ;; | Outline function | key binding | Org replacement |
18866 ;; |------------------------------------+-------------+-----------------------|
18867 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18868 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18869 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18870 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18871 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18872 ;; | `show-entry' | overridden | no replacement |
18873 ;; | `show-children' | `C-c C-i' | visibility cycling |
18874 ;; | `show-branches' | `C-c C-k' | still same function |
18875 ;; | `show-subtree' | overridden | visibility cycling |
18876 ;; | `show-all' | overridden | no replacement |
18877 ;; | `hide-subtree' | overridden | visibility cycling |
18878 ;; | `hide-body' | overridden | no replacement |
18879 ;; | `hide-entry' | overridden | visibility cycling |
18880 ;; | `hide-leaves' | overridden | no replacement |
18881 ;; | `hide-sublevels' | overridden | no replacement |
18882 ;; | `hide-other' | overridden | no replacement |
18884 ;; Make `C-c C-x' a prefix key
18885 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18887 ;; TAB key with modifiers
18888 (org-defkey org-mode-map "\C-i" 'org-cycle)
18889 (org-defkey org-mode-map [(tab)] 'org-cycle)
18890 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18891 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18892 ;; The following line is necessary under Suse GNU/Linux
18893 (unless (featurep 'xemacs)
18894 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18895 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18896 (define-key org-mode-map [backtab] 'org-shifttab)
18898 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18899 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18900 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18902 ;; Cursor keys with modifiers
18903 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18904 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18905 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18906 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18908 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18909 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18910 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18911 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18913 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18914 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18915 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18916 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18918 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18919 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18920 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18921 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18923 ;; Babel keys
18924 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18925 (mapc (lambda (pair)
18926 (define-key org-babel-map (car pair) (cdr pair)))
18927 org-babel-key-bindings)
18929 ;;; Extra keys for tty access.
18930 ;; We only set them when really needed because otherwise the
18931 ;; menus don't show the simple keys
18933 (when (or org-use-extra-keys
18934 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18935 (not window-system))
18936 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18937 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18938 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18939 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18940 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18941 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18942 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18943 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18944 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18945 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18946 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18947 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18948 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18949 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18950 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18951 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18952 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18953 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18954 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18955 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18956 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18957 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18958 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18959 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18960 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18961 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18962 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18963 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18965 ;; All the other keys
18967 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18968 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18969 (if (boundp 'narrow-map)
18970 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18971 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18972 (if (boundp 'narrow-map)
18973 (org-defkey narrow-map "b" 'org-narrow-to-block)
18974 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18975 (if (boundp 'narrow-map)
18976 (org-defkey narrow-map "e" 'org-narrow-to-element)
18977 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18978 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18979 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18980 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18981 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18982 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18983 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18984 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18985 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18986 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18987 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18988 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18989 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18990 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18991 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18992 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18993 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18994 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18995 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18996 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18997 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18998 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18999 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19000 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19001 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19002 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19003 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19004 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19005 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19006 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19007 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19008 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19009 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19010 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19011 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19012 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19013 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19014 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19015 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19016 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19017 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19018 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19019 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19020 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19021 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19022 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19023 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19024 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19025 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19026 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19027 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19028 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19029 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19030 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19031 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19032 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19033 (org-defkey org-mode-map "\C-c^" 'org-sort)
19034 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19035 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19036 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19037 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19038 (org-defkey org-mode-map "\C-m" 'org-return)
19039 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19040 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19041 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19042 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19043 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19044 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19045 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19046 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19047 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19048 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19049 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19050 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19051 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19052 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19053 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19054 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19055 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19056 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19057 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19058 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19059 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19060 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19061 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19063 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19064 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19065 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19067 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19068 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19069 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19070 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19071 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19072 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19073 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19074 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19075 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19076 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19077 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19078 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19079 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19080 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19081 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19082 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19083 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19084 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19085 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19086 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19087 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19088 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19089 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19091 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19092 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19093 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19094 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19095 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19097 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19099 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19101 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19102 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19104 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19107 (when (featurep 'xemacs)
19108 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19111 (defconst org-speed-commands-default
19113 ("Outline Navigation")
19114 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19115 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19116 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19117 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19118 ("F" . org-next-block)
19119 ("B" . org-previous-block)
19120 ("u" . (org-speed-move-safe 'outline-up-heading))
19121 ("j" . org-goto)
19122 ("g" . (org-refile t))
19123 ("Outline Visibility")
19124 ("c" . org-cycle)
19125 ("C" . org-shifttab)
19126 (" " . org-display-outline-path)
19127 ("s" . org-narrow-to-subtree)
19128 ("=" . org-columns)
19129 ("Outline Structure Editing")
19130 ("U" . org-shiftmetaup)
19131 ("D" . org-shiftmetadown)
19132 ("r" . org-metaright)
19133 ("l" . org-metaleft)
19134 ("R" . org-shiftmetaright)
19135 ("L" . org-shiftmetaleft)
19136 ("i" . (progn (forward-char 1) (call-interactively
19137 'org-insert-heading-respect-content)))
19138 ("^" . org-sort)
19139 ("w" . org-refile)
19140 ("a" . org-archive-subtree-default-with-confirmation)
19141 ("@" . org-mark-subtree)
19142 ("#" . org-toggle-comment)
19143 ("Clock Commands")
19144 ("I" . org-clock-in)
19145 ("O" . org-clock-out)
19146 ("Meta Data Editing")
19147 ("t" . org-todo)
19148 ("," . (org-priority))
19149 ("0" . (org-priority ?\ ))
19150 ("1" . (org-priority ?A))
19151 ("2" . (org-priority ?B))
19152 ("3" . (org-priority ?C))
19153 (":" . org-set-tags-command)
19154 ("e" . org-set-effort)
19155 ("E" . org-inc-effort)
19156 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19157 (org-entry-put (point) "APPT_WARNTIME" m)))
19158 ("Agenda Views etc")
19159 ("v" . org-agenda)
19160 ("/" . org-sparse-tree)
19161 ("Misc")
19162 ("o" . org-open-at-point)
19163 ("?" . org-speed-command-help)
19164 ("<" . (org-agenda-set-restriction-lock 'subtree))
19165 (">" . (org-agenda-remove-restriction-lock))
19167 "The default speed commands.")
19169 (defun org-print-speed-command (e)
19170 (if (> (length (car e)) 1)
19171 (progn
19172 (princ "\n")
19173 (princ (car e))
19174 (princ "\n")
19175 (princ (make-string (length (car e)) ?-))
19176 (princ "\n"))
19177 (princ (car e))
19178 (princ " ")
19179 (if (symbolp (cdr e))
19180 (princ (symbol-name (cdr e)))
19181 (prin1 (cdr e)))
19182 (princ "\n")))
19184 (defun org-speed-command-help ()
19185 "Show the available speed commands."
19186 (interactive)
19187 (if (not org-use-speed-commands)
19188 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19189 (with-output-to-temp-buffer "*Help*"
19190 (princ "User-defined Speed commands\n===========================\n")
19191 (mapc 'org-print-speed-command org-speed-commands-user)
19192 (princ "\n")
19193 (princ "Built-in Speed commands\n=======================\n")
19194 (mapc 'org-print-speed-command org-speed-commands-default))
19195 (with-current-buffer "*Help*"
19196 (setq truncate-lines t))))
19198 (defun org-speed-move-safe (cmd)
19199 "Execute CMD, but make sure that the cursor always ends up in a headline.
19200 If not, return to the original position and throw an error."
19201 (interactive)
19202 (let ((pos (point)))
19203 (call-interactively cmd)
19204 (unless (and (bolp) (org-at-heading-p))
19205 (goto-char pos)
19206 (error "Boundary reached while executing %s" cmd))))
19208 (defvar org-self-insert-command-undo-counter 0)
19210 (defvar org-table-auto-blank-field) ; defined in org-table.el
19211 (defvar org-speed-command nil)
19213 (define-obsolete-function-alias
19214 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19216 (defun org-speed-command-activate (keys)
19217 "Hook for activating single-letter speed commands.
19218 `org-speed-commands-default' specifies a minimal command set.
19219 Use `org-speed-commands-user' for further customization."
19220 (when (or (and (bolp) (looking-at org-outline-regexp))
19221 (and (functionp org-use-speed-commands)
19222 (funcall org-use-speed-commands)))
19223 (cdr (assoc keys (append org-speed-commands-user
19224 org-speed-commands-default)))))
19226 (define-obsolete-function-alias
19227 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19229 (defun org-babel-speed-command-activate (keys)
19230 "Hook for activating single-letter code block commands."
19231 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19232 (cdr (assoc keys org-babel-key-bindings))))
19234 (defcustom org-speed-command-hook
19235 '(org-speed-command-default-hook org-babel-speed-command-hook)
19236 "Hook for activating speed commands at strategic locations.
19237 Hook functions are called in sequence until a valid handler is
19238 found.
19240 Each hook takes a single argument, a user-pressed command key
19241 which is also a `self-insert-command' from the global map.
19243 Within the hook, examine the cursor position and the command key
19244 and return nil or a valid handler as appropriate. Handler could
19245 be one of an interactive command, a function, or a form.
19247 Set `org-use-speed-commands' to non-nil value to enable this
19248 hook. The default setting is `org-speed-command-activate'."
19249 :group 'org-structure
19250 :version "24.1"
19251 :type 'hook)
19253 (defun org-self-insert-command (N)
19254 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19255 If the cursor is in a table looking at whitespace, the whitespace is
19256 overwritten, and the table is not marked as requiring realignment."
19257 (interactive "p")
19258 (org-check-before-invisible-edit 'insert)
19259 (cond
19260 ((and org-use-speed-commands
19261 (setq org-speed-command
19262 (run-hook-with-args-until-success
19263 'org-speed-command-hook (this-command-keys))))
19264 (cond
19265 ((commandp org-speed-command)
19266 (setq this-command org-speed-command)
19267 (call-interactively org-speed-command))
19268 ((functionp org-speed-command)
19269 (funcall org-speed-command))
19270 ((and org-speed-command (listp org-speed-command))
19271 (eval org-speed-command))
19272 (t (let (org-use-speed-commands)
19273 (call-interactively 'org-self-insert-command)))))
19274 ((and
19275 (org-table-p)
19276 (progn
19277 ;; check if we blank the field, and if that triggers align
19278 (and (featurep 'org-table) org-table-auto-blank-field
19279 (member last-command
19280 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19281 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19282 ;; got extra space, this field does not determine column width
19283 (let (org-table-may-need-update) (org-table-blank-field))
19284 ;; no extra space, this field may determine column width
19285 (org-table-blank-field)))
19287 (eq N 1)
19288 (looking-at "[^|\n]* |"))
19289 (let (org-table-may-need-update)
19290 (goto-char (1- (match-end 0)))
19291 (backward-delete-char 1)
19292 (goto-char (match-beginning 0))
19293 (self-insert-command N)))
19295 (setq org-table-may-need-update t)
19296 (self-insert-command N)
19297 (org-fix-tags-on-the-fly)
19298 (if org-self-insert-cluster-for-undo
19299 (if (not (eq last-command 'org-self-insert-command))
19300 (setq org-self-insert-command-undo-counter 1)
19301 (if (>= org-self-insert-command-undo-counter 20)
19302 (setq org-self-insert-command-undo-counter 1)
19303 (and (> org-self-insert-command-undo-counter 0)
19304 buffer-undo-list (listp buffer-undo-list)
19305 (not (cadr buffer-undo-list)) ; remove nil entry
19306 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19307 (setq org-self-insert-command-undo-counter
19308 (1+ org-self-insert-command-undo-counter))))))))
19310 (defun org-check-before-invisible-edit (kind)
19311 "Check is editing if kind KIND would be dangerous with invisible text around.
19312 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19313 ;; First, try to get out of here as quickly as possible, to reduce overhead
19314 (if (and org-catch-invisible-edits
19315 (or (not (boundp 'visible-mode)) (not visible-mode))
19316 (or (get-char-property (point) 'invisible)
19317 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19318 ;; OK, we need to take a closer look
19319 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19320 (invisible-before-point (if (bobp) nil (get-char-property
19321 (1- (point)) 'invisible)))
19322 (border-and-ok-direction
19324 ;; Check if we are acting predictably before invisible text
19325 (and invisible-at-point (not invisible-before-point)
19326 (memq kind '(insert delete-backward)))
19327 ;; Check if we are acting predictably after invisible text
19328 ;; This works not well, and I have turned it off. It seems
19329 ;; better to always show and stop after invisible text.
19330 ;; (and (not invisible-at-point) invisible-before-point
19331 ;; (memq kind '(insert delete)))
19333 (when (or (memq invisible-at-point '(outline org-hide-block t))
19334 (memq invisible-before-point '(outline org-hide-block t)))
19335 (if (eq org-catch-invisible-edits 'error)
19336 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19337 (if (and org-custom-properties-overlays
19338 (y-or-n-p "Display invisible properties in this buffer? "))
19339 (org-toggle-custom-properties-visibility)
19340 ;; Make the area visible
19341 (save-excursion
19342 (if invisible-before-point
19343 (goto-char (previous-single-char-property-change
19344 (point) 'invisible)))
19345 (org-cycle))
19346 (cond
19347 ((eq org-catch-invisible-edits 'show)
19348 ;; That's it, we do the edit after showing
19349 (message
19350 "Unfolding invisible region around point before editing")
19351 (sit-for 1))
19352 ((and (eq org-catch-invisible-edits 'smart)
19353 border-and-ok-direction)
19354 (message "Unfolding invisible region around point before editing"))
19356 ;; Don't do the edit, make the user repeat it in full visibility
19357 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19359 (defun org-fix-tags-on-the-fly ()
19360 (when (and (equal (char-after (point-at-bol)) ?*)
19361 (org-at-heading-p))
19362 (org-align-tags-here org-tags-column)))
19364 (defun org-delete-backward-char (N)
19365 "Like `delete-backward-char', insert whitespace at field end in tables.
19366 When deleting backwards, in tables this function will insert whitespace in
19367 front of the next \"|\" separator, to keep the table aligned. The table will
19368 still be marked for re-alignment if the field did fill the entire column,
19369 because, in this case the deletion might narrow the column."
19370 (interactive "p")
19371 (save-match-data
19372 (org-check-before-invisible-edit 'delete-backward)
19373 (if (and (org-table-p)
19374 (eq N 1)
19375 (string-match "|" (buffer-substring (point-at-bol) (point)))
19376 (looking-at ".*?|"))
19377 (let ((pos (point))
19378 (noalign (looking-at "[^|\n\r]* |"))
19379 (c org-table-may-need-update))
19380 (backward-delete-char N)
19381 (if (not overwrite-mode)
19382 (progn
19383 (skip-chars-forward "^|")
19384 (insert " ")
19385 (goto-char (1- pos))))
19386 ;; noalign: if there were two spaces at the end, this field
19387 ;; does not determine the width of the column.
19388 (if noalign (setq org-table-may-need-update c)))
19389 (backward-delete-char N)
19390 (org-fix-tags-on-the-fly))))
19392 (defun org-delete-char (N)
19393 "Like `delete-char', but insert whitespace at field end in tables.
19394 When deleting characters, in tables this function will insert whitespace in
19395 front of the next \"|\" separator, to keep the table aligned. The table will
19396 still be marked for re-alignment if the field did fill the entire column,
19397 because, in this case the deletion might narrow the column."
19398 (interactive "p")
19399 (save-match-data
19400 (org-check-before-invisible-edit 'delete)
19401 (if (and (org-table-p)
19402 (not (bolp))
19403 (not (= (char-after) ?|))
19404 (eq N 1))
19405 (if (looking-at ".*?|")
19406 (let ((pos (point))
19407 (noalign (looking-at "[^|\n\r]* |"))
19408 (c org-table-may-need-update))
19409 (replace-match
19410 (concat (substring (match-string 0) 1 -1) " |") nil t)
19411 (goto-char pos)
19412 ;; noalign: if there were two spaces at the end, this field
19413 ;; does not determine the width of the column.
19414 (if noalign (setq org-table-may-need-update c)))
19415 (delete-char N))
19416 (delete-char N)
19417 (org-fix-tags-on-the-fly))))
19419 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19420 (put 'org-self-insert-command 'delete-selection t)
19421 (put 'orgtbl-self-insert-command 'delete-selection t)
19422 (put 'org-delete-char 'delete-selection 'supersede)
19423 (put 'org-delete-backward-char 'delete-selection 'supersede)
19424 (put 'org-yank 'delete-selection 'yank)
19426 ;; Make `flyspell-mode' delay after some commands
19427 (put 'org-self-insert-command 'flyspell-delayed t)
19428 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19429 (put 'org-delete-char 'flyspell-delayed t)
19430 (put 'org-delete-backward-char 'flyspell-delayed t)
19432 ;; Make pabbrev-mode expand after org-mode commands
19433 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19434 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19436 ;; How to do this: Measure non-white length of current string
19437 ;; If equal to column width, we should realign.
19439 (defun org-remap (map &rest commands)
19440 "In MAP, remap the functions given in COMMANDS.
19441 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19442 (let (new old)
19443 (while commands
19444 (setq old (pop commands) new (pop commands))
19445 (if (fboundp 'command-remapping)
19446 (org-defkey map (vector 'remap old) new)
19447 (substitute-key-definition old new map global-map)))))
19449 (defun org-transpose-words ()
19450 "Transpose words for Org.
19451 This uses the `org-mode-transpose-word-syntax-table' syntax
19452 table, which interprets characters in `org-emphasis-alist' as
19453 word constituants."
19454 (interactive)
19455 (with-syntax-table org-mode-transpose-word-syntax-table
19456 (call-interactively 'transpose-words)))
19457 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19459 (when (eq org-enable-table-editor 'optimized)
19460 ;; If the user wants maximum table support, we need to hijack
19461 ;; some standard editing functions
19462 (org-remap org-mode-map
19463 'self-insert-command 'org-self-insert-command
19464 'delete-char 'org-delete-char
19465 'delete-backward-char 'org-delete-backward-char)
19466 (org-defkey org-mode-map "|" 'org-force-self-insert))
19468 (defvar org-ctrl-c-ctrl-c-hook nil
19469 "Hook for functions attaching themselves to `C-c C-c'.
19471 This can be used to add additional functionality to the C-c C-c
19472 key which executes context-dependent commands. This hook is run
19473 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19474 run after the last test.
19476 Each function will be called with no arguments. The function
19477 must check if the context is appropriate for it to act. If yes,
19478 it should do its thing and then return a non-nil value. If the
19479 context is wrong, just do nothing and return nil.")
19481 (defvar org-ctrl-c-ctrl-c-final-hook nil
19482 "Hook for functions attaching themselves to `C-c C-c'.
19484 This can be used to add additional functionality to the C-c C-c
19485 key which executes context-dependent commands. This hook is run
19486 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19487 before the first test.
19489 Each function will be called with no arguments. The function
19490 must check if the context is appropriate for it to act. If yes,
19491 it should do its thing and then return a non-nil value. If the
19492 context is wrong, just do nothing and return nil.")
19494 (defvar org-tab-first-hook nil
19495 "Hook for functions to attach themselves to TAB.
19496 See `org-ctrl-c-ctrl-c-hook' for more information.
19497 This hook runs as the first action when TAB is pressed, even before
19498 `org-cycle' messes around with the `outline-regexp' to cater for
19499 inline tasks and plain list item folding.
19500 If any function in this hook returns t, any other actions that
19501 would have been caused by TAB (such as table field motion or visibility
19502 cycling) will not occur.")
19504 (defvar org-tab-after-check-for-table-hook nil
19505 "Hook for functions to attach themselves to TAB.
19506 See `org-ctrl-c-ctrl-c-hook' for more information.
19507 This hook runs after it has been established that the cursor is not in a
19508 table, but before checking if the cursor is in a headline or if global cycling
19509 should be done.
19510 If any function in this hook returns t, not other actions like visibility
19511 cycling will be done.")
19513 (defvar org-tab-after-check-for-cycling-hook nil
19514 "Hook for functions to attach themselves to TAB.
19515 See `org-ctrl-c-ctrl-c-hook' for more information.
19516 This hook runs after it has been established that not table field motion and
19517 not visibility should be done because of current context. This is probably
19518 the place where a package like yasnippets can hook in.")
19520 (defvar org-tab-before-tab-emulation-hook nil
19521 "Hook for functions to attach themselves to TAB.
19522 See `org-ctrl-c-ctrl-c-hook' for more information.
19523 This hook runs after every other options for TAB have been exhausted, but
19524 before indentation and \t insertion takes place.")
19526 (defvar org-metaleft-hook nil
19527 "Hook for functions attaching themselves to `M-left'.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.")
19529 (defvar org-metaright-hook nil
19530 "Hook for functions attaching themselves to `M-right'.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-metaup-hook nil
19533 "Hook for functions attaching themselves to `M-up'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-metadown-hook nil
19536 "Hook for functions attaching themselves to `M-down'.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.")
19538 (defvar org-shiftmetaleft-hook nil
19539 "Hook for functions attaching themselves to `M-S-left'.
19540 See `org-ctrl-c-ctrl-c-hook' for more information.")
19541 (defvar org-shiftmetaright-hook nil
19542 "Hook for functions attaching themselves to `M-S-right'.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftmetaup-hook nil
19545 "Hook for functions attaching themselves to `M-S-up'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftmetadown-hook nil
19548 "Hook for functions attaching themselves to `M-S-down'.
19549 See `org-ctrl-c-ctrl-c-hook' for more information.")
19550 (defvar org-metareturn-hook nil
19551 "Hook for functions attaching themselves to `M-RET'.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19553 (defvar org-shiftup-hook nil
19554 "Hook for functions attaching themselves to `S-up'.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-shiftup-final-hook nil
19557 "Hook for functions attaching themselves to `S-up'.
19558 This one runs after all other options except shift-select have been excluded.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.")
19560 (defvar org-shiftdown-hook nil
19561 "Hook for functions attaching themselves to `S-down'.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19563 (defvar org-shiftdown-final-hook nil
19564 "Hook for functions attaching themselves to `S-down'.
19565 This one runs after all other options except shift-select have been excluded.
19566 See `org-ctrl-c-ctrl-c-hook' for more information.")
19567 (defvar org-shiftleft-hook nil
19568 "Hook for functions attaching themselves to `S-left'.
19569 See `org-ctrl-c-ctrl-c-hook' for more information.")
19570 (defvar org-shiftleft-final-hook nil
19571 "Hook for functions attaching themselves to `S-left'.
19572 This one runs after all other options except shift-select have been excluded.
19573 See `org-ctrl-c-ctrl-c-hook' for more information.")
19574 (defvar org-shiftright-hook nil
19575 "Hook for functions attaching themselves to `S-right'.
19576 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defvar org-shiftright-final-hook nil
19578 "Hook for functions attaching themselves to `S-right'.
19579 This one runs after all other options except shift-select have been excluded.
19580 See `org-ctrl-c-ctrl-c-hook' for more information.")
19582 (defun org-modifier-cursor-error ()
19583 "Throw an error, a modified cursor command was applied in wrong context."
19584 (user-error "This command is active in special context like tables, headlines or items"))
19586 (defun org-shiftselect-error ()
19587 "Throw an error because Shift-Cursor command was applied in wrong context."
19588 (if (and (boundp 'shift-select-mode) shift-select-mode)
19589 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19590 (user-error "This command works only in special context like headlines or timestamps")))
19592 (defun org-call-for-shift-select (cmd)
19593 (let ((this-command-keys-shift-translated t))
19594 (call-interactively cmd)))
19596 (defun org-shifttab (&optional arg)
19597 "Global visibility cycling or move to previous table field.
19598 Call `org-table-previous-field' within a table.
19599 When ARG is nil, cycle globally through visibility states.
19600 When ARG is a numeric prefix, show contents of this level."
19601 (interactive "P")
19602 (cond
19603 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19604 ((integerp arg)
19605 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19606 (message "Content view to level: %d" arg)
19607 (org-content (prefix-numeric-value arg2))
19608 (org-cycle-show-empty-lines t)
19609 (setq org-cycle-global-status 'overview)))
19610 (t (call-interactively 'org-global-cycle))))
19612 (defun org-shiftmetaleft ()
19613 "Promote subtree or delete table column.
19614 Calls `org-promote-subtree', `org-outdent-item-tree', or
19615 `org-table-delete-column', depending on context. See the
19616 individual commands for more information."
19617 (interactive)
19618 (cond
19619 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19620 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19621 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19622 ((if (not (org-region-active-p)) (org-at-item-p)
19623 (save-excursion (goto-char (region-beginning))
19624 (org-at-item-p)))
19625 (call-interactively 'org-outdent-item-tree))
19626 (t (org-modifier-cursor-error))))
19628 (defun org-shiftmetaright ()
19629 "Demote subtree or insert table column.
19630 Calls `org-demote-subtree', `org-indent-item-tree', or
19631 `org-table-insert-column', depending on context. See the
19632 individual commands for more information."
19633 (interactive)
19634 (cond
19635 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19636 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19637 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19638 ((if (not (org-region-active-p)) (org-at-item-p)
19639 (save-excursion (goto-char (region-beginning))
19640 (org-at-item-p)))
19641 (call-interactively 'org-indent-item-tree))
19642 (t (org-modifier-cursor-error))))
19644 (defun org-shiftmetaup (&optional arg)
19645 "Move subtree up or kill table row.
19646 Calls `org-move-subtree-up' or `org-table-kill-row' or
19647 `org-move-item-up' or `org-timestamp-up', depending on context.
19648 See the individual commands for more information."
19649 (interactive "P")
19650 (cond
19651 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19652 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19653 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19654 ((org-at-item-p) (call-interactively 'org-move-item-up))
19655 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19656 (call-interactively 'org-timestamp-up)))
19657 (t (call-interactively 'org-drag-line-backward))))
19659 (defun org-shiftmetadown (&optional arg)
19660 "Move subtree down or insert table row.
19661 Calls `org-move-subtree-down' or `org-table-insert-row' or
19662 `org-move-item-down' or `org-timestamp-up', depending on context.
19663 See the individual commands for more information."
19664 (interactive "P")
19665 (cond
19666 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19667 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19668 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19669 ((org-at-item-p) (call-interactively 'org-move-item-down))
19670 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19671 (call-interactively 'org-timestamp-down)))
19672 (t (call-interactively 'org-drag-line-forward))))
19674 (defsubst org-hidden-tree-error ()
19675 (user-error
19676 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19678 (defun org-metaleft (&optional arg)
19679 "Promote heading or move table column to left.
19680 Calls `org-do-promote' or `org-table-move-column', depending on context.
19681 With no specific context, calls the Emacs default `backward-word'.
19682 See the individual commands for more information."
19683 (interactive "P")
19684 (cond
19685 ((run-hook-with-args-until-success 'org-metaleft-hook))
19686 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19687 ((org-with-limited-levels
19688 (or (org-at-heading-p)
19689 (and (org-region-active-p)
19690 (save-excursion
19691 (goto-char (region-beginning))
19692 (org-at-heading-p)))))
19693 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19694 (call-interactively 'org-do-promote))
19695 ;; At an inline task.
19696 ((org-at-heading-p)
19697 (call-interactively 'org-inlinetask-promote))
19698 ((or (org-at-item-p)
19699 (and (org-region-active-p)
19700 (save-excursion
19701 (goto-char (region-beginning))
19702 (org-at-item-p))))
19703 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19704 (call-interactively 'org-outdent-item))
19705 (t (call-interactively 'backward-word))))
19707 (defun org-metaright (&optional arg)
19708 "Demote a subtree, a list item or move table column to right.
19709 In front of a drawer or a block keyword, indent it correctly.
19710 With no specific context, calls the Emacs default `forward-word'.
19711 See the individual commands for more information."
19712 (interactive "P")
19713 (cond
19714 ((run-hook-with-args-until-success 'org-metaright-hook))
19715 ((org-at-table-p) (call-interactively 'org-table-move-column))
19716 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19717 ((org-at-block-p) (call-interactively 'org-indent-block))
19718 ((org-with-limited-levels
19719 (or (org-at-heading-p)
19720 (and (org-region-active-p)
19721 (save-excursion
19722 (goto-char (region-beginning))
19723 (org-at-heading-p)))))
19724 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19725 (call-interactively 'org-do-demote))
19726 ;; At an inline task.
19727 ((org-at-heading-p)
19728 (call-interactively 'org-inlinetask-demote))
19729 ((or (org-at-item-p)
19730 (and (org-region-active-p)
19731 (save-excursion
19732 (goto-char (region-beginning))
19733 (org-at-item-p))))
19734 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19735 (call-interactively 'org-indent-item))
19736 (t (call-interactively 'forward-word))))
19738 (defun org-check-for-hidden (what)
19739 "Check if there are hidden headlines/items in the current visual line.
19740 WHAT can be either `headlines' or `items'. If the current line is
19741 an outline or item heading and it has a folded subtree below it,
19742 this function returns t, nil otherwise."
19743 (let ((re (cond
19744 ((eq what 'headlines) org-outline-regexp-bol)
19745 ((eq what 'items) (org-item-beginning-re))
19746 (t (error "This should not happen"))))
19747 beg end)
19748 (save-excursion
19749 (catch 'exit
19750 (unless (org-region-active-p)
19751 (setq beg (point-at-bol))
19752 (beginning-of-line 2)
19753 (while (and (not (eobp)) ;; this is like `next-line'
19754 (get-char-property (1- (point)) 'invisible))
19755 (beginning-of-line 2))
19756 (setq end (point))
19757 (goto-char beg)
19758 (goto-char (point-at-eol))
19759 (setq end (max end (point)))
19760 (while (re-search-forward re end t)
19761 (if (get-char-property (match-beginning 0) 'invisible)
19762 (throw 'exit t))))
19763 nil))))
19765 (defun org-metaup (&optional arg)
19766 "Move subtree up or move table row up.
19767 Calls `org-move-subtree-up' or `org-table-move-row' or
19768 `org-move-item-up', depending on context. See the individual commands
19769 for more information."
19770 (interactive "P")
19771 (cond
19772 ((run-hook-with-args-until-success 'org-metaup-hook))
19773 ((org-region-active-p)
19774 (let* ((a (min (region-beginning) (region-end)))
19775 (b (1- (max (region-beginning) (region-end))))
19776 (c (save-excursion (goto-char a)
19777 (move-beginning-of-line 0)))
19778 (d (save-excursion (goto-char a)
19779 (move-end-of-line 0) (point))))
19780 (transpose-regions a b c d)
19781 (goto-char c)))
19782 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19783 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19784 ((org-at-item-p) (call-interactively 'org-move-item-up))
19785 (t (org-drag-element-backward))))
19787 (defun org-metadown (&optional arg)
19788 "Move subtree down or move table row down.
19789 Calls `org-move-subtree-down' or `org-table-move-row' or
19790 `org-move-item-down', depending on context. See the individual
19791 commands for more information."
19792 (interactive "P")
19793 (cond
19794 ((run-hook-with-args-until-success 'org-metadown-hook))
19795 ((org-region-active-p)
19796 (let* ((a (min (region-beginning) (region-end)))
19797 (b (max (region-beginning) (region-end)))
19798 (c (save-excursion (goto-char b)
19799 (move-beginning-of-line 1)))
19800 (d (save-excursion (goto-char b)
19801 (move-end-of-line 1) (1+ (point)))))
19802 (transpose-regions a b c d)
19803 (goto-char d)))
19804 ((org-at-table-p) (call-interactively 'org-table-move-row))
19805 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19806 ((org-at-item-p) (call-interactively 'org-move-item-down))
19807 (t (org-drag-element-forward))))
19809 (defun org-shiftup (&optional arg)
19810 "Increase item in timestamp or increase priority of current headline.
19811 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19812 depending on context. See the individual commands for more information."
19813 (interactive "P")
19814 (cond
19815 ((run-hook-with-args-until-success 'org-shiftup-hook))
19816 ((and org-support-shift-select (org-region-active-p))
19817 (org-call-for-shift-select 'previous-line))
19818 ((org-at-timestamp-p t)
19819 (call-interactively (if org-edit-timestamp-down-means-later
19820 'org-timestamp-down 'org-timestamp-up)))
19821 ((and (not (eq org-support-shift-select 'always))
19822 org-enable-priority-commands
19823 (org-at-heading-p))
19824 (call-interactively 'org-priority-up))
19825 ((and (not org-support-shift-select) (org-at-item-p))
19826 (call-interactively 'org-previous-item))
19827 ((org-clocktable-try-shift 'up arg))
19828 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19829 (org-support-shift-select
19830 (org-call-for-shift-select 'previous-line))
19831 (t (org-shiftselect-error))))
19833 (defun org-shiftdown (&optional arg)
19834 "Decrease item in timestamp or decrease priority of current headline.
19835 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19836 depending on context. See the individual commands for more information."
19837 (interactive "P")
19838 (cond
19839 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19840 ((and org-support-shift-select (org-region-active-p))
19841 (org-call-for-shift-select 'next-line))
19842 ((org-at-timestamp-p t)
19843 (call-interactively (if org-edit-timestamp-down-means-later
19844 'org-timestamp-up 'org-timestamp-down)))
19845 ((and (not (eq org-support-shift-select 'always))
19846 org-enable-priority-commands
19847 (org-at-heading-p))
19848 (call-interactively 'org-priority-down))
19849 ((and (not org-support-shift-select) (org-at-item-p))
19850 (call-interactively 'org-next-item))
19851 ((org-clocktable-try-shift 'down arg))
19852 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19853 (org-support-shift-select
19854 (org-call-for-shift-select 'next-line))
19855 (t (org-shiftselect-error))))
19857 (defun org-shiftright (&optional arg)
19858 "Cycle the thing at point or in the current line, depending on context.
19859 Depending on context, this does one of the following:
19861 - switch a timestamp at point one day into the future
19862 - on a headline, switch to the next TODO keyword.
19863 - on an item, switch entire list to the next bullet type
19864 - on a property line, switch to the next allowed value
19865 - on a clocktable definition line, move time block into the future"
19866 (interactive "P")
19867 (cond
19868 ((run-hook-with-args-until-success 'org-shiftright-hook))
19869 ((and org-support-shift-select (org-region-active-p))
19870 (org-call-for-shift-select 'forward-char))
19871 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19872 ((and (not (eq org-support-shift-select 'always))
19873 (org-at-heading-p))
19874 (let ((org-inhibit-logging
19875 (not org-treat-S-cursor-todo-selection-as-state-change))
19876 (org-inhibit-blocking
19877 (not org-treat-S-cursor-todo-selection-as-state-change)))
19878 (org-call-with-arg 'org-todo 'right)))
19879 ((or (and org-support-shift-select
19880 (not (eq org-support-shift-select 'always))
19881 (org-at-item-bullet-p))
19882 (and (not org-support-shift-select) (org-at-item-p)))
19883 (org-call-with-arg 'org-cycle-list-bullet nil))
19884 ((and (not (eq org-support-shift-select 'always))
19885 (org-at-property-p))
19886 (call-interactively 'org-property-next-allowed-value))
19887 ((org-clocktable-try-shift 'right arg))
19888 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19889 (org-support-shift-select
19890 (org-call-for-shift-select 'forward-char))
19891 (t (org-shiftselect-error))))
19893 (defun org-shiftleft (&optional arg)
19894 "Cycle the thing at point or in the current line, depending on context.
19895 Depending on context, this does one of the following:
19897 - switch a timestamp at point one day into the past
19898 - on a headline, switch to the previous TODO keyword.
19899 - on an item, switch entire list to the previous bullet type
19900 - on a property line, switch to the previous allowed value
19901 - on a clocktable definition line, move time block into the past"
19902 (interactive "P")
19903 (cond
19904 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19905 ((and org-support-shift-select (org-region-active-p))
19906 (org-call-for-shift-select 'backward-char))
19907 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19908 ((and (not (eq org-support-shift-select 'always))
19909 (org-at-heading-p))
19910 (let ((org-inhibit-logging
19911 (not org-treat-S-cursor-todo-selection-as-state-change))
19912 (org-inhibit-blocking
19913 (not org-treat-S-cursor-todo-selection-as-state-change)))
19914 (org-call-with-arg 'org-todo 'left)))
19915 ((or (and org-support-shift-select
19916 (not (eq org-support-shift-select 'always))
19917 (org-at-item-bullet-p))
19918 (and (not org-support-shift-select) (org-at-item-p)))
19919 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19920 ((and (not (eq org-support-shift-select 'always))
19921 (org-at-property-p))
19922 (call-interactively 'org-property-previous-allowed-value))
19923 ((org-clocktable-try-shift 'left arg))
19924 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19925 (org-support-shift-select
19926 (org-call-for-shift-select 'backward-char))
19927 (t (org-shiftselect-error))))
19929 (defun org-shiftcontrolright ()
19930 "Switch to next TODO set."
19931 (interactive)
19932 (cond
19933 ((and org-support-shift-select (org-region-active-p))
19934 (org-call-for-shift-select 'forward-word))
19935 ((and (not (eq org-support-shift-select 'always))
19936 (org-at-heading-p))
19937 (org-call-with-arg 'org-todo 'nextset))
19938 (org-support-shift-select
19939 (org-call-for-shift-select 'forward-word))
19940 (t (org-shiftselect-error))))
19942 (defun org-shiftcontrolleft ()
19943 "Switch to previous TODO set."
19944 (interactive)
19945 (cond
19946 ((and org-support-shift-select (org-region-active-p))
19947 (org-call-for-shift-select 'backward-word))
19948 ((and (not (eq org-support-shift-select 'always))
19949 (org-at-heading-p))
19950 (org-call-with-arg 'org-todo 'previousset))
19951 (org-support-shift-select
19952 (org-call-for-shift-select 'backward-word))
19953 (t (org-shiftselect-error))))
19955 (defun org-shiftcontrolup (&optional n)
19956 "Change timestamps synchronously up in CLOCK log lines.
19957 Optional argument N tells to change by that many units."
19958 (interactive "P")
19959 (cond ((and (not org-support-shift-select)
19960 (org-at-clock-log-p)
19961 (org-at-timestamp-p t))
19962 (org-clock-timestamps-up n))
19963 (t (org-shiftselect-error))))
19965 (defun org-shiftcontroldown (&optional n)
19966 "Change timestamps synchronously down in CLOCK log lines.
19967 Optional argument N tells to change by that many units."
19968 (interactive "P")
19969 (cond ((and (not org-support-shift-select)
19970 (org-at-clock-log-p)
19971 (org-at-timestamp-p t))
19972 (org-clock-timestamps-down n))
19973 (t (org-shiftselect-error))))
19975 (defun org-ctrl-c-ret ()
19976 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19977 (interactive)
19978 (cond
19979 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19980 (t (call-interactively 'org-insert-heading))))
19982 (defun org-find-visible ()
19983 (let ((s (point)))
19984 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19985 (get-char-property s 'invisible)))
19987 (defun org-find-invisible ()
19988 (let ((s (point)))
19989 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19990 (not (get-char-property s 'invisible))))
19993 (defun org-copy-visible (beg end)
19994 "Copy the visible parts of the region."
19995 (interactive "r")
19996 (let (snippets s)
19997 (save-excursion
19998 (save-restriction
19999 (narrow-to-region beg end)
20000 (setq s (goto-char (point-min)))
20001 (while (not (= (point) (point-max)))
20002 (goto-char (org-find-invisible))
20003 (push (buffer-substring s (point)) snippets)
20004 (setq s (goto-char (org-find-visible))))))
20005 (kill-new (apply 'concat (nreverse snippets)))))
20007 (defun org-copy-special ()
20008 "Copy region in table or copy current subtree.
20009 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20010 See the individual commands for more information."
20011 (interactive)
20012 (call-interactively
20013 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20015 (defun org-cut-special ()
20016 "Cut region in table or cut current subtree.
20017 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20018 See the individual commands for more information."
20019 (interactive)
20020 (call-interactively
20021 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20023 (defun org-paste-special (arg)
20024 "Paste rectangular region into table, or past subtree relative to level.
20025 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20026 See the individual commands for more information."
20027 (interactive "P")
20028 (if (org-at-table-p)
20029 (org-table-paste-rectangle)
20030 (org-paste-subtree arg)))
20032 (defsubst org-in-fixed-width-region-p ()
20033 "Is point in a fixed-width region?"
20034 (save-match-data
20035 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20037 (defun org-edit-special (&optional arg)
20038 "Call a special editor for the element at point.
20039 When at a table, call the formula editor with `org-table-edit-formulas'.
20040 When in a source code block, call `org-edit-src-code'.
20041 When in a fixed-width region, call `org-edit-fixed-width-region'.
20042 When at an #+INCLUDE keyword, visit the included file.
20043 On a link, call `ffap' to visit the link at point.
20044 Otherwise, return a user error."
20045 (interactive "P")
20046 (let ((element (org-element-at-point)))
20047 (assert (not buffer-read-only) nil
20048 "Buffer is read-only: %s" (buffer-name))
20049 (case (org-element-type element)
20050 (src-block
20051 (if (not arg) (org-edit-src-code)
20052 (let* ((info (org-babel-get-src-block-info))
20053 (lang (nth 0 info))
20054 (params (nth 2 info))
20055 (session (cdr (assq :session params))))
20056 (if (not session) (org-edit-src-code)
20057 ;; At a src-block with a session and function called with
20058 ;; an ARG: switch to the buffer related to the inferior
20059 ;; process.
20060 (switch-to-buffer
20061 (funcall (intern (concat "org-babel-prep-session:" lang))
20062 session params))))))
20063 (keyword
20064 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20065 (find-file
20066 (org-remove-double-quotes
20067 (car (org-split-string (org-element-property :value element)))))
20068 (user-error "No special environment to edit here")))
20069 (table
20070 (if (eq (org-element-property :type element) 'table.el)
20071 (org-edit-src-code)
20072 (call-interactively 'org-table-edit-formulas)))
20073 ;; Only Org tables contain `table-row' type elements.
20074 (table-row (call-interactively 'org-table-edit-formulas))
20075 ((example-block export-block) (org-edit-src-code))
20076 (fixed-width (org-edit-fixed-width-region))
20077 (otherwise
20078 ;; No notable element at point. Though, we may be at a link,
20079 ;; which is an object. Thus, scan deeper.
20080 (if (eq (org-element-type (org-element-context element)) 'link)
20081 (call-interactively 'ffap)
20082 (user-error "No special environment to edit here"))))))
20084 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20085 (defun org-ctrl-c-ctrl-c (&optional arg)
20086 "Set tags in headline, or update according to changed information at point.
20088 This command does many different things, depending on context:
20090 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20091 this is what we do.
20093 - If the cursor is on a statistics cookie, update it.
20095 - If the cursor is in a headline, prompt for tags and insert them
20096 into the current line, aligned to `org-tags-column'. When called
20097 with prefix arg, realign all tags in the current buffer.
20099 - If the cursor is in one of the special #+KEYWORD lines, this
20100 triggers scanning the buffer for these lines and updating the
20101 information.
20103 - If the cursor is inside a table, realign the table. This command
20104 works even if the automatic table editor has been turned off.
20106 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20107 the entire table.
20109 - If the cursor is at a footnote reference or definition, jump to
20110 the corresponding definition or references, respectively.
20112 - If the cursor is a the beginning of a dynamic block, update it.
20114 - If the current buffer is a capture buffer, close note and file it.
20116 - If the cursor is on a <<<target>>>, update radio targets and
20117 corresponding links in this buffer.
20119 - If the cursor is on a numbered item in a plain list, renumber the
20120 ordered list.
20122 - If the cursor is on a checkbox, toggle it.
20124 - If the cursor is on a code block, evaluate it. The variable
20125 `org-confirm-babel-evaluate' can be used to control prompting
20126 before code block evaluation, by default every code block
20127 evaluation requires confirmation. Code block evaluation can be
20128 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20129 (interactive "P")
20130 (cond
20131 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20132 org-occur-highlights
20133 org-latex-fragment-image-overlays)
20134 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20135 (org-remove-occur-highlights)
20136 (org-remove-latex-fragment-image-overlays)
20137 (message "Temporary highlights/overlays removed from current buffer"))
20138 ((and (local-variable-p 'org-finish-function (current-buffer))
20139 (fboundp org-finish-function))
20140 (funcall org-finish-function))
20141 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20143 (let* ((context (org-element-context)) (type (org-element-type context)))
20144 ;; Test if point is within a blank line.
20145 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20146 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20147 (user-error "C-c C-c can do nothing useful at this location"))
20148 ;; For convenience: at the first line of a paragraph on the
20149 ;; same line as an item, apply function on that item instead.
20150 (when (eq type 'paragraph)
20151 (let ((parent (org-element-property :parent context)))
20152 (when (and (eq (org-element-type parent) 'item)
20153 (= (point-at-bol) (org-element-property :begin parent)))
20154 (setq context parent type 'item))))
20155 ;; Act according to type of element or object at point.
20156 (case type
20157 (clock (org-clock-update-time-maybe))
20158 (dynamic-block
20159 (save-excursion
20160 (goto-char (org-element-property :post-affiliated context))
20161 (org-update-dblock)))
20162 (footnote-definition
20163 (goto-char (org-element-property :post-affiliated context))
20164 (call-interactively 'org-footnote-action))
20165 (footnote-reference (call-interactively 'org-footnote-action))
20166 ((headline inlinetask)
20167 (save-excursion (goto-char (org-element-property :begin context))
20168 (call-interactively 'org-set-tags)))
20169 (item
20170 ;; At an item: a double C-u set checkbox to "[-]"
20171 ;; unconditionally, whereas a single one will toggle its
20172 ;; presence. Without an universal argument, if the item
20173 ;; has a checkbox, toggle it. Otherwise repair the list.
20174 (let* ((box (org-element-property :checkbox context))
20175 (struct (org-element-property :structure context))
20176 (old-struct (copy-tree struct))
20177 (parents (org-list-parents-alist struct))
20178 (prevs (org-list-prevs-alist struct))
20179 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20180 (org-list-set-checkbox
20181 (org-element-property :begin context) struct
20182 (cond ((equal arg '(16)) "[-]")
20183 ((and (not box) (equal arg '(4))) "[ ]")
20184 ((or (not box) (equal arg '(4))) nil)
20185 ((eq box 'on) "[ ]")
20186 (t "[X]")))
20187 ;; Mimic `org-list-write-struct' but with grabbing
20188 ;; a return value from `org-list-struct-fix-box'.
20189 (org-list-struct-fix-ind struct parents 2)
20190 (org-list-struct-fix-item-end struct)
20191 (org-list-struct-fix-bul struct prevs)
20192 (org-list-struct-fix-ind struct parents)
20193 (let ((block-item
20194 (org-list-struct-fix-box struct parents prevs orderedp)))
20195 (if (and box (equal struct old-struct))
20196 (if (equal arg '(16))
20197 (message "Checkboxes already reset")
20198 (user-error "Cannot toggle this checkbox: %s"
20199 (if (eq box 'on)
20200 "all subitems checked"
20201 "unchecked subitems")))
20202 (org-list-struct-apply-struct struct old-struct)
20203 (org-update-checkbox-count-maybe))
20204 (when block-item
20205 (message "Checkboxes were removed due to empty box at line %d"
20206 (org-current-line block-item))))))
20207 (keyword
20208 (let ((org-inhibit-startup-visibility-stuff t)
20209 (org-startup-align-all-tables nil))
20210 (when (boundp 'org-table-coordinate-overlays)
20211 (mapc 'delete-overlay org-table-coordinate-overlays)
20212 (setq org-table-coordinate-overlays nil))
20213 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20214 (message "Local setup has been refreshed"))
20215 (plain-list
20216 ;; At a plain list, with a double C-u argument, set
20217 ;; checkboxes of each item to "[-]", whereas a single one
20218 ;; will toggle their presence according to the state of the
20219 ;; first item in the list. Without an argument, repair the
20220 ;; list.
20221 (let* ((begin (org-element-property :contents-begin context))
20222 (beginm (move-marker (make-marker) begin))
20223 (struct (org-element-property :structure context))
20224 (old-struct (copy-tree struct))
20225 (first-box (save-excursion
20226 (goto-char begin)
20227 (looking-at org-list-full-item-re)
20228 (match-string-no-properties 3)))
20229 (new-box (cond ((equal arg '(16)) "[-]")
20230 ((equal arg '(4)) (unless first-box "[ ]"))
20231 ((equal first-box "[X]") "[ ]")
20232 (t "[X]"))))
20233 (cond
20234 (arg
20235 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20236 (org-list-get-all-items
20237 begin struct (org-list-prevs-alist struct))))
20238 ((and first-box (eq (point) begin))
20239 ;; For convenience, when point is at bol on the first
20240 ;; item of the list and no argument is provided, simply
20241 ;; toggle checkbox of that item, if any.
20242 (org-list-set-checkbox begin struct new-box)))
20243 (org-list-write-struct
20244 struct (org-list-parents-alist struct) old-struct)
20245 (org-update-checkbox-count-maybe)
20246 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20247 ((property-drawer node-property)
20248 (call-interactively 'org-property-action))
20249 ((radio-target target)
20250 (call-interactively 'org-update-radio-target-regexp))
20251 (statistics-cookie
20252 (call-interactively 'org-update-statistics-cookies))
20253 ((table table-cell table-row)
20254 ;; At a table, recalculate every field and align it. Also
20255 ;; send the table if necessary. If the table has
20256 ;; a `table.el' type, just give up. At a table row or
20257 ;; cell, maybe recalculate line but always align table.
20258 (if (eq (org-element-property :type context) 'table.el)
20259 (message "Use C-c ' to edit table.el tables")
20260 (let ((org-enable-table-editor t))
20261 (if (or (eq type 'table)
20262 ;; Check if point is at a TBLFM line.
20263 (and (eq type 'table-row)
20264 (= (point) (org-element-property :end context))))
20265 (save-excursion
20266 (if (org-at-TBLFM-p)
20267 (progn (require 'org-table)
20268 (org-table-calc-current-TBLFM))
20269 (goto-char (org-element-property :contents-begin context))
20270 (org-call-with-arg 'org-table-recalculate (or arg t))
20271 (orgtbl-send-table 'maybe)))
20272 (org-table-maybe-eval-formula)
20273 (cond (arg (call-interactively 'org-table-recalculate))
20274 ((org-table-maybe-recalculate-line))
20275 (t (org-table-align)))))))
20276 (timestamp (org-timestamp-change 0 'day))
20277 (otherwise
20278 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20279 (user-error
20280 "C-c C-c can do nothing useful at this location")))))))))
20282 (defun org-mode-restart ()
20283 "Restart Org-mode, to scan again for special lines.
20284 Also updates the keyword regular expressions."
20285 (interactive)
20286 (org-mode)
20287 (message "Org-mode restarted"))
20289 (defun org-kill-note-or-show-branches ()
20290 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20291 (interactive)
20292 (if (not org-finish-function)
20293 (progn
20294 (hide-subtree)
20295 (call-interactively 'show-branches))
20296 (let ((org-note-abort t))
20297 (funcall org-finish-function))))
20299 (defun org-open-line (n)
20300 "Insert a new row in tables, call `open-line' elsewhere."
20301 (interactive "*p")
20302 (if (org-at-table-p)
20303 (org-table-insert-row)
20304 (open-line n)))
20306 (defun org-return (&optional indent)
20307 "Goto next table row or insert a newline.
20308 Calls `org-table-next-row' or `newline', depending on context.
20309 See the individual commands for more information."
20310 (interactive)
20311 (let (org-ts-what)
20312 (cond
20313 ((or (bobp) (org-in-src-block-p))
20314 (if indent (newline-and-indent) (newline)))
20315 ((org-at-table-p)
20316 (org-table-justify-field-maybe)
20317 (call-interactively 'org-table-next-row))
20318 ;; when `newline-and-indent' is called within a list, make sure
20319 ;; text moved stays inside the item.
20320 ((and (org-in-item-p) indent)
20321 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20322 (progn
20323 (save-match-data (newline))
20324 (org-indent-line-to (length (match-string 0))))
20325 (let ((ind (org-get-indentation)))
20326 (newline)
20327 (if (org-looking-back org-list-end-re)
20328 (org-indent-line)
20329 (org-indent-line-to ind)))))
20330 ((and org-return-follows-link
20331 (org-at-timestamp-p t)
20332 (not (eq org-ts-what 'after)))
20333 (org-follow-timestamp-link))
20334 ((and org-return-follows-link
20335 (let ((tprop (get-text-property (point) 'face)))
20336 (or (eq tprop 'org-link)
20337 (and (listp tprop) (memq 'org-link tprop)))))
20338 (call-interactively 'org-open-at-point))
20339 ((and (org-at-heading-p)
20340 (looking-at
20341 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20342 (org-show-entry)
20343 (end-of-line 1)
20344 (newline))
20345 (t (if indent (newline-and-indent) (newline))))))
20347 (defun org-return-indent ()
20348 "Goto next table row or insert a newline and indent.
20349 Calls `org-table-next-row' or `newline-and-indent', depending on
20350 context. See the individual commands for more information."
20351 (interactive)
20352 (org-return t))
20354 (defun org-ctrl-c-star ()
20355 "Compute table, or change heading status of lines.
20356 Calls `org-table-recalculate' or `org-toggle-heading',
20357 depending on context."
20358 (interactive)
20359 (cond
20360 ((org-at-table-p)
20361 (call-interactively 'org-table-recalculate))
20363 ;; Convert all lines in region to list items
20364 (call-interactively 'org-toggle-heading))))
20366 (defun org-ctrl-c-minus ()
20367 "Insert separator line in table or modify bullet status of line.
20368 Also turns a plain line or a region of lines into list items.
20369 Calls `org-table-insert-hline', `org-toggle-item', or
20370 `org-cycle-list-bullet', depending on context."
20371 (interactive)
20372 (cond
20373 ((org-at-table-p)
20374 (call-interactively 'org-table-insert-hline))
20375 ((org-region-active-p)
20376 (call-interactively 'org-toggle-item))
20377 ((org-in-item-p)
20378 (call-interactively 'org-cycle-list-bullet))
20380 (call-interactively 'org-toggle-item))))
20382 (defun org-toggle-item (arg)
20383 "Convert headings or normal lines to items, items to normal lines.
20384 If there is no active region, only the current line is considered.
20386 If the first non blank line in the region is a headline, convert
20387 all headlines to items, shifting text accordingly.
20389 If it is an item, convert all items to normal lines.
20391 If it is normal text, change region into a list of items.
20392 With a prefix argument ARG, change the region in a single item."
20393 (interactive "P")
20394 (let ((shift-text
20395 (function
20396 ;; Shift text in current section to IND, from point to END.
20397 ;; The function leaves point to END line.
20398 (lambda (ind end)
20399 (let ((min-i 1000) (end (copy-marker end)))
20400 ;; First determine the minimum indentation (MIN-I) of
20401 ;; the text.
20402 (save-excursion
20403 (catch 'exit
20404 (while (< (point) end)
20405 (let ((i (org-get-indentation)))
20406 (cond
20407 ;; Skip blank lines and inline tasks.
20408 ((looking-at "^[ \t]*$"))
20409 ((looking-at org-outline-regexp-bol))
20410 ;; We can't find less than 0 indentation.
20411 ((zerop i) (throw 'exit (setq min-i 0)))
20412 ((< i min-i) (setq min-i i))))
20413 (forward-line))))
20414 ;; Then indent each line so that a line indented to
20415 ;; MIN-I becomes indented to IND. Ignore blank lines
20416 ;; and inline tasks in the process.
20417 (let ((delta (- ind min-i)))
20418 (while (< (point) end)
20419 (unless (or (looking-at "^[ \t]*$")
20420 (looking-at org-outline-regexp-bol))
20421 (org-indent-line-to (+ (org-get-indentation) delta)))
20422 (forward-line)))))))
20423 (skip-blanks
20424 (function
20425 ;; Return beginning of first non-blank line, starting from
20426 ;; line at POS.
20427 (lambda (pos)
20428 (save-excursion
20429 (goto-char pos)
20430 (skip-chars-forward " \r\t\n")
20431 (point-at-bol)))))
20432 beg end)
20433 ;; Determine boundaries of changes.
20434 (if (org-region-active-p)
20435 (setq beg (funcall skip-blanks (region-beginning))
20436 end (copy-marker (region-end)))
20437 (setq beg (funcall skip-blanks (point-at-bol))
20438 end (copy-marker (point-at-eol))))
20439 ;; Depending on the starting line, choose an action on the text
20440 ;; between BEG and END.
20441 (org-with-limited-levels
20442 (save-excursion
20443 (goto-char beg)
20444 (cond
20445 ;; Case 1. Start at an item: de-itemize. Note that it only
20446 ;; happens when a region is active: `org-ctrl-c-minus'
20447 ;; would call `org-cycle-list-bullet' otherwise.
20448 ((org-at-item-p)
20449 (while (< (point) end)
20450 (when (org-at-item-p)
20451 (skip-chars-forward " \t")
20452 (delete-region (point) (match-end 0)))
20453 (forward-line)))
20454 ;; Case 2. Start at an heading: convert to items.
20455 ((org-at-heading-p)
20456 (let* ((bul (org-list-bullet-string "-"))
20457 (bul-len (length bul))
20458 ;; Indentation of the first heading. It should be
20459 ;; relative to the indentation of its parent, if any.
20460 (start-ind (save-excursion
20461 (cond
20462 ((not org-adapt-indentation) 0)
20463 ((not (outline-previous-heading)) 0)
20464 (t (length (match-string 0))))))
20465 ;; Level of first heading. Further headings will be
20466 ;; compared to it to determine hierarchy in the list.
20467 (ref-level (org-reduced-level (org-outline-level))))
20468 (while (< (point) end)
20469 (let* ((level (org-reduced-level (org-outline-level)))
20470 (delta (max 0 (- level ref-level))))
20471 ;; If current headline is less indented than the first
20472 ;; one, set it as reference, in order to preserve
20473 ;; subtrees.
20474 (when (< level ref-level) (setq ref-level level))
20475 (replace-match bul t t)
20476 (org-indent-line-to (+ start-ind (* delta bul-len)))
20477 ;; Ensure all text down to END (or SECTION-END) belongs
20478 ;; to the newly created item.
20479 (let ((section-end (save-excursion
20480 (or (outline-next-heading) (point)))))
20481 (forward-line)
20482 (funcall shift-text
20483 (+ start-ind (* (1+ delta) bul-len))
20484 (min end section-end)))))))
20485 ;; Case 3. Normal line with ARG: make the first line of region
20486 ;; an item, and shift indentation of others lines to
20487 ;; set them as item's body.
20488 (arg (let* ((bul (org-list-bullet-string "-"))
20489 (bul-len (length bul))
20490 (ref-ind (org-get-indentation)))
20491 (skip-chars-forward " \t")
20492 (insert bul)
20493 (forward-line)
20494 (while (< (point) end)
20495 ;; Ensure that lines less indented than first one
20496 ;; still get included in item body.
20497 (funcall shift-text
20498 (+ ref-ind bul-len)
20499 (min end (save-excursion (or (outline-next-heading)
20500 (point)))))
20501 (forward-line))))
20502 ;; Case 4. Normal line without ARG: turn each non-item line
20503 ;; into an item.
20505 (while (< (point) end)
20506 (unless (or (org-at-heading-p) (org-at-item-p))
20507 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20508 (replace-match
20509 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20510 (forward-line))))))))
20512 (defun org-toggle-heading (&optional nstars)
20513 "Convert headings to normal text, or items or text to headings.
20514 If there is no active region, only convert the current line.
20516 With a \\[universal-argument] prefix, convert the whole list at
20517 point into heading.
20519 In a region:
20521 - If the first non blank line is a headline, remove the stars
20522 from all headlines in the region.
20524 - If it is a normal line, turn each and every normal line (i.e.,
20525 not an heading or an item) in the region into headings. If you
20526 want to convert only the first line of this region, use one
20527 universal prefix argument.
20529 - If it is a plain list item, turn all plain list items into headings.
20531 When converting a line into a heading, the number of stars is chosen
20532 such that the lines become children of the current entry. However,
20533 when a numeric prefix argument is given, its value determines the
20534 number of stars to add."
20535 (interactive "P")
20536 (let ((skip-blanks
20537 (function
20538 ;; Return beginning of first non-blank line, starting from
20539 ;; line at POS.
20540 (lambda (pos)
20541 (save-excursion
20542 (goto-char pos)
20543 (while (org-at-comment-p) (forward-line))
20544 (skip-chars-forward " \r\t\n")
20545 (point-at-bol)))))
20546 beg end toggled)
20547 ;; Determine boundaries of changes. If a universal prefix has
20548 ;; been given, put the list in a region. If region ends at a bol,
20549 ;; do not consider the last line to be in the region.
20551 (when (and current-prefix-arg (org-at-item-p))
20552 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20553 (org-mark-element))
20555 (if (org-region-active-p)
20556 (setq beg (funcall skip-blanks (region-beginning))
20557 end (copy-marker (save-excursion
20558 (goto-char (region-end))
20559 (if (bolp) (point) (point-at-eol)))))
20560 (setq beg (funcall skip-blanks (point-at-bol))
20561 end (copy-marker (point-at-eol))))
20562 ;; Ensure inline tasks don't count as headings.
20563 (org-with-limited-levels
20564 (save-excursion
20565 (goto-char beg)
20566 (cond
20567 ;; Case 1. Started at an heading: de-star headings.
20568 ((org-at-heading-p)
20569 (while (< (point) end)
20570 (when (org-at-heading-p t)
20571 (looking-at org-outline-regexp) (replace-match "")
20572 (setq toggled t))
20573 (forward-line)))
20574 ;; Case 2. Started at an item: change items into headlines.
20575 ;; One star will be added by `org-list-to-subtree'.
20576 ((org-at-item-p)
20577 (let* ((stars (make-string
20578 ;; subtract the star that will be added again by
20579 ;; `org-list-to-subtree'
20580 (if (numberp nstars) (1- nstars)
20581 (or (org-current-level) 0))
20582 ?*))
20583 (add-stars
20584 (cond (nstars "") ; stars from prefix only
20585 ((equal stars "") "") ; before first heading
20586 (org-odd-levels-only "*") ; inside heading, odd
20587 (t "")))) ; inside heading, oddeven
20588 (while (< (point) end)
20589 (when (org-at-item-p)
20590 ;; Pay attention to cases when region ends before list.
20591 (let* ((struct (org-list-struct))
20592 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20593 (save-restriction
20594 (narrow-to-region (point) list-end)
20595 (insert
20596 (org-list-to-subtree
20597 (org-list-parse-list t)
20598 '(:istart (concat stars add-stars (funcall get-stars depth))
20599 :icount (concat stars add-stars (funcall get-stars depth)))))))
20600 (setq toggled t))
20601 (forward-line))))
20602 ;; Case 3. Started at normal text: make every line an heading,
20603 ;; skipping headlines and items.
20604 (t (let* ((stars
20605 (make-string
20606 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20607 (add-stars
20608 (cond (nstars "") ; stars from prefix only
20609 ((equal stars "") "*") ; before first heading
20610 (org-odd-levels-only "**") ; inside heading, odd
20611 (t "*"))) ; inside heading, oddeven
20612 (rpl (concat stars add-stars " "))
20613 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20614 (while (< (point) (if (equal nstars '(4)) lend end))
20615 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20616 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20617 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20618 (forward-line)))))))
20619 (unless toggled (message "Cannot toggle heading from here"))))
20621 (defun org-meta-return (&optional arg)
20622 "Insert a new heading or wrap a region in a table.
20623 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20624 See the individual commands for more information."
20625 (interactive "P")
20626 (org-check-before-invisible-edit 'insert)
20627 (cond
20628 ((run-hook-with-args-until-success 'org-metareturn-hook))
20629 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20630 (newline-and-indent))
20631 ((org-at-table-p)
20632 (call-interactively 'org-table-wrap-region))
20633 (t (call-interactively 'org-insert-heading))))
20635 ;;; Menu entries
20637 (defsubst org-in-subtree-not-table-p ()
20638 "Are we in a subtree and not in a table?"
20639 (and (not (org-before-first-heading-p))
20640 (not (org-at-table-p))))
20642 ;; Define the Org-mode menus
20643 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20644 '("Tbl"
20645 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20646 ["Next Field" org-cycle (org-at-table-p)]
20647 ["Previous Field" org-shifttab (org-at-table-p)]
20648 ["Next Row" org-return (org-at-table-p)]
20649 "--"
20650 ["Blank Field" org-table-blank-field (org-at-table-p)]
20651 ["Edit Field" org-table-edit-field (org-at-table-p)]
20652 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20653 "--"
20654 ("Column"
20655 ["Move Column Left" org-metaleft (org-at-table-p)]
20656 ["Move Column Right" org-metaright (org-at-table-p)]
20657 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20658 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20659 ("Row"
20660 ["Move Row Up" org-metaup (org-at-table-p)]
20661 ["Move Row Down" org-metadown (org-at-table-p)]
20662 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20663 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20664 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20665 "--"
20666 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20667 ("Rectangle"
20668 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20669 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20670 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20671 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20672 "--"
20673 ("Calculate"
20674 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20675 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20676 ["Edit Formulas" org-edit-special (org-at-table-p)]
20677 "--"
20678 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20679 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20680 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20681 "--"
20682 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20683 "--"
20684 ["Sum Column/Rectangle" org-table-sum
20685 (or (org-at-table-p) (org-region-active-p))]
20686 ["Which Column?" org-table-current-column (org-at-table-p)])
20687 ["Debug Formulas"
20688 org-table-toggle-formula-debugger
20689 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20690 ["Show Col/Row Numbers"
20691 org-table-toggle-coordinate-overlays
20692 :style toggle
20693 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20694 "--"
20695 ["Create" org-table-create (and (not (org-at-table-p))
20696 org-enable-table-editor)]
20697 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20698 ["Import from File" org-table-import (not (org-at-table-p))]
20699 ["Export to File" org-table-export (org-at-table-p)]
20700 "--"
20701 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20703 (easy-menu-define org-org-menu org-mode-map "Org menu"
20704 '("Org"
20705 ("Show/Hide"
20706 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20707 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20708 ["Sparse Tree..." org-sparse-tree t]
20709 ["Reveal Context" org-reveal t]
20710 ["Show All" show-all t]
20711 "--"
20712 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20713 "--"
20714 ["New Heading" org-insert-heading t]
20715 ("Navigate Headings"
20716 ["Up" outline-up-heading t]
20717 ["Next" outline-next-visible-heading t]
20718 ["Previous" outline-previous-visible-heading t]
20719 ["Next Same Level" outline-forward-same-level t]
20720 ["Previous Same Level" outline-backward-same-level t]
20721 "--"
20722 ["Jump" org-goto t])
20723 ("Edit Structure"
20724 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20725 "--"
20726 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20727 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20728 "--"
20729 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20730 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20731 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20732 "--"
20733 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20734 "--"
20735 ["Copy visible text" org-copy-visible t]
20736 "--"
20737 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20738 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20739 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20740 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20741 "--"
20742 ["Sort Region/Children" org-sort t]
20743 "--"
20744 ["Convert to odd levels" org-convert-to-odd-levels t]
20745 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20746 ("Editing"
20747 ["Emphasis..." org-emphasize t]
20748 ["Edit Source Example" org-edit-special t]
20749 "--"
20750 ["Footnote new/jump" org-footnote-action t]
20751 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20752 ("Archive"
20753 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20754 "--"
20755 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20756 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20757 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20759 "--"
20760 ("Hyperlinks"
20761 ["Store Link (Global)" org-store-link t]
20762 ["Find existing link to here" org-occur-link-in-agenda-files t]
20763 ["Insert Link" org-insert-link t]
20764 ["Follow Link" org-open-at-point t]
20765 "--"
20766 ["Next link" org-next-link t]
20767 ["Previous link" org-previous-link t]
20768 "--"
20769 ["Descriptive Links"
20770 org-toggle-link-display
20771 :style radio
20772 :selected org-descriptive-links
20774 ["Literal Links"
20775 org-toggle-link-display
20776 :style radio
20777 :selected (not org-descriptive-links)])
20778 "--"
20779 ("TODO Lists"
20780 ["TODO/DONE/-" org-todo t]
20781 ("Select keyword"
20782 ["Next keyword" org-shiftright (org-at-heading-p)]
20783 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20784 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20785 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20786 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20787 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20788 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20789 "--"
20790 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20791 :selected org-enforce-todo-dependencies :style toggle :active t]
20792 "Settings for tree at point"
20793 ["Do Children sequentially" org-toggle-ordered-property :style radio
20794 :selected (org-entry-get nil "ORDERED")
20795 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20796 ["Do Children parallel" org-toggle-ordered-property :style radio
20797 :selected (not (org-entry-get nil "ORDERED"))
20798 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20799 "--"
20800 ["Set Priority" org-priority t]
20801 ["Priority Up" org-shiftup t]
20802 ["Priority Down" org-shiftdown t]
20803 "--"
20804 ["Get news from all feeds" org-feed-update-all t]
20805 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20806 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20807 ("TAGS and Properties"
20808 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20809 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20810 "--"
20811 ["Set property" org-set-property (not (org-before-first-heading-p))]
20812 ["Column view of properties" org-columns t]
20813 ["Insert Column View DBlock" org-insert-columns-dblock t])
20814 ("Dates and Scheduling"
20815 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20816 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20817 ("Change Date"
20818 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20819 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20820 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20821 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20822 ["Compute Time Range" org-evaluate-time-range t]
20823 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20824 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20825 "--"
20826 ["Custom time format" org-toggle-time-stamp-overlays
20827 :style radio :selected org-display-custom-times]
20828 "--"
20829 ["Goto Calendar" org-goto-calendar t]
20830 ["Date from Calendar" org-date-from-calendar t]
20831 "--"
20832 ["Start/Restart Timer" org-timer-start t]
20833 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20834 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20835 ["Insert Timer String" org-timer t]
20836 ["Insert Timer Item" org-timer-item t])
20837 ("Logging work"
20838 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20839 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20840 ["Clock out" org-clock-out t]
20841 ["Clock cancel" org-clock-cancel t]
20842 "--"
20843 ["Mark as default task" org-clock-mark-default-task t]
20844 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20845 ["Goto running clock" org-clock-goto t]
20846 "--"
20847 ["Display times" org-clock-display t]
20848 ["Create clock table" org-clock-report t]
20849 "--"
20850 ["Record DONE time"
20851 (progn (setq org-log-done (not org-log-done))
20852 (message "Switching to %s will %s record a timestamp"
20853 (car org-done-keywords)
20854 (if org-log-done "automatically" "not")))
20855 :style toggle :selected org-log-done])
20856 "--"
20857 ["Agenda Command..." org-agenda t]
20858 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20859 ("File List for Agenda")
20860 ("Special views current file"
20861 ["TODO Tree" org-show-todo-tree t]
20862 ["Check Deadlines" org-check-deadlines t]
20863 ["Timeline" org-timeline t]
20864 ["Tags/Property tree" org-match-sparse-tree t])
20865 "--"
20866 ["Export/Publish..." org-export-dispatch t]
20867 ("LaTeX"
20868 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20869 :selected org-cdlatex-mode]
20870 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20871 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20872 ["Modify math symbol" org-cdlatex-math-modify
20873 (org-inside-LaTeX-fragment-p)]
20874 ["Insert citation" org-reftex-citation t]
20875 "--"
20876 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20877 "--"
20878 ("MobileOrg"
20879 ["Push Files and Views" org-mobile-push t]
20880 ["Get Captured and Flagged" org-mobile-pull t]
20881 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20882 "--"
20883 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20884 "--"
20885 ("Documentation"
20886 ["Show Version" org-version t]
20887 ["Info Documentation" org-info t])
20888 ("Customize"
20889 ["Browse Org Group" org-customize t]
20890 "--"
20891 ["Expand This Menu" org-create-customize-menu
20892 (fboundp 'customize-menu-create)])
20893 ["Send bug report" org-submit-bug-report t]
20894 "--"
20895 ("Refresh/Reload"
20896 ["Refresh setup current buffer" org-mode-restart t]
20897 ["Reload Org (after update)" org-reload t]
20898 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20901 (defun org-info (&optional node)
20902 "Read documentation for Org-mode in the info system.
20903 With optional NODE, go directly to that node."
20904 (interactive)
20905 (info (format "(org)%s" (or node ""))))
20907 ;;;###autoload
20908 (defun org-submit-bug-report ()
20909 "Submit a bug report on Org-mode via mail.
20911 Don't hesitate to report any problems or inaccurate documentation.
20913 If you don't have setup sending mail from (X)Emacs, please copy the
20914 output buffer into your mail program, as it gives us important
20915 information about your Org-mode version and configuration."
20916 (interactive)
20917 (require 'reporter)
20918 (org-load-modules-maybe)
20919 (org-require-autoloaded-modules)
20920 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20921 (reporter-submit-bug-report
20922 "emacs-orgmode@gnu.org"
20923 (org-version nil 'full)
20924 (let (list)
20925 (save-window-excursion
20926 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20927 (delete-other-windows)
20928 (erase-buffer)
20929 (insert "You are about to submit a bug report to the Org-mode mailing list.
20931 We would like to add your full Org-mode and Outline configuration to the
20932 bug report. This greatly simplifies the work of the maintainer and
20933 other experts on the mailing list.
20935 HOWEVER, some variables you have customized may contain private
20936 information. The names of customers, colleagues, or friends, might
20937 appear in the form of file names, tags, todo states, or search strings.
20938 If you answer yes to the prompt, you might want to check and remove
20939 such private information before sending the email.")
20940 (add-text-properties (point-min) (point-max) '(face org-warning))
20941 (when (yes-or-no-p "Include your Org-mode configuration ")
20942 (mapatoms
20943 (lambda (v)
20944 (and (boundp v)
20945 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20946 (or (and (symbol-value v)
20947 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20948 (and
20949 (get v 'custom-type) (get v 'standard-value)
20950 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20951 (push v list)))))
20952 (kill-buffer (get-buffer "*Warn about privacy*"))
20953 list))
20954 nil nil
20955 "Remember to cover the basics, that is, what you expected to happen and
20956 what in fact did happen. You don't know how to make a good report? See
20958 http://orgmode.org/manual/Feedback.html#Feedback
20960 Your bug report will be posted to the Org-mode mailing list.
20961 ------------------------------------------------------------------------")
20962 (save-excursion
20963 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20964 (replace-match "\\1Bug: \\3 [\\2]")))))
20967 (defun org-install-agenda-files-menu ()
20968 (let ((bl (buffer-list)))
20969 (save-excursion
20970 (while bl
20971 (set-buffer (pop bl))
20972 (if (derived-mode-p 'org-mode) (setq bl nil)))
20973 (when (derived-mode-p 'org-mode)
20974 (easy-menu-change
20975 '("Org") "File List for Agenda"
20976 (append
20977 (list
20978 ["Edit File List" (org-edit-agenda-file-list) t]
20979 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20980 ["Remove Current File from List" org-remove-file t]
20981 ["Cycle through agenda files" org-cycle-agenda-files t]
20982 ["Occur in all agenda files" org-occur-in-agenda-files t]
20983 "--")
20984 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20986 ;;;; Documentation
20988 (defun org-require-autoloaded-modules ()
20989 (interactive)
20990 (mapc 'require
20991 '(org-agenda org-archive org-attach org-clock org-colview org-id
20992 org-remember org-table org-timer)))
20994 ;;;###autoload
20995 (defun org-reload (&optional uncompiled)
20996 "Reload all org lisp files.
20997 With prefix arg UNCOMPILED, load the uncompiled versions."
20998 (interactive "P")
20999 (require 'loadhist)
21000 (let* ((org-dir (org-find-library-dir "org"))
21001 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21002 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21003 (remove-re (mapconcat 'identity
21004 (mapcar (lambda (f) (concat "^" f "$"))
21005 (list (if (featurep 'xemacs)
21006 "org-colview"
21007 "org-colview-xemacs")
21008 "org" "org-loaddefs" "org-version"))
21009 "\\|"))
21010 (feats (delete-dups
21011 (mapcar 'file-name-sans-extension
21012 (mapcar 'file-name-nondirectory
21013 (delq nil
21014 (mapcar 'feature-file
21015 features))))))
21016 (lfeat (append
21017 (sort
21018 (setq feats
21019 (delq nil (mapcar
21020 (lambda (f)
21021 (if (and (string-match feature-re f)
21022 (not (string-match remove-re f)))
21023 f nil))
21024 feats)))
21025 'string-lessp)
21026 (list "org-version" "org")))
21027 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21028 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21029 load-uncore load-misses)
21030 (setq load-misses
21031 (delq 't
21032 (mapcar (lambda (f)
21033 (or (org-load-noerror-mustsuffix (concat org-dir f))
21034 (and (string= org-dir contrib-dir)
21035 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21036 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21037 (add-to-list 'load-uncore f 'append)
21040 lfeat)))
21041 (if load-uncore
21042 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21043 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21044 (if load-misses
21045 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21046 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21047 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21049 ;;;###autoload
21050 (defun org-customize ()
21051 "Call the customize function with org as argument."
21052 (interactive)
21053 (org-load-modules-maybe)
21054 (org-require-autoloaded-modules)
21055 (customize-browse 'org))
21057 (defun org-create-customize-menu ()
21058 "Create a full customization menu for Org-mode, insert it into the menu."
21059 (interactive)
21060 (org-load-modules-maybe)
21061 (org-require-autoloaded-modules)
21062 (if (fboundp 'customize-menu-create)
21063 (progn
21064 (easy-menu-change
21065 '("Org") "Customize"
21066 `(["Browse Org group" org-customize t]
21067 "--"
21068 ,(customize-menu-create 'org)
21069 ["Set" Custom-set t]
21070 ["Save" Custom-save t]
21071 ["Reset to Current" Custom-reset-current t]
21072 ["Reset to Saved" Custom-reset-saved t]
21073 ["Reset to Standard Settings" Custom-reset-standard t]))
21074 (message "\"Org\"-menu now contains full customization menu"))
21075 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21077 ;;;; Miscellaneous stuff
21079 ;;; Generally useful functions
21081 (defun org-get-at-bol (property)
21082 "Get text property PROPERTY at beginning of line."
21083 (get-text-property (point-at-bol) property))
21085 (defun org-find-text-property-in-string (prop s)
21086 "Return the first non-nil value of property PROP in string S."
21087 (or (get-text-property 0 prop s)
21088 (get-text-property (or (next-single-property-change 0 prop s) 0)
21089 prop s)))
21091 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21092 "Display the given MESSAGE as a warning."
21093 (if (fboundp 'display-warning)
21094 (display-warning 'org message
21095 (if (featurep 'xemacs) 'warning :warning))
21096 (let ((buf (get-buffer-create "*Org warnings*")))
21097 (with-current-buffer buf
21098 (goto-char (point-max))
21099 (insert "Warning (Org): " message)
21100 (unless (bolp)
21101 (newline)))
21102 (display-buffer buf)
21103 (sit-for 0))))
21105 (defun org-eval (form)
21106 "Eval FORM and return result."
21107 (condition-case error
21108 (eval form)
21109 (error (format "%%![Error: %s]" error))))
21111 (defun org-in-clocktable-p ()
21112 "Check if the cursor is in a clocktable."
21113 (let ((pos (point)) start)
21114 (save-excursion
21115 (end-of-line 1)
21116 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21117 (setq start (match-beginning 0))
21118 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21119 (>= (match-end 0) pos)
21120 start))))
21122 (defun org-in-commented-line ()
21123 "Is point in a line starting with `#'?"
21124 (equal (char-after (point-at-bol)) ?#))
21126 (defun org-in-indented-comment-line ()
21127 "Is point in a line starting with `#' after some white space?"
21128 (save-excursion
21129 (save-match-data
21130 (goto-char (point-at-bol))
21131 (looking-at "[ \t]*#"))))
21133 (defun org-in-verbatim-emphasis ()
21134 (save-match-data
21135 (and (org-in-regexp org-emph-re 2)
21136 (>= (point) (match-beginning 3))
21137 (<= (point) (match-end 4))
21138 (member (match-string 3) '("=" "~")))))
21140 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21141 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21142 (if (and marker (marker-buffer marker)
21143 (buffer-live-p (marker-buffer marker)))
21144 (progn
21145 (org-pop-to-buffer-same-window (marker-buffer marker))
21146 (if (or (> marker (point-max)) (< marker (point-min)))
21147 (widen))
21148 (goto-char marker)
21149 (org-show-context 'org-goto))
21150 (if bookmark
21151 (bookmark-jump bookmark)
21152 (error "Cannot find location"))))
21154 (defun org-quote-csv-field (s)
21155 "Quote field for inclusion in CSV material."
21156 (if (string-match "[\",]" s)
21157 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21160 (defun org-force-self-insert (N)
21161 "Needed to enforce self-insert under remapping."
21162 (interactive "p")
21163 (self-insert-command N))
21165 (defun org-string-width (s)
21166 "Compute width of string, ignoring invisible characters.
21167 This ignores character with invisibility property `org-link', and also
21168 characters with property `org-cwidth', because these will become invisible
21169 upon the next fontification round."
21170 (let (b l)
21171 (when (or (eq t buffer-invisibility-spec)
21172 (assq 'org-link buffer-invisibility-spec))
21173 (while (setq b (text-property-any 0 (length s)
21174 'invisible 'org-link s))
21175 (setq s (concat (substring s 0 b)
21176 (substring s (or (next-single-property-change
21177 b 'invisible s) (length s)))))))
21178 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21179 (setq s (concat (substring s 0 b)
21180 (substring s (or (next-single-property-change
21181 b 'org-cwidth s) (length s))))))
21182 (setq l (string-width s) b -1)
21183 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21184 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21187 (defun org-shorten-string (s maxlength)
21188 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21189 If the string is shorter or has length MAXLENGTH, just return the
21190 original string. If it is longer, the functions finds a space in the
21191 string, breaks this string off at that locations and adds three dots
21192 as ellipsis. Including the ellipsis, the string will not be longer
21193 than MAXLENGTH. If finding a good breaking point in the string does
21194 not work, the string is just chopped off in the middle of a word
21195 if necessary."
21196 (if (<= (length s) maxlength)
21198 (let* ((n (max (- maxlength 4) 1))
21199 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21200 (if (string-match re s)
21201 (concat (match-string 1 s) "...")
21202 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21204 (defun org-get-indentation (&optional line)
21205 "Get the indentation of the current line, interpreting tabs.
21206 When LINE is given, assume it represents a line and compute its indentation."
21207 (if line
21208 (if (string-match "^ *" (org-remove-tabs line))
21209 (match-end 0))
21210 (save-excursion
21211 (beginning-of-line 1)
21212 (skip-chars-forward " \t")
21213 (current-column))))
21215 (defun org-get-string-indentation (s)
21216 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21217 (let ((n -1) (i 0) (w tab-width) c)
21218 (catch 'exit
21219 (while (< (setq n (1+ n)) (length s))
21220 (setq c (aref s n))
21221 (cond ((= c ?\ ) (setq i (1+ i)))
21222 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21223 (t (throw 'exit t)))))
21226 (defun org-remove-tabs (s &optional width)
21227 "Replace tabulators in S with spaces.
21228 Assumes that s is a single line, starting in column 0."
21229 (setq width (or width tab-width))
21230 (while (string-match "\t" s)
21231 (setq s (replace-match
21232 (make-string
21233 (- (* width (/ (+ (match-beginning 0) width) width))
21234 (match-beginning 0)) ?\ )
21235 t t s)))
21238 (defun org-fix-indentation (line ind)
21239 "Fix indentation in LINE.
21240 IND is a cons cell with target and minimum indentation.
21241 If the current indentation in LINE is smaller than the minimum,
21242 leave it alone. If it is larger than ind, set it to the target."
21243 (let* ((l (org-remove-tabs line))
21244 (i (org-get-indentation l))
21245 (i1 (car ind)) (i2 (cdr ind)))
21246 (if (>= i i2) (setq l (substring line i2)))
21247 (if (> i1 0)
21248 (concat (make-string i1 ?\ ) l)
21249 l)))
21251 (defun org-remove-indentation (code &optional n)
21252 "Remove the maximum common indentation from the lines in CODE.
21253 N may optionally be the number of spaces to remove."
21254 (with-temp-buffer
21255 (insert code)
21256 (org-do-remove-indentation n)
21257 (buffer-string)))
21259 (defun org-do-remove-indentation (&optional n)
21260 "Remove the maximum common indentation from the buffer."
21261 (untabify (point-min) (point-max))
21262 (let ((min 10000) re)
21263 (if n
21264 (setq min n)
21265 (goto-char (point-min))
21266 (while (re-search-forward "^ *[^ \n]" nil t)
21267 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21268 (unless (or (= min 0) (= min 10000))
21269 (setq re (format "^ \\{%d\\}" min))
21270 (goto-char (point-min))
21271 (while (re-search-forward re nil t)
21272 (replace-match "")
21273 (end-of-line 1))
21274 min)))
21276 (defun org-fill-template (template alist)
21277 "Find each %key of ALIST in TEMPLATE and replace it."
21278 (let ((case-fold-search nil)
21279 entry key value)
21280 (setq alist (sort (copy-sequence alist)
21281 (lambda (a b) (< (length (car a)) (length (car b))))))
21282 (while (setq entry (pop alist))
21283 (setq template
21284 (replace-regexp-in-string
21285 (concat "%" (regexp-quote (car entry)))
21286 (or (cdr entry) "") template t t)))
21287 template))
21289 (defun org-base-buffer (buffer)
21290 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21291 (if (not buffer)
21292 buffer
21293 (or (buffer-base-buffer buffer)
21294 buffer)))
21296 (defun org-trim (s)
21297 "Remove whitespace at beginning and end of string."
21298 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21299 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21302 (defun org-wrap (string &optional width lines)
21303 "Wrap string to either a number of lines, or a width in characters.
21304 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21305 that costs. If there is a word longer than WIDTH, the text is actually
21306 wrapped to the length of that word.
21307 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21308 many lines, whatever width that takes.
21309 The return value is a list of lines, without newlines at the end."
21310 (let* ((words (org-split-string string "[ \t\n]+"))
21311 (maxword (apply 'max (mapcar 'org-string-width words)))
21312 w ll)
21313 (cond (width
21314 (org-do-wrap words (max maxword width)))
21315 (lines
21316 (setq w maxword)
21317 (setq ll (org-do-wrap words maxword))
21318 (if (<= (length ll) lines)
21320 (setq ll words)
21321 (while (> (length ll) lines)
21322 (setq w (1+ w))
21323 (setq ll (org-do-wrap words w)))
21324 ll))
21325 (t (error "Cannot wrap this")))))
21327 (defun org-do-wrap (words width)
21328 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21329 (let (lines line)
21330 (while words
21331 (setq line (pop words))
21332 (while (and words (< (+ (length line) (length (car words))) width))
21333 (setq line (concat line " " (pop words))))
21334 (setq lines (push line lines)))
21335 (nreverse lines)))
21337 (defun org-split-string (string &optional separators)
21338 "Splits STRING into substrings at SEPARATORS.
21339 No empty strings are returned if there are matches at the beginning
21340 and end of string."
21341 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21342 (start 0)
21343 notfirst
21344 (list nil))
21345 (while (and (string-match rexp string
21346 (if (and notfirst
21347 (= start (match-beginning 0))
21348 (< start (length string)))
21349 (1+ start) start))
21350 (< (match-beginning 0) (length string)))
21351 (setq notfirst t)
21352 (or (eq (match-beginning 0) 0)
21353 (and (eq (match-beginning 0) (match-end 0))
21354 (eq (match-beginning 0) start))
21355 (setq list
21356 (cons (substring string start (match-beginning 0))
21357 list)))
21358 (setq start (match-end 0)))
21359 (or (eq start (length string))
21360 (setq list
21361 (cons (substring string start)
21362 list)))
21363 (nreverse list)))
21365 (defun org-quote-vert (s)
21366 "Replace \"|\" with \"\\vert\"."
21367 (while (string-match "|" s)
21368 (setq s (replace-match "\\vert" t t s)))
21371 (defun org-uuidgen-p (s)
21372 "Is S an ID created by UUIDGEN?"
21373 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21375 (defun org-in-src-block-p (&optional inside)
21376 "Whether point is in a code source block.
21377 When INSIDE is non-nil, don't consider we are within a src block
21378 when point is at #+BEGIN_SRC or #+END_SRC."
21379 (let ((case-fold-search t) ov)
21380 (or (and (setq ov (overlays-at (point)))
21381 (memq 'org-block-background
21382 (overlay-properties (car ov))))
21383 (and (not inside)
21384 (save-match-data
21385 (save-excursion
21386 (beginning-of-line)
21387 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21389 (defun org-context ()
21390 "Return a list of contexts of the current cursor position.
21391 If several contexts apply, all are returned.
21392 Each context entry is a list with a symbol naming the context, and
21393 two positions indicating start and end of the context. Possible
21394 contexts are:
21396 :headline anywhere in a headline
21397 :headline-stars on the leading stars in a headline
21398 :todo-keyword on a TODO keyword (including DONE) in a headline
21399 :tags on the TAGS in a headline
21400 :priority on the priority cookie in a headline
21401 :item on the first line of a plain list item
21402 :item-bullet on the bullet/number of a plain list item
21403 :checkbox on the checkbox in a plain list item
21404 :table in an org-mode table
21405 :table-special on a special filed in a table
21406 :table-table in a table.el table
21407 :clocktable in a clocktable
21408 :src-block in a source block
21409 :link on a hyperlink
21410 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21411 :target on a <<target>>
21412 :radio-target on a <<<radio-target>>>
21413 :latex-fragment on a LaTeX fragment
21414 :latex-preview on a LaTeX fragment with overlaid preview image
21416 This function expects the position to be visible because it uses font-lock
21417 faces as a help to recognize the following contexts: :table-special, :link,
21418 and :keyword."
21419 (let* ((f (get-text-property (point) 'face))
21420 (faces (if (listp f) f (list f)))
21421 (case-fold-search t)
21422 (p (point)) clist o)
21423 ;; First the large context
21424 (cond
21425 ((org-at-heading-p t)
21426 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21427 (when (progn
21428 (beginning-of-line 1)
21429 (looking-at org-todo-line-tags-regexp))
21430 (push (org-point-in-group p 1 :headline-stars) clist)
21431 (push (org-point-in-group p 2 :todo-keyword) clist)
21432 (push (org-point-in-group p 4 :tags) clist))
21433 (goto-char p)
21434 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21435 (if (looking-at "\\[#[A-Z0-9]\\]")
21436 (push (org-point-in-group p 0 :priority) clist)))
21438 ((org-at-item-p)
21439 (push (org-point-in-group p 2 :item-bullet) clist)
21440 (push (list :item (point-at-bol)
21441 (save-excursion (org-end-of-item) (point)))
21442 clist)
21443 (and (org-at-item-checkbox-p)
21444 (push (org-point-in-group p 0 :checkbox) clist)))
21446 ((org-at-table-p)
21447 (push (list :table (org-table-begin) (org-table-end)) clist)
21448 (if (memq 'org-formula faces)
21449 (push (list :table-special
21450 (previous-single-property-change p 'face)
21451 (next-single-property-change p 'face)) clist)))
21452 ((org-at-table-p 'any)
21453 (push (list :table-table) clist)))
21454 (goto-char p)
21456 (let ((case-fold-search t))
21457 ;; New the "medium" contexts: clocktables, source blocks
21458 (cond ((org-in-clocktable-p)
21459 (push (list :clocktable
21460 (and (or (looking-at "#\\+BEGIN: clocktable")
21461 (search-backward "#+BEGIN: clocktable" nil t))
21462 (match-beginning 0))
21463 (and (re-search-forward "#\\+END:?" nil t)
21464 (match-end 0))) clist))
21465 ((org-in-src-block-p)
21466 (push (list :src-block
21467 (and (or (looking-at "#\\+BEGIN_SRC")
21468 (search-backward "#+BEGIN_SRC" nil t))
21469 (match-beginning 0))
21470 (and (search-forward "#+END_SRC" nil t)
21471 (match-beginning 0))) clist))))
21472 (goto-char p)
21474 ;; Now the small context
21475 (cond
21476 ((org-at-timestamp-p)
21477 (push (org-point-in-group p 0 :timestamp) clist))
21478 ((memq 'org-link faces)
21479 (push (list :link
21480 (previous-single-property-change p 'face)
21481 (next-single-property-change p 'face)) clist))
21482 ((memq 'org-special-keyword faces)
21483 (push (list :keyword
21484 (previous-single-property-change p 'face)
21485 (next-single-property-change p 'face)) clist))
21486 ((org-at-target-p)
21487 (push (org-point-in-group p 0 :target) clist)
21488 (goto-char (1- (match-beginning 0)))
21489 (if (looking-at org-radio-target-regexp)
21490 (push (org-point-in-group p 0 :radio-target) clist))
21491 (goto-char p))
21492 ((setq o (car (delq nil
21493 (mapcar
21494 (lambda (x)
21495 (if (memq x org-latex-fragment-image-overlays) x))
21496 (overlays-at (point))))))
21497 (push (list :latex-fragment
21498 (overlay-start o) (overlay-end o)) clist)
21499 (push (list :latex-preview
21500 (overlay-start o) (overlay-end o)) clist))
21501 ((org-inside-LaTeX-fragment-p)
21502 ;; FIXME: positions wrong.
21503 (push (list :latex-fragment (point) (point)) clist)))
21505 (setq clist (nreverse (delq nil clist)))
21506 clist))
21508 ;; FIXME: Compare with at-regexp-p Do we need both?
21509 (defun org-in-regexp (re &optional nlines visually)
21510 "Check if point is inside a match of regexp.
21511 Normally only the current line is checked, but you can include NLINES extra
21512 lines both before and after point into the search.
21513 If VISUALLY is set, require that the cursor is not after the match but
21514 really on, so that the block visually is on the match."
21515 (catch 'exit
21516 (let ((pos (point))
21517 (eol (point-at-eol (+ 1 (or nlines 0))))
21518 (inc (if visually 1 0)))
21519 (save-excursion
21520 (beginning-of-line (- 1 (or nlines 0)))
21521 (while (re-search-forward re eol t)
21522 (if (and (<= (match-beginning 0) pos)
21523 (>= (+ inc (match-end 0)) pos))
21524 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21526 (defun org-at-regexp-p (regexp)
21527 "Is point inside a match of REGEXP in the current line?"
21528 (catch 'exit
21529 (save-excursion
21530 (let ((pos (point)) (end (point-at-eol)))
21531 (beginning-of-line 1)
21532 (while (re-search-forward regexp end t)
21533 (if (and (<= (match-beginning 0) pos)
21534 (>= (match-end 0) pos))
21535 (throw 'exit t)))
21536 nil))))
21538 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21539 "Non-nil when point is between matches of START-RE and END-RE.
21541 Also return a non-nil value when point is on one of the matches.
21543 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21544 buffer positions. Default values are the positions of headlines
21545 surrounding the point.
21547 The functions returns a cons cell whose car (resp. cdr) is the
21548 position before START-RE (resp. after END-RE)."
21549 (save-match-data
21550 (let ((pos (point))
21551 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21552 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21553 beg end)
21554 (save-excursion
21555 ;; Point is on a block when on START-RE or if START-RE can be
21556 ;; found before it...
21557 (and (or (org-at-regexp-p start-re)
21558 (re-search-backward start-re limit-up t))
21559 (setq beg (match-beginning 0))
21560 ;; ... and END-RE after it...
21561 (goto-char (match-end 0))
21562 (re-search-forward end-re limit-down t)
21563 (> (setq end (match-end 0)) pos)
21564 ;; ... without another START-RE in-between.
21565 (goto-char (match-beginning 0))
21566 (not (re-search-backward start-re (1+ beg) t))
21567 ;; Return value.
21568 (cons beg end))))))
21570 (defun org-in-block-p (names)
21571 "Non-nil when point belongs to a block whose name belongs to NAMES.
21573 NAMES is a list of strings containing names of blocks.
21575 Return first block name matched, or nil. Beware that in case of
21576 nested blocks, the returned name may not belong to the closest
21577 block from point."
21578 (save-match-data
21579 (catch 'exit
21580 (let ((case-fold-search t)
21581 (lim-up (save-excursion (outline-previous-heading)))
21582 (lim-down (save-excursion (outline-next-heading))))
21583 (mapc (lambda (name)
21584 (let ((n (regexp-quote name)))
21585 (when (org-between-regexps-p
21586 (concat "^[ \t]*#\\+begin_" n)
21587 (concat "^[ \t]*#\\+end_" n)
21588 lim-up lim-down)
21589 (throw 'exit n))))
21590 names))
21591 nil)))
21593 (defun org-in-drawer-p ()
21594 "Is point within a drawer?"
21595 (save-match-data
21596 (let ((case-fold-search t)
21597 (lim-up (save-excursion (outline-previous-heading)))
21598 (lim-down (save-excursion (outline-next-heading))))
21599 (org-between-regexps-p
21600 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21601 "^[ \t]*:end:.*$"
21602 lim-up lim-down))))
21604 (defun org-occur-in-agenda-files (regexp &optional nlines)
21605 "Call `multi-occur' with buffers for all agenda files."
21606 (interactive "sOrg-files matching: \np")
21607 (let* ((files (org-agenda-files))
21608 (tnames (mapcar 'file-truename files))
21609 (extra org-agenda-text-search-extra-files)
21611 (when (eq (car extra) 'agenda-archives)
21612 (setq extra (cdr extra))
21613 (setq files (org-add-archive-files files)))
21614 (while (setq f (pop extra))
21615 (unless (member (file-truename f) tnames)
21616 (add-to-list 'files f 'append)
21617 (add-to-list 'tnames (file-truename f) 'append)))
21618 (multi-occur
21619 (mapcar (lambda (x)
21620 (with-current-buffer
21621 (or (get-file-buffer x) (find-file-noselect x))
21622 (widen)
21623 (current-buffer)))
21624 files)
21625 regexp)))
21627 (if (boundp 'occur-mode-find-occurrence-hook)
21628 ;; Emacs 23
21629 (add-hook 'occur-mode-find-occurrence-hook
21630 (lambda ()
21631 (when (derived-mode-p 'org-mode)
21632 (org-reveal))))
21633 ;; Emacs 22
21634 (defadvice occur-mode-goto-occurrence
21635 (after org-occur-reveal activate)
21636 (and (derived-mode-p 'org-mode) (org-reveal)))
21637 (defadvice occur-mode-goto-occurrence-other-window
21638 (after org-occur-reveal activate)
21639 (and (derived-mode-p 'org-mode) (org-reveal)))
21640 (defadvice occur-mode-display-occurrence
21641 (after org-occur-reveal activate)
21642 (when (derived-mode-p 'org-mode)
21643 (let ((pos (occur-mode-find-occurrence)))
21644 (with-current-buffer (marker-buffer pos)
21645 (save-excursion
21646 (goto-char pos)
21647 (org-reveal)))))))
21649 (defun org-occur-link-in-agenda-files ()
21650 "Create a link and search for it in the agendas.
21651 The link is not stored in `org-stored-links', it is just created
21652 for the search purpose."
21653 (interactive)
21654 (let ((link (condition-case nil
21655 (org-store-link nil)
21656 (error "Unable to create a link to here"))))
21657 (org-occur-in-agenda-files (regexp-quote link))))
21659 (defun org-reverse-string (string)
21660 "Return the reverse of STRING."
21661 (apply 'string (reverse (string-to-list string))))
21663 (defsubst org-uniquify (list)
21664 "Non-destructively remove duplicate elements from LIST."
21665 (let ((res (copy-sequence list))) (delete-dups res)))
21667 (defun org-uniquify-alist (alist)
21668 "Merge elements of ALIST with the same key.
21670 For example, in this alist:
21672 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21673 => '((a 1 3) (b 2))
21675 merge (a 1) and (a 3) into (a 1 3).
21677 The function returns the new ALIST."
21678 (let (rtn)
21679 (mapc
21680 (lambda (e)
21681 (let (n)
21682 (if (not (assoc (car e) rtn))
21683 (push e rtn)
21684 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21685 (setq rtn (assq-delete-all (car e) rtn))
21686 (push n rtn))))
21687 alist)
21688 rtn))
21690 (defun org-delete-all (elts list)
21691 "Remove all elements in ELTS from LIST."
21692 (while elts
21693 (setq list (delete (pop elts) list)))
21694 list)
21696 (defun org-count (cl-item cl-seq)
21697 "Count the number of occurrences of ITEM in SEQ.
21698 Taken from `count' in cl-seq.el with all keyword arguments removed."
21699 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21700 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21701 (while (< cl-start cl-end)
21702 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21703 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21704 (setq cl-start (1+ cl-start)))
21705 cl-count))
21707 (defun org-remove-if (predicate seq)
21708 "Remove everything from SEQ that fulfills PREDICATE."
21709 (let (res e)
21710 (while seq
21711 (setq e (pop seq))
21712 (if (not (funcall predicate e)) (push e res)))
21713 (nreverse res)))
21715 (defun org-remove-if-not (predicate seq)
21716 "Remove everything from SEQ that does not fulfill PREDICATE."
21717 (let (res e)
21718 (while seq
21719 (setq e (pop seq))
21720 (if (funcall predicate e) (push e res)))
21721 (nreverse res)))
21723 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21724 "Reduce two-argument FUNCTION across SEQ.
21725 Taken from `reduce' in cl-seq.el with all keyword arguments but
21726 \":initial-value\" removed."
21727 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21728 (cadr (memq :initial-value cl-keys)))
21729 (cl-seq (pop cl-seq))
21730 (t (funcall cl-func)))))
21731 (while cl-seq
21732 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21733 cl-accum))
21735 (defun org-back-over-empty-lines ()
21736 "Move backwards over whitespace, to the beginning of the first empty line.
21737 Returns the number of empty lines passed."
21738 (let ((pos (point)))
21739 (if (cdr (assoc 'heading org-blank-before-new-entry))
21740 (skip-chars-backward " \t\n\r")
21741 (unless (eobp)
21742 (forward-line -1)))
21743 (beginning-of-line 2)
21744 (goto-char (min (point) pos))
21745 (count-lines (point) pos)))
21747 (defun org-skip-whitespace ()
21748 (skip-chars-forward " \t\n\r"))
21750 (defun org-point-in-group (point group &optional context)
21751 "Check if POINT is in match-group GROUP.
21752 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21753 match. If the match group does not exist or point is not inside it,
21754 return nil."
21755 (and (match-beginning group)
21756 (>= point (match-beginning group))
21757 (<= point (match-end group))
21758 (if context
21759 (list context (match-beginning group) (match-end group))
21760 t)))
21762 (defun org-switch-to-buffer-other-window (&rest args)
21763 "Switch to buffer in a second window on the current frame.
21764 In particular, do not allow pop-up frames.
21765 Returns the newly created buffer."
21766 (org-no-popups
21767 (apply 'switch-to-buffer-other-window args)))
21769 (defun org-combine-plists (&rest plists)
21770 "Create a single property list from all plists in PLISTS.
21771 The process starts by copying the first list, and then setting properties
21772 from the other lists. Settings in the last list are the most significant
21773 ones and overrule settings in the other lists."
21774 (let ((rtn (copy-sequence (pop plists)))
21775 p v ls)
21776 (while plists
21777 (setq ls (pop plists))
21778 (while ls
21779 (setq p (pop ls) v (pop ls))
21780 (setq rtn (plist-put rtn p v))))
21781 rtn))
21783 (defun org-replace-escapes (string table)
21784 "Replace %-escapes in STRING with values in TABLE.
21785 TABLE is an association list with keys like \"%a\" and string values.
21786 The sequences in STRING may contain normal field width and padding information,
21787 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21788 so values can contain further %-escapes if they are define later in TABLE."
21789 (let ((tbl (copy-alist table))
21790 (case-fold-search nil)
21791 (pchg 0)
21792 e re rpl)
21793 (while (setq e (pop tbl))
21794 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21795 (when (and (cdr e) (string-match re (cdr e)))
21796 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21797 (safe "SREF"))
21798 (add-text-properties 0 3 (list 'sref sref) safe)
21799 (setcdr e (replace-match safe t t (cdr e)))))
21800 (while (string-match re string)
21801 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21802 (cdr e)))
21803 (setq string (replace-match rpl t t string))))
21804 (while (setq pchg (next-property-change pchg string))
21805 (let ((sref (get-text-property pchg 'sref string)))
21806 (when (and sref (string-match "SREF" string pchg))
21807 (setq string (replace-match sref t t string)))))
21808 string))
21810 (defun org-sublist (list start end)
21811 "Return a section of LIST, from START to END.
21812 Counting starts at 1."
21813 (let (rtn (c start))
21814 (setq list (nthcdr (1- start) list))
21815 (while (and list (<= c end))
21816 (push (pop list) rtn)
21817 (setq c (1+ c)))
21818 (nreverse rtn)))
21820 (defun org-find-base-buffer-visiting (file)
21821 "Like `find-buffer-visiting' but always return the base buffer and
21822 not an indirect buffer."
21823 (let ((buf (or (get-file-buffer file)
21824 (find-buffer-visiting file))))
21825 (if buf
21826 (or (buffer-base-buffer buf) buf)
21827 nil)))
21829 (defun org-image-file-name-regexp (&optional extensions)
21830 "Return regexp matching the file names of images.
21831 If EXTENSIONS is given, only match these."
21832 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21833 (image-file-name-regexp)
21834 (let ((image-file-name-extensions
21835 (or extensions
21836 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21837 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21838 (concat "\\."
21839 (regexp-opt (nconc (mapcar 'upcase
21840 image-file-name-extensions)
21841 image-file-name-extensions)
21843 "\\'"))))
21845 (defun org-file-image-p (file &optional extensions)
21846 "Return non-nil if FILE is an image."
21847 (save-match-data
21848 (string-match (org-image-file-name-regexp extensions) file)))
21850 (defun org-get-cursor-date (&optional with-time)
21851 "Return the date at cursor in as a time.
21852 This works in the calendar and in the agenda, anywhere else it just
21853 returns the current time.
21854 If WITH-TIME is non-nil, returns the time of the event at point (in
21855 the agenda) or the current time of the day."
21856 (let (date day defd tp tm hod mod)
21857 (when with-time
21858 (setq tp (get-text-property (point) 'time))
21859 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21860 (setq hod (string-to-number (match-string 1 tp))
21861 mod (string-to-number (match-string 2 tp))))
21862 (or tp (setq hod (nth 2 (decode-time (current-time)))
21863 mod (nth 1 (decode-time (current-time))))))
21864 (cond
21865 ((eq major-mode 'calendar-mode)
21866 (setq date (calendar-cursor-to-date)
21867 defd (encode-time 0 (or mod 0) (or hod 0)
21868 (nth 1 date) (nth 0 date) (nth 2 date))))
21869 ((eq major-mode 'org-agenda-mode)
21870 (setq day (get-text-property (point) 'day))
21871 (if day
21872 (setq date (calendar-gregorian-from-absolute day)
21873 defd (encode-time 0 (or mod 0) (or hod 0)
21874 (nth 1 date) (nth 0 date) (nth 2 date))))))
21875 (or defd (current-time))))
21877 (defun org-mark-subtree (&optional up)
21878 "Mark the current subtree.
21879 This puts point at the start of the current subtree, and mark at
21880 the end. If a numeric prefix UP is given, move up into the
21881 hierarchy of headlines by UP levels before marking the subtree."
21882 (interactive "P")
21883 (org-with-limited-levels
21884 (cond ((org-at-heading-p) (beginning-of-line))
21885 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21886 (t (outline-previous-visible-heading 1))))
21887 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21888 (if (org-called-interactively-p 'any)
21889 (call-interactively 'org-mark-element)
21890 (org-mark-element)))
21893 ;;; Indentation
21895 (defun org-indent-line ()
21896 "Indent line depending on context."
21897 (interactive)
21898 (let* ((pos (point))
21899 (itemp (org-at-item-p))
21900 (case-fold-search t)
21901 (org-drawer-regexp (or org-drawer-regexp "\000"))
21902 (inline-task-p (and (featurep 'org-inlinetask)
21903 (org-inlinetask-in-task-p)))
21904 (inline-re (and inline-task-p
21905 (org-inlinetask-outline-regexp)))
21906 column)
21907 (if (and orgstruct-is-++ (eq pos (point)))
21908 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21909 (indent-according-to-mode))
21910 (beginning-of-line 1)
21911 (cond
21912 ;; Headings
21913 ((looking-at org-outline-regexp) (setq column 0))
21914 ;; Footnote definition
21915 ((looking-at org-footnote-definition-re) (setq column 0))
21916 ;; Literal examples
21917 ((looking-at "[ \t]*:\\( \\|$\\)")
21918 (setq column (org-get-indentation))) ; do nothing
21919 ;; Lists
21920 ((ignore-errors (goto-char (org-in-item-p)))
21921 (setq column (if itemp
21922 (org-get-indentation)
21923 (org-list-item-body-column (point))))
21924 (goto-char pos))
21925 ;; Drawers
21926 ((and (looking-at "[ \t]*:END:")
21927 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21928 (save-excursion
21929 (goto-char (1- (match-beginning 1)))
21930 (setq column (current-column))))
21931 ;; Special blocks
21932 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21933 (save-excursion
21934 (re-search-backward
21935 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21936 (setq column (org-get-indentation (match-string 0))))
21937 ((and (not (looking-at "[ \t]*#\\+begin_"))
21938 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21939 (save-excursion
21940 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21941 (setq column
21942 (cond ((equal (downcase (match-string 1)) "src")
21943 ;; src blocks: let `org-edit-src-exit' handle them
21944 (org-get-indentation))
21945 ((equal (downcase (match-string 1)) "example")
21946 (max (org-get-indentation)
21947 (org-get-indentation (match-string 0))))
21949 (org-get-indentation (match-string 0))))))
21950 ;; This line has nothing special, look at the previous relevant
21951 ;; line to compute indentation
21953 (beginning-of-line 0)
21954 (while (and (not (bobp))
21955 (not (looking-at org-table-line-regexp))
21956 (not (looking-at org-drawer-regexp))
21957 ;; When point started in an inline task, do not move
21958 ;; above task starting line.
21959 (not (and inline-task-p (looking-at inline-re)))
21960 ;; Skip drawers, blocks, empty lines, verbatim,
21961 ;; comments, tables, footnotes definitions, lists,
21962 ;; inline tasks.
21963 (or (and (looking-at "[ \t]*:END:")
21964 (re-search-backward org-drawer-regexp nil t))
21965 (and (looking-at "[ \t]*#\\+end_")
21966 (re-search-backward "[ \t]*#\\+begin_"nil t))
21967 (looking-at "[ \t]*[\n:#|]")
21968 (looking-at org-footnote-definition-re)
21969 (and (not inline-task-p)
21970 (featurep 'org-inlinetask)
21971 (org-inlinetask-in-task-p)
21972 (or (org-inlinetask-goto-beginning) t))))
21973 (beginning-of-line 0))
21974 (cond
21975 ;; There was a list item above.
21976 ((save-excursion
21977 (and (ignore-errors (goto-char (org-in-item-p)))
21978 (goto-char
21979 (org-list-get-top-point (org-list-struct)))))
21980 (looking-at org-list-full-item-re)
21981 (setq column (length (match-string 0))))
21982 ;; There was an heading above.
21983 ((looking-at "\\*+[ \t]+")
21984 (if (not org-adapt-indentation)
21985 (setq column 0)
21986 (goto-char (match-end 0))
21987 (setq column (current-column))))
21988 ;; A drawer had started and is unfinished
21989 ((looking-at org-drawer-regexp)
21990 (goto-char (1- (match-beginning 1)))
21991 (setq column (current-column)))
21992 ;; Else, nothing noticeable found: get indentation and go on.
21993 (t (setq column (org-get-indentation))))))
21994 ;; Now apply indentation and move cursor accordingly
21995 (goto-char pos)
21996 (if (<= (current-column) (current-indentation))
21997 (org-indent-line-to column)
21998 (save-excursion (org-indent-line-to column)))
21999 ;; Special polishing for properties, see `org-property-format'
22000 (setq column (current-column))
22001 (beginning-of-line 1)
22002 (if (looking-at
22003 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
22004 (replace-match (concat (match-string 1)
22005 (format org-property-format
22006 (match-string 2) (match-string 3)))
22007 t t))
22008 (org-move-to-column column))))
22010 (defun org-indent-drawer ()
22011 "Indent the drawer at point."
22012 (interactive)
22013 (let ((p (point))
22014 (e (and (save-excursion (re-search-forward ":END:" nil t))
22015 (match-end 0)))
22016 (folded
22017 (save-excursion
22018 (end-of-line)
22019 (when (overlays-at (point))
22020 (member 'invisible (overlay-properties
22021 (car (overlays-at (point)))))))))
22022 (when folded (org-cycle))
22023 (indent-for-tab-command)
22024 (while (and (move-beginning-of-line 2) (< (point) e))
22025 (indent-for-tab-command))
22026 (goto-char p)
22027 (when folded (org-cycle)))
22028 (message "Drawer at point indented"))
22030 (defun org-indent-block ()
22031 "Indent the block at point."
22032 (interactive)
22033 (let ((p (point))
22034 (case-fold-search t)
22035 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22036 (match-end 0)))
22037 (folded
22038 (save-excursion
22039 (end-of-line)
22040 (when (overlays-at (point))
22041 (member 'invisible (overlay-properties
22042 (car (overlays-at (point)))))))))
22043 (when folded (org-cycle))
22044 (indent-for-tab-command)
22045 (while (and (move-beginning-of-line 2) (< (point) e))
22046 (indent-for-tab-command))
22047 (goto-char p)
22048 (when folded (org-cycle)))
22049 (message "Block at point indented"))
22051 (defun org-indent-region (start end)
22052 "Indent region."
22053 (interactive "r")
22054 (save-excursion
22055 (let ((line-end (org-current-line end)))
22056 (goto-char start)
22057 (while (< (org-current-line) line-end)
22058 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22059 (t (call-interactively 'org-indent-line)))
22060 (move-beginning-of-line 2)))))
22063 ;;; Filling
22065 ;; We use our own fill-paragraph and auto-fill functions.
22067 ;; `org-fill-paragraph' relies on adaptive filling and context
22068 ;; checking. Appropriate `fill-prefix' is computed with
22069 ;; `org-adaptive-fill-function'.
22071 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22072 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22073 ;; `org-adaptive-fill-function' value. Internally,
22074 ;; `org-comment-line-break-function' breaks the line.
22076 ;; `org-setup-filling' installs filling and auto-filling related
22077 ;; variables during `org-mode' initialization.
22079 (defun org-setup-filling ()
22080 (interactive)
22081 ;; Prevent auto-fill from inserting unwanted new items.
22082 (when (boundp 'fill-nobreak-predicate)
22083 (org-set-local
22084 'fill-nobreak-predicate
22085 (org-uniquify
22086 (append fill-nobreak-predicate
22087 '(org-fill-paragraph-separate-nobreak-p
22088 org-fill-line-break-nobreak-p
22089 org-fill-paragraph-with-timestamp-nobreak-p)))))
22090 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22091 (org-set-local 'auto-fill-inhibit-regexp nil)
22092 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22093 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22094 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22096 (defvar org-element-paragraph-separate) ; org-element.el
22097 (defun org-fill-paragraph-separate-nobreak-p ()
22098 "Non-nil when a new line at point would end current paragraph."
22099 (looking-at (substring org-element-paragraph-separate 1)))
22101 (defun org-fill-line-break-nobreak-p ()
22102 "Non-nil when a new line at point would create an Org line break."
22103 (save-excursion
22104 (skip-chars-backward "[ \t]")
22105 (skip-chars-backward "\\\\")
22106 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22108 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22109 "Non-nil when a new line at point would split a timestamp."
22110 (and (org-at-timestamp-p t)
22111 (not (looking-at org-ts-regexp-both))))
22113 (declare-function message-in-body-p "message" ())
22114 (defvar orgtbl-line-start-regexp) ; From org-table.el
22115 (defun org-adaptive-fill-function ()
22116 "Compute a fill prefix for the current line.
22117 Return fill prefix, as a string, or nil if current line isn't
22118 meant to be filled."
22119 (let (prefix)
22120 (catch 'exit
22121 (when (derived-mode-p 'message-mode)
22122 (save-excursion
22123 (beginning-of-line)
22124 (cond ((or (not (message-in-body-p))
22125 (looking-at orgtbl-line-start-regexp))
22126 (throw 'exit nil))
22127 ((looking-at message-cite-prefix-regexp)
22128 (throw 'exit (match-string-no-properties 0)))
22129 ((looking-at org-outline-regexp)
22130 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22131 (org-with-wide-buffer
22132 (let* ((p (line-beginning-position))
22133 (element (save-excursion
22134 (beginning-of-line)
22135 (or (ignore-errors (org-element-at-point))
22136 (user-error "An element cannot be parsed line %d"
22137 (line-number-at-pos (point))))))
22138 (type (org-element-type element))
22139 (post-affiliated (org-element-property :post-affiliated element)))
22140 (unless (and post-affiliated (< p post-affiliated))
22141 (case type
22142 (comment (looking-at "[ \t]*# ?") (match-string 0))
22143 (footnote-definition "")
22144 ((item plain-list)
22145 (make-string (org-list-item-body-column
22146 (or post-affiliated
22147 (org-element-property :begin element)))
22148 ? ))
22149 (paragraph
22150 ;; Fill prefix is usually the same as the current line,
22151 ;; except if the paragraph is at the beginning of an item.
22152 (let ((parent (org-element-property :parent element)))
22153 (cond ((eq (org-element-type parent) 'item)
22154 (make-string (org-list-item-body-column
22155 (org-element-property :begin parent))
22156 ? ))
22157 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22158 (match-string 0))
22159 (t ""))))
22160 (comment-block
22161 ;; Only fill contents if P is within block boundaries.
22162 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22163 (forward-line)
22164 (point)))
22165 (cend (save-excursion
22166 (goto-char (org-element-property :end element))
22167 (skip-chars-backward " \r\t\n")
22168 (line-beginning-position))))
22169 (when (and (>= p cbeg) (< p cend))
22170 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22171 (match-string 0)
22172 "")))))))))))
22174 (declare-function message-goto-body "message" ())
22175 (defvar message-cite-prefix-regexp) ; From message.el
22176 (defun org-fill-paragraph (&optional justify)
22177 "Fill element at point, when applicable.
22179 This function only applies to comment blocks, comments, example
22180 blocks and paragraphs. Also, as a special case, re-align table
22181 when point is at one.
22183 If JUSTIFY is non-nil (interactively, with prefix argument),
22184 justify as well. If `sentence-end-double-space' is non-nil, then
22185 period followed by one space does not end a sentence, so don't
22186 break a line there. The variable `fill-column' controls the
22187 width for filling.
22189 For convenience, when point is at a plain list, an item or
22190 a footnote definition, try to fill the first paragraph within."
22191 (interactive)
22192 (if (and (derived-mode-p 'message-mode)
22193 (or (not (message-in-body-p))
22194 (save-excursion (move-beginning-of-line 1)
22195 (looking-at message-cite-prefix-regexp))))
22196 ;; First ensure filling is correct in message-mode.
22197 (let ((fill-paragraph-function
22198 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22199 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22200 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22201 (paragraph-separate
22202 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22203 (fill-paragraph nil))
22204 (with-syntax-table org-mode-transpose-word-syntax-table
22205 ;; Move to end of line in order to get the first paragraph
22206 ;; within a plain list or a footnote definition.
22207 (let ((element (save-excursion
22208 (end-of-line)
22209 (or (ignore-errors (org-element-at-point))
22210 (user-error "An element cannot be parsed line %d"
22211 (line-number-at-pos (point)))))))
22212 ;; First check if point is in a blank line at the beginning of
22213 ;; the buffer. In that case, ignore filling.
22214 (case (org-element-type element)
22215 ;; Use major mode filling function is src blocks.
22216 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22217 ;; Align Org tables, leave table.el tables as-is.
22218 (table-row (org-table-align) t)
22219 (table
22220 (when (eq (org-element-property :type element) 'org)
22221 (save-excursion
22222 (goto-char (org-element-property :post-affiliated element))
22223 (org-table-align)))
22225 (paragraph
22226 ;; Paragraphs may contain `line-break' type objects.
22227 (let ((beg (max (point-min)
22228 (org-element-property :contents-begin element)))
22229 (end (min (point-max)
22230 (org-element-property :contents-end element))))
22231 ;; Do nothing if point is at an affiliated keyword.
22232 (if (< (line-end-position) beg) t
22233 (when (derived-mode-p 'message-mode)
22234 ;; In `message-mode', do not fill following citation
22235 ;; in current paragraph nor text before message body.
22236 (let ((body-start (save-excursion (message-goto-body))))
22237 (when body-start (setq beg (max body-start beg))))
22238 (when (save-excursion
22239 (re-search-forward
22240 (concat "^" message-cite-prefix-regexp) end t))
22241 (setq end (match-beginning 0))))
22242 ;; Fill paragraph, taking line breaks into account.
22243 ;; For that, slice the paragraph using line breaks as
22244 ;; separators, and fill the parts in reverse order to
22245 ;; avoid messing with markers.
22246 (save-excursion
22247 (goto-char end)
22248 (mapc
22249 (lambda (pos)
22250 (fill-region-as-paragraph pos (point) justify)
22251 (goto-char pos))
22252 ;; Find the list of ending positions for line breaks
22253 ;; in the current paragraph. Add paragraph
22254 ;; beginning to include first slice.
22255 (nreverse
22256 (cons beg
22257 (org-element-map
22258 (org-element--parse-objects
22259 beg end nil (org-element-restriction 'paragraph))
22260 'line-break
22261 (lambda (lb) (org-element-property :end lb)))))))
22262 t)))
22263 ;; Contents of `comment-block' type elements should be
22264 ;; filled as plain text, but only if point is within block
22265 ;; markers.
22266 (comment-block
22267 (let* ((case-fold-search t)
22268 (beg (save-excursion
22269 (goto-char (org-element-property :begin element))
22270 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22271 (forward-line)
22272 (point)))
22273 (end (save-excursion
22274 (goto-char (org-element-property :end element))
22275 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22276 (line-beginning-position))))
22277 (when (and (>= (point) beg) (< (point) end))
22278 (fill-region-as-paragraph
22279 (save-excursion
22280 (end-of-line)
22281 (re-search-backward "^[ \t]*$" beg 'move)
22282 (line-beginning-position))
22283 (save-excursion
22284 (beginning-of-line)
22285 (re-search-forward "^[ \t]*$" end 'move)
22286 (line-beginning-position))
22287 justify)))
22289 ;; Fill comments.
22290 (comment
22291 (let ((begin (org-element-property :post-affiliated element))
22292 (end (save-excursion
22293 (goto-char (org-element-property :end element))
22294 (skip-chars-backward " \r\t\n")
22295 (line-end-position))))
22296 ;; Do not fill comments when at a blank line or at
22297 ;; affiliated keywords.
22298 (when (and (>= (point) begin) (<= (point) end))
22299 (let ((fill-prefix (save-excursion
22300 (beginning-of-line)
22301 (looking-at "[ \t]*#")
22302 (concat (match-string 0) " "))))
22303 (save-excursion
22304 (fill-region-as-paragraph begin end justify))))))
22305 ;; Ignore every other element.
22306 (otherwise t))))))
22308 (defun org-auto-fill-function ()
22309 "Auto-fill function."
22310 ;; Check if auto-filling is meaningful.
22311 (let ((fc (current-fill-column)))
22312 (when (and fc (> (current-column) fc))
22313 (let* ((fill-prefix (org-adaptive-fill-function))
22314 ;; Enforce empty fill prefix, if required. Otherwise, it
22315 ;; will be computed again.
22316 (adaptive-fill-mode (not (equal fill-prefix ""))))
22317 (when fill-prefix (do-auto-fill))))))
22319 (defun org-comment-line-break-function (&optional soft)
22320 "Break line at point and indent, continuing comment if within one.
22321 The inserted newline is marked hard if variable
22322 `use-hard-newlines' is true, unless optional argument SOFT is
22323 non-nil."
22324 (if soft (insert-and-inherit ?\n) (newline 1))
22325 (save-excursion (forward-char -1) (delete-horizontal-space))
22326 (delete-horizontal-space)
22327 (indent-to-left-margin)
22328 (insert-before-markers-and-inherit fill-prefix))
22331 ;;; Comments
22333 ;; Org comments syntax is quite complex. It requires the entire line
22334 ;; to be just a comment. Also, even with the right syntax at the
22335 ;; beginning of line, some some elements (i.e. verse-block or
22336 ;; example-block) don't accept comments. Usual Emacs comment commands
22337 ;; cannot cope with those requirements. Therefore, Org replaces them.
22339 ;; Org still relies on `comment-dwim', but cannot trust
22340 ;; `comment-only-p'. So, `comment-region-function' and
22341 ;; `uncomment-region-function' both point
22342 ;; to`org-comment-or-uncomment-region'. Eventually,
22343 ;; `org-insert-comment' takes care of insertion of comments at the
22344 ;; beginning of line.
22346 ;; `org-setup-comments-handling' install comments related variables
22347 ;; during `org-mode' initialization.
22349 (defun org-setup-comments-handling ()
22350 (interactive)
22351 (org-set-local 'comment-use-syntax nil)
22352 (org-set-local 'comment-start "# ")
22353 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22354 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22355 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22356 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22358 (defun org-insert-comment ()
22359 "Insert an empty comment above current line.
22360 If the line is empty, insert comment at its beginning."
22361 (beginning-of-line)
22362 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22363 (org-indent-line)
22364 (insert "# "))
22366 (defvar comment-empty-lines) ; From newcomment.el.
22367 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22368 "Comment or uncomment each non-blank line in the region.
22369 Uncomment each non-blank line between BEG and END if it only
22370 contains commented lines. Otherwise, comment them."
22371 (save-restriction
22372 ;; Restrict region
22373 (narrow-to-region (save-excursion (goto-char beg)
22374 (skip-chars-forward " \r\t\n" end)
22375 (line-beginning-position))
22376 (save-excursion (goto-char end)
22377 (skip-chars-backward " \r\t\n" beg)
22378 (line-end-position)))
22379 (let ((uncommentp
22380 ;; UNCOMMENTP is non-nil when every non blank line between
22381 ;; BEG and END is a comment.
22382 (save-excursion
22383 (goto-char (point-min))
22384 (while (and (not (eobp))
22385 (let ((element (org-element-at-point)))
22386 (and (eq (org-element-type element) 'comment)
22387 (goto-char (min (point-max)
22388 (org-element-property
22389 :end element)))))))
22390 (eobp))))
22391 (if uncommentp
22392 ;; Only blank lines and comments in region: uncomment it.
22393 (save-excursion
22394 (goto-char (point-min))
22395 (while (not (eobp))
22396 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22397 (replace-match "" nil nil nil 1))
22398 (forward-line)))
22399 ;; Comment each line in region.
22400 (let ((min-indent (point-max)))
22401 ;; First find the minimum indentation across all lines.
22402 (save-excursion
22403 (goto-char (point-min))
22404 (while (and (not (eobp)) (not (zerop min-indent)))
22405 (unless (looking-at "[ \t]*$")
22406 (setq min-indent (min min-indent (current-indentation))))
22407 (forward-line)))
22408 ;; Then loop over all lines.
22409 (save-excursion
22410 (goto-char (point-min))
22411 (while (not (eobp))
22412 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22413 ;; Don't get fooled by invisible text (e.g. link path)
22414 ;; when moving to column MIN-INDENT.
22415 (let ((buffer-invisibility-spec nil))
22416 (org-move-to-column min-indent t))
22417 (insert comment-start))
22418 (forward-line))))))))
22421 ;;; Planning
22423 ;; This section contains tools to operate on timestamp objects, as
22424 ;; returned by, e.g. `org-element-context'.
22426 (defun org-timestamp-has-time-p (timestamp)
22427 "Non-nil when TIMESTAMP has a time specified."
22428 (org-element-property :hour-start timestamp))
22430 (defun org-timestamp-format (timestamp format &optional end utc)
22431 "Format a TIMESTAMP element into a string.
22433 FORMAT is a format specifier to be passed to
22434 `format-time-string'.
22436 When optional argument END is non-nil, use end of date-range or
22437 time-range, if possible.
22439 When optional argument UTC is non-nil, time will be expressed as
22440 Universal Time."
22441 (format-time-string
22442 format
22443 (apply 'encode-time
22444 (cons 0
22445 (mapcar
22446 (lambda (prop) (or (org-element-property prop timestamp) 0))
22447 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22448 '(:minute-start :hour-start :day-start :month-start
22449 :year-start)))))
22450 utc))
22452 (defun org-timestamp-split-range (timestamp &optional end)
22453 "Extract a timestamp object from a date or time range.
22455 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22456 the end of the range. Otherwise, extract its start.
22458 Return a new timestamp object sharing the same parent as
22459 TIMESTAMP."
22460 (let ((type (org-element-property :type timestamp)))
22461 (if (memq type '(active inactive diary)) timestamp
22462 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22463 ;; Set new type.
22464 (org-element-put-property
22465 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22466 ;; Copy start properties over end properties if END is
22467 ;; non-nil. Otherwise, copy end properties over `start' ones.
22468 (let ((p-alist '((:minute-start . :minute-end)
22469 (:hour-start . :hour-end)
22470 (:day-start . :day-end)
22471 (:month-start . :month-end)
22472 (:year-start . :year-end))))
22473 (dolist (p-cell p-alist)
22474 (org-element-put-property
22475 split-ts
22476 (funcall (if end 'car 'cdr) p-cell)
22477 (org-element-property
22478 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22479 ;; Eventually refresh `:raw-value'.
22480 (org-element-put-property split-ts :raw-value nil)
22481 (org-element-put-property
22482 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22484 (defun org-timestamp-translate (timestamp &optional boundary)
22485 "Apply `org-translate-time' on a TIMESTAMP object.
22486 When optional argument BOUNDARY is non-nil, it is either the
22487 symbol `start' or `end'. In this case, only translate the
22488 starting or ending part of TIMESTAMP if it is a date or time
22489 range. Otherwise, translate both parts."
22490 (if (and (not boundary)
22491 (memq (org-element-property :type timestamp)
22492 '(active-range inactive-range)))
22493 (concat
22494 (org-translate-time
22495 (org-element-property :raw-value
22496 (org-timestamp-split-range timestamp)))
22497 "--"
22498 (org-translate-time
22499 (org-element-property :raw-value
22500 (org-timestamp-split-range timestamp t))))
22501 (org-translate-time
22502 (org-element-property
22503 :raw-value
22504 (if (not boundary) timestamp
22505 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22509 ;;; Other stuff.
22511 (defun org-toggle-fixed-width-section (arg)
22512 "Toggle the fixed-width export.
22513 If there is no active region, the QUOTE keyword at the current headline is
22514 inserted or removed. When present, it causes the text between this headline
22515 and the next to be exported as fixed-width text, and unmodified.
22516 If there is an active region, this command adds or removes a colon as the
22517 first character of this line. If the first character of a line is a colon,
22518 this line is also exported in fixed-width font."
22519 (interactive "P")
22520 (let* ((cc 0)
22521 (regionp (org-region-active-p))
22522 (beg (if regionp (region-beginning) (point)))
22523 (end (if regionp (region-end)))
22524 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22525 (case-fold-search nil)
22526 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22527 off)
22528 (if regionp
22529 (save-excursion
22530 (goto-char beg)
22531 (setq cc (current-column))
22532 (beginning-of-line 1)
22533 (setq off (looking-at re))
22534 (while (> nlines 0)
22535 (setq nlines (1- nlines))
22536 (beginning-of-line 1)
22537 (cond
22538 (arg
22539 (org-move-to-column cc t)
22540 (insert ": \n")
22541 (forward-line -1))
22542 ((and off (looking-at re))
22543 (replace-match "" t t nil 1))
22544 ((not off) (org-move-to-column cc t) (insert ": ")))
22545 (forward-line 1)))
22546 (save-excursion
22547 (org-back-to-heading)
22548 (cond
22549 ((looking-at (format org-heading-keyword-regexp-format
22550 org-quote-string))
22551 (goto-char (match-end 1))
22552 (looking-at (concat " +" org-quote-string))
22553 (replace-match "" t t)
22554 (when (eolp) (insert " ")))
22555 ((looking-at org-outline-regexp)
22556 (goto-char (match-end 0))
22557 (insert org-quote-string " ")))))))
22559 (defun org-reftex-citation ()
22560 "Use reftex-citation to insert a citation into the buffer.
22561 This looks for a line like
22563 #+BIBLIOGRAPHY: foo plain option:-d
22565 and derives from it that foo.bib is the bibliography file relevant
22566 for this document. It then installs the necessary environment for RefTeX
22567 to work in this buffer and calls `reftex-citation' to insert a citation
22568 into the buffer.
22570 Export of such citations to both LaTeX and HTML is handled by the contributed
22571 package org-exp-bibtex by Taru Karttunen."
22572 (interactive)
22573 (let ((reftex-docstruct-symbol 'rds)
22574 (reftex-cite-format "\\cite{%l}")
22575 rds bib)
22576 (save-excursion
22577 (save-restriction
22578 (widen)
22579 (let ((case-fold-search t)
22580 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22581 (if (not (save-excursion
22582 (or (re-search-forward re nil t)
22583 (re-search-backward re nil t))))
22584 (error "No bibliography defined in file")
22585 (setq bib (concat (match-string 1) ".bib")
22586 rds (list (list 'bib bib)))))))
22587 (call-interactively 'reftex-citation)))
22589 ;;;; Functions extending outline functionality
22591 (defun org-beginning-of-line (&optional arg)
22592 "Go to the beginning of the current line. If that is invisible, continue
22593 to a visible line beginning. This makes the function of C-a more intuitive.
22594 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22595 first attempt, and only move to after the tags when the cursor is already
22596 beyond the end of the headline."
22597 (interactive "P")
22598 (let ((pos (point))
22599 (special (if (consp org-special-ctrl-a/e)
22600 (car org-special-ctrl-a/e)
22601 org-special-ctrl-a/e))
22602 refpos)
22603 (if (org-bound-and-true-p visual-line-mode)
22604 (beginning-of-visual-line 1)
22605 (beginning-of-line 1))
22606 (if (and arg (fboundp 'move-beginning-of-line))
22607 (call-interactively 'move-beginning-of-line)
22608 (if (bobp)
22610 (backward-char 1)
22611 (if (org-truely-invisible-p)
22612 (while (and (not (bobp)) (org-truely-invisible-p))
22613 (backward-char 1)
22614 (beginning-of-line 1))
22615 (forward-char 1))))
22616 (when special
22617 (cond
22618 ((and (looking-at org-complex-heading-regexp)
22619 (= (char-after (match-end 1)) ?\ ))
22620 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22621 (point-at-eol)))
22622 (goto-char
22623 (if (eq special t)
22624 (cond ((> pos refpos) refpos)
22625 ((= pos (point)) refpos)
22626 (t (point)))
22627 (cond ((> pos (point)) (point))
22628 ((not (eq last-command this-command)) (point))
22629 (t refpos)))))
22630 ((org-at-item-p)
22631 ;; Being at an item and not looking at an the item means point
22632 ;; was previously moved to beginning of a visual line, which
22633 ;; doesn't contain the item. Therefore, do nothing special,
22634 ;; just stay here.
22635 (when (looking-at org-list-full-item-re)
22636 ;; Set special position at first white space character after
22637 ;; bullet, and check-box, if any.
22638 (let ((after-bullet
22639 (let ((box (match-end 3)))
22640 (if (not box) (match-end 1)
22641 (let ((after (char-after box)))
22642 (if (and after (= after ? )) (1+ box) box))))))
22643 ;; Special case: Move point to special position when
22644 ;; currently after it or at beginning of line.
22645 (if (eq special t)
22646 (when (or (> pos after-bullet) (= (point) pos))
22647 (goto-char after-bullet))
22648 ;; Reversed case: Move point to special position when
22649 ;; point was already at beginning of line and command is
22650 ;; repeated.
22651 (when (and (= (point) pos) (eq last-command this-command))
22652 (goto-char after-bullet))))))))
22653 (org-no-warnings
22654 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22656 (defun org-end-of-line (&optional arg)
22657 "Go to the end of the line.
22658 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22659 tags on the first attempt, and only move to after the tags when
22660 the cursor is already beyond the end of the headline."
22661 (interactive "P")
22662 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22663 org-special-ctrl-a/e))
22664 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22665 'end-of-visual-line)
22666 ((fboundp 'move-end-of-line) 'move-end-of-line)
22667 (t 'end-of-line))))
22668 (if (or (not special) arg) (call-interactively move-fun)
22669 (let* ((element (save-excursion (beginning-of-line)
22670 (org-element-at-point)))
22671 (type (org-element-type element)))
22672 (cond
22673 ((memq type '(headline inlinetask))
22674 (let ((pos (point)))
22675 (beginning-of-line 1)
22676 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22677 (if (eq special t)
22678 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22679 (goto-char (match-beginning 1))
22680 (goto-char (match-end 0)))
22681 (if (or (< pos (match-end 0))
22682 (not (eq this-command last-command)))
22683 (goto-char (match-end 0))
22684 (goto-char (match-beginning 1))))
22685 (call-interactively move-fun))))
22686 ((org-element-property :hiddenp element)
22687 ;; If element is hidden, `move-end-of-line' would put point
22688 ;; after it. Use `end-of-line' to stay on current line.
22689 (call-interactively 'end-of-line))
22690 (t (call-interactively move-fun)))))
22691 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22693 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22694 (define-key org-mode-map "\C-e" 'org-end-of-line)
22696 (defun org-backward-sentence (&optional arg)
22697 "Go to beginning of sentence, or beginning of table field.
22698 This will call `backward-sentence' or `org-table-beginning-of-field',
22699 depending on context."
22700 (interactive "P")
22701 (cond
22702 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22703 (t (call-interactively 'backward-sentence))))
22705 (defun org-forward-sentence (&optional arg)
22706 "Go to end of sentence, or end of table field.
22707 This will call `forward-sentence' or `org-table-end-of-field',
22708 depending on context."
22709 (interactive "P")
22710 (cond
22711 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22712 (t (call-interactively 'forward-sentence))))
22714 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22715 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22717 (defun org-kill-line (&optional arg)
22718 "Kill line, to tags or end of line."
22719 (interactive "P")
22720 (cond
22721 ((or (not org-special-ctrl-k)
22722 (bolp)
22723 (not (org-at-heading-p)))
22724 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22725 org-ctrl-k-protect-subtree)
22726 (if (or (eq org-ctrl-k-protect-subtree 'error)
22727 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22728 (user-error "C-k aborted as it would kill a hidden subtree")))
22729 (call-interactively
22730 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22731 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22732 (kill-region (point) (match-beginning 1))
22733 (org-set-tags nil t))
22734 (t (kill-region (point) (point-at-eol)))))
22736 (define-key org-mode-map "\C-k" 'org-kill-line)
22738 (defun org-yank (&optional arg)
22739 "Yank. If the kill is a subtree, treat it specially.
22740 This command will look at the current kill and check if is a single
22741 subtree, or a series of subtrees[1]. If it passes the test, and if the
22742 cursor is at the beginning of a line or after the stars of a currently
22743 empty headline, then the yank is handled specially. How exactly depends
22744 on the value of the following variables, both set by default.
22746 org-yank-folded-subtrees
22747 When set, the subtree(s) will be folded after insertion, but only
22748 if doing so would now swallow text after the yanked text.
22750 org-yank-adjusted-subtrees
22751 When set, the subtree will be promoted or demoted in order to
22752 fit into the local outline tree structure, which means that the level
22753 will be adjusted so that it becomes the smaller one of the two
22754 *visible* surrounding headings.
22756 Any prefix to this command will cause `yank' to be called directly with
22757 no special treatment. In particular, a simple \\[universal-argument] prefix \
22758 will just
22759 plainly yank the text as it is.
22761 \[1] The test checks if the first non-white line is a heading
22762 and if there are no other headings with fewer stars."
22763 (interactive "P")
22764 (org-yank-generic 'yank arg))
22766 (defun org-yank-generic (command arg)
22767 "Perform some yank-like command.
22769 This function implements the behavior described in the `org-yank'
22770 documentation. However, it has been generalized to work for any
22771 interactive command with similar behavior."
22773 ;; pretend to be command COMMAND
22774 (setq this-command command)
22776 (if arg
22777 (call-interactively command)
22779 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22780 (and (org-kill-is-subtree-p)
22781 (or (bolp)
22782 (and (looking-at "[ \t]*$")
22783 (string-match
22784 "\\`\\*+\\'"
22785 (buffer-substring (point-at-bol) (point)))))))
22786 swallowp)
22787 (cond
22788 ((and subtreep org-yank-folded-subtrees)
22789 (let ((beg (point))
22790 end)
22791 (if (and subtreep org-yank-adjusted-subtrees)
22792 (org-paste-subtree nil nil 'for-yank)
22793 (call-interactively command))
22795 (setq end (point))
22796 (goto-char beg)
22797 (when (and (bolp) subtreep
22798 (not (setq swallowp
22799 (org-yank-folding-would-swallow-text beg end))))
22800 (org-with-limited-levels
22801 (or (looking-at org-outline-regexp)
22802 (re-search-forward org-outline-regexp-bol end t))
22803 (while (and (< (point) end) (looking-at org-outline-regexp))
22804 (hide-subtree)
22805 (org-cycle-show-empty-lines 'folded)
22806 (condition-case nil
22807 (outline-forward-same-level 1)
22808 (error (goto-char end))))))
22809 (when swallowp
22810 (message
22811 "Inserted text not folded because that would swallow text"))
22813 (goto-char end)
22814 (skip-chars-forward " \t\n\r")
22815 (beginning-of-line 1)
22816 (push-mark beg 'nomsg)))
22817 ((and subtreep org-yank-adjusted-subtrees)
22818 (let ((beg (point-at-bol)))
22819 (org-paste-subtree nil nil 'for-yank)
22820 (push-mark beg 'nomsg)))
22822 (call-interactively command))))))
22824 (defun org-yank-folding-would-swallow-text (beg end)
22825 "Would hide-subtree at BEG swallow any text after END?"
22826 (let (level)
22827 (org-with-limited-levels
22828 (save-excursion
22829 (goto-char beg)
22830 (when (or (looking-at org-outline-regexp)
22831 (re-search-forward org-outline-regexp-bol end t))
22832 (setq level (org-outline-level)))
22833 (goto-char end)
22834 (skip-chars-forward " \t\r\n\v\f")
22835 (if (or (eobp)
22836 (and (bolp) (looking-at org-outline-regexp)
22837 (<= (org-outline-level) level)))
22838 nil ; Nothing would be swallowed
22839 t))))) ; something would swallow
22841 (define-key org-mode-map "\C-y" 'org-yank)
22843 (defun org-truely-invisible-p ()
22844 "Check if point is at a character currently not visible.
22845 This version does not only check the character property, but also
22846 `visible-mode'."
22847 ;; Early versions of noutline don't have `outline-invisible-p'.
22848 (if (org-bound-and-true-p visible-mode)
22850 (outline-invisible-p)))
22852 (defun org-invisible-p2 ()
22853 "Check if point is at a character currently not visible."
22854 (save-excursion
22855 (if (and (eolp) (not (bobp))) (backward-char 1))
22856 ;; Early versions of noutline don't have `outline-invisible-p'.
22857 (outline-invisible-p)))
22859 (defun org-back-to-heading (&optional invisible-ok)
22860 "Call `outline-back-to-heading', but provide a better error message."
22861 (condition-case nil
22862 (outline-back-to-heading invisible-ok)
22863 (error (error "Before first headline at position %d in buffer %s"
22864 (point) (current-buffer)))))
22866 (defun org-before-first-heading-p ()
22867 "Before first heading?"
22868 (save-excursion
22869 (end-of-line)
22870 (null (re-search-backward org-outline-regexp-bol nil t))))
22872 (defun org-at-heading-p (&optional ignored)
22873 (outline-on-heading-p t))
22874 ;; Compatibility alias with Org versions < 7.8.03
22875 (defalias 'org-on-heading-p 'org-at-heading-p)
22877 (defun org-at-comment-p nil
22878 "Is cursor in a line starting with a # character?"
22879 (save-excursion
22880 (beginning-of-line)
22881 (looking-at "^#")))
22883 (defun org-at-drawer-p nil
22884 "Is cursor at a drawer keyword?"
22885 (save-excursion
22886 (move-beginning-of-line 1)
22887 (looking-at org-drawer-regexp)))
22889 (defun org-at-block-p nil
22890 "Is cursor at a block keyword?"
22891 (save-excursion
22892 (move-beginning-of-line 1)
22893 (looking-at org-block-regexp)))
22895 (defun org-point-at-end-of-empty-headline ()
22896 "If point is at the end of an empty headline, return t, else nil.
22897 If the heading only contains a TODO keyword, it is still still considered
22898 empty."
22899 (and (looking-at "[ \t]*$")
22900 (when org-todo-line-regexp
22901 (save-excursion
22902 (beginning-of-line 1)
22903 (let ((case-fold-search nil))
22904 (looking-at org-todo-line-regexp)
22905 (string= (match-string 3) ""))))))
22907 (defun org-at-heading-or-item-p ()
22908 (or (org-at-heading-p) (org-at-item-p)))
22910 (defun org-at-target-p ()
22911 (or (org-in-regexp org-radio-target-regexp)
22912 (org-in-regexp org-target-regexp)))
22913 ;; Compatibility alias with Org versions < 7.8.03
22914 (defalias 'org-on-target-p 'org-at-target-p)
22916 (defun org-up-heading-all (arg)
22917 "Move to the heading line of which the present line is a subheading.
22918 This function considers both visible and invisible heading lines.
22919 With argument, move up ARG levels."
22920 (if (fboundp 'outline-up-heading-all)
22921 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22922 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22924 (defun org-up-heading-safe ()
22925 "Move to the heading line of which the present line is a subheading.
22926 This version will not throw an error. It will return the level of the
22927 headline found, or nil if no higher level is found.
22929 Also, this function will be a lot faster than `outline-up-heading',
22930 because it relies on stars being the outline starters. This can really
22931 make a significant difference in outlines with very many siblings."
22932 (let (start-level re)
22933 (org-back-to-heading t)
22934 (setq start-level (funcall outline-level))
22935 (if (equal start-level 1)
22937 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22938 (if (re-search-backward re nil t)
22939 (funcall outline-level)))))
22941 (defun org-first-sibling-p ()
22942 "Is this heading the first child of its parents?"
22943 (interactive)
22944 (let ((re org-outline-regexp-bol)
22945 level l)
22946 (unless (org-at-heading-p t)
22947 (user-error "Not at a heading"))
22948 (setq level (funcall outline-level))
22949 (save-excursion
22950 (if (not (re-search-backward re nil t))
22952 (setq l (funcall outline-level))
22953 (< l level)))))
22955 (defun org-goto-sibling (&optional previous)
22956 "Goto the next sibling, even if it is invisible.
22957 When PREVIOUS is set, go to the previous sibling instead. Returns t
22958 when a sibling was found. When none is found, return nil and don't
22959 move point."
22960 (let ((fun (if previous 're-search-backward 're-search-forward))
22961 (pos (point))
22962 (re org-outline-regexp-bol)
22963 level l)
22964 (when (condition-case nil (org-back-to-heading t) (error nil))
22965 (setq level (funcall outline-level))
22966 (catch 'exit
22967 (or previous (forward-char 1))
22968 (while (funcall fun re nil t)
22969 (setq l (funcall outline-level))
22970 (when (< l level) (goto-char pos) (throw 'exit nil))
22971 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22972 (goto-char pos)
22973 nil))))
22975 (defun org-show-siblings ()
22976 "Show all siblings of the current headline."
22977 (save-excursion
22978 (while (org-goto-sibling) (org-flag-heading nil)))
22979 (save-excursion
22980 (while (org-goto-sibling 'previous)
22981 (org-flag-heading nil))))
22983 (defun org-goto-first-child ()
22984 "Goto the first child, even if it is invisible.
22985 Return t when a child was found. Otherwise don't move point and
22986 return nil."
22987 (let (level (pos (point)) (re org-outline-regexp-bol))
22988 (when (condition-case nil (org-back-to-heading t) (error nil))
22989 (setq level (outline-level))
22990 (forward-char 1)
22991 (if (and (re-search-forward re nil t) (> (outline-level) level))
22992 (progn (goto-char (match-beginning 0)) t)
22993 (goto-char pos) nil))))
22995 (defun org-show-hidden-entry ()
22996 "Show an entry where even the heading is hidden."
22997 (save-excursion
22998 (org-show-entry)))
23000 (defun org-flag-heading (flag &optional entry)
23001 "Flag the current heading. FLAG non-nil means make invisible.
23002 When ENTRY is non-nil, show the entire entry."
23003 (save-excursion
23004 (org-back-to-heading t)
23005 ;; Check if we should show the entire entry
23006 (if entry
23007 (progn
23008 (org-show-entry)
23009 (save-excursion
23010 (and (outline-next-heading)
23011 (org-flag-heading nil))))
23012 (outline-flag-region (max (point-min) (1- (point)))
23013 (save-excursion (outline-end-of-heading) (point))
23014 flag))))
23016 (defun org-get-next-sibling ()
23017 "Move to next heading of the same level, and return point.
23018 If there is no such heading, return nil.
23019 This is like outline-next-sibling, but invisible headings are ok."
23020 (let ((level (funcall outline-level)))
23021 (outline-next-heading)
23022 (while (and (not (eobp)) (> (funcall outline-level) level))
23023 (outline-next-heading))
23024 (if (or (eobp) (< (funcall outline-level) level))
23026 (point))))
23028 (defun org-get-last-sibling ()
23029 "Move to previous heading of the same level, and return point.
23030 If there is no such heading, return nil."
23031 (let ((opoint (point))
23032 (level (funcall outline-level)))
23033 (outline-previous-heading)
23034 (when (and (/= (point) opoint) (outline-on-heading-p t))
23035 (while (and (> (funcall outline-level) level)
23036 (not (bobp)))
23037 (outline-previous-heading))
23038 (if (< (funcall outline-level) level)
23040 (point)))))
23042 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23043 "Goto to the end of a subtree."
23044 ;; This contains an exact copy of the original function, but it uses
23045 ;; `org-back-to-heading', to make it work also in invisible
23046 ;; trees. And is uses an invisible-ok argument.
23047 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23048 ;; Furthermore, when used inside Org, finding the end of a large subtree
23049 ;; with many children and grandchildren etc, this can be much faster
23050 ;; than the outline version.
23051 (org-back-to-heading invisible-ok)
23052 (let ((first t)
23053 (level (funcall outline-level)))
23054 (if (and (derived-mode-p 'org-mode) (< level 1000))
23055 ;; A true heading (not a plain list item), in Org-mode
23056 ;; This means we can easily find the end by looking
23057 ;; only for the right number of stars. Using a regexp to do
23058 ;; this is so much faster than using a Lisp loop.
23059 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23060 (forward-char 1)
23061 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23062 ;; something else, do it the slow way
23063 (while (and (not (eobp))
23064 (or first (> (funcall outline-level) level)))
23065 (setq first nil)
23066 (outline-next-heading)))
23067 (unless to-heading
23068 (if (memq (preceding-char) '(?\n ?\^M))
23069 (progn
23070 ;; Go to end of line before heading
23071 (forward-char -1)
23072 (if (memq (preceding-char) '(?\n ?\^M))
23073 ;; leave blank line before heading
23074 (forward-char -1))))))
23075 (point))
23077 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23078 "Use Org version in org-mode, for dramatic speed-up."
23079 (if (derived-mode-p 'org-mode)
23080 (progn
23081 (org-end-of-subtree nil t)
23082 (unless (eobp) (backward-char 1)))
23083 ad-do-it))
23085 (defun org-end-of-meta-data-and-drawers ()
23086 "Jump to the first text after meta data and drawers in the current entry.
23087 This will move over empty lines, lines with planning time stamps,
23088 clocking lines, and drawers."
23089 (org-back-to-heading t)
23090 (let ((end (save-excursion (outline-next-heading) (point)))
23091 (re (concat "\\(" org-drawer-regexp "\\)"
23092 "\\|" "[ \t]*" org-keyword-time-regexp)))
23093 (forward-line 1)
23094 (while (re-search-forward re end t)
23095 (if (not (match-end 1))
23096 ;; empty or planning line
23097 (forward-line 1)
23098 ;; a drawer, find the end
23099 (re-search-forward "^[ \t]*:END:" end 'move)
23100 (forward-line 1)))
23101 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23102 (point)))
23104 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23105 "Move forward to the ARG'th subheading at same level as this one.
23106 Stop at the first and last subheadings of a superior heading.
23107 Normally this only looks at visible headings, but when INVISIBLE-OK is
23108 non-nil it will also look at invisible ones."
23109 (interactive "p")
23110 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23111 (if (and arg (< arg 0))
23112 (goto-char (point-min))
23113 (outline-next-heading))
23114 (org-at-heading-p)
23115 (let ((level (- (match-end 0) (match-beginning 0) 1))
23116 (f (if (and arg (< arg 0))
23117 're-search-backward
23118 're-search-forward))
23119 (count (if arg (abs arg) 1))
23120 (result (point)))
23121 (while (and (prog1 (> count 0)
23122 (forward-char (if (and arg (< arg 0)) -1 1)))
23123 (funcall f org-outline-regexp-bol nil 'move))
23124 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23125 (cond ((< l level) (setq count 0))
23126 ((and (= l level)
23127 (or invisible-ok
23128 (progn
23129 (goto-char (line-beginning-position))
23130 (not (outline-invisible-p)))))
23131 (setq count (1- count))
23132 (when (eq l level)
23133 (setq result (point)))))))
23134 (goto-char result))
23135 (beginning-of-line 1)))
23137 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23138 "Move backward to the ARG'th subheading at same level as this one.
23139 Stop at the first and last subheadings of a superior heading."
23140 (interactive "p")
23141 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23143 (defun org-next-block (arg &optional backward block-regexp)
23144 "Jump to the next block.
23145 With a prefix argument ARG, jump forward ARG many source blocks.
23146 When BACKWARD is non-nil, jump to the previous block.
23147 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23148 (interactive "p")
23149 (let ((re (or block-regexp org-block-regexp))
23150 (re-search-fn (or (and backward 're-search-backward)
23151 're-search-forward)))
23152 (if (looking-at re) (forward-char 1))
23153 (condition-case nil
23154 (funcall re-search-fn re nil nil arg)
23155 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23156 (goto-char (match-beginning 0)) (org-show-context)))
23158 (defun org-previous-block (arg &optional block-regexp)
23159 "Jump to the previous block.
23160 With a prefix argument ARG, jump backward ARG many source blocks.
23161 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23162 (interactive "p")
23163 (org-next-block arg t block-regexp))
23165 (defun org-forward-element ()
23166 "Move forward by one element.
23167 Move to the next element at the same level, when possible."
23168 (interactive)
23169 (cond ((eobp) (user-error "Cannot move further down"))
23170 ((org-with-limited-levels (org-at-heading-p))
23171 (let ((origin (point)))
23172 (goto-char (org-end-of-subtree nil t))
23173 (unless (org-with-limited-levels (org-at-heading-p))
23174 (goto-char origin)
23175 (user-error "Cannot move further down"))))
23177 (let* ((elem (org-element-at-point))
23178 (end (org-element-property :end elem))
23179 (parent (org-element-property :parent elem)))
23180 (cond ((and parent (= (org-element-property :contents-end parent) end))
23181 (goto-char (org-element-property :end parent)))
23182 ((integer-or-marker-p end) (goto-char end))
23183 (t (message "No element at point")))))))
23185 (defun org-backward-element ()
23186 "Move backward by one element.
23187 Move to the previous element at the same level, when possible."
23188 (interactive)
23189 (cond ((bobp) (user-error "Cannot move further up"))
23190 ((org-with-limited-levels (org-at-heading-p))
23191 ;; At a headline, move to the previous one, if any, or stay
23192 ;; here.
23193 (let ((origin (point)))
23194 (org-with-limited-levels (org-backward-heading-same-level 1))
23195 ;; When current headline has no sibling above, move to its
23196 ;; parent.
23197 (when (= (point) origin)
23198 (or (org-with-limited-levels (org-up-heading-safe))
23199 (progn (goto-char origin)
23200 (user-error "Cannot move further up"))))))
23202 (let* ((trail (org-element-at-point 'keep-trail))
23203 (elem (car trail))
23204 (prev-elem (nth 1 trail))
23205 (beg (org-element-property :begin elem)))
23206 (cond
23207 ;; Move to beginning of current element if point isn't
23208 ;; there already.
23209 ((null beg) (message "No element at point"))
23210 ((/= (point) beg) (goto-char beg))
23211 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23212 ((org-before-first-heading-p) (goto-char (point-min)))
23213 (t (org-back-to-heading)))))))
23215 (defun org-up-element ()
23216 "Move to upper element."
23217 (interactive)
23218 (if (org-with-limited-levels (org-at-heading-p))
23219 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23220 (let* ((elem (org-element-at-point))
23221 (parent (org-element-property :parent elem)))
23222 (if parent (goto-char (org-element-property :begin parent))
23223 (if (org-with-limited-levels (org-before-first-heading-p))
23224 (user-error "No surrounding element")
23225 (org-with-limited-levels (org-back-to-heading)))))))
23227 (defvar org-element-greater-elements)
23228 (defun org-down-element ()
23229 "Move to inner element."
23230 (interactive)
23231 (let ((element (org-element-at-point)))
23232 (cond
23233 ((memq (org-element-type element) '(plain-list table))
23234 (goto-char (org-element-property :contents-begin element))
23235 (forward-char))
23236 ((memq (org-element-type element) org-element-greater-elements)
23237 ;; If contents are hidden, first disclose them.
23238 (when (org-element-property :hiddenp element) (org-cycle))
23239 (goto-char (or (org-element-property :contents-begin element)
23240 (user-error "No content for this element"))))
23241 (t (user-error "No inner element")))))
23243 (defun org-drag-element-backward ()
23244 "Move backward element at point."
23245 (interactive)
23246 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23247 (let* ((trail (org-element-at-point 'keep-trail))
23248 (elem (car trail))
23249 (prev-elem (nth 1 trail)))
23250 ;; Error out if no previous element or previous element is
23251 ;; a parent of the current one.
23252 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23253 (user-error "Cannot drag element backward")
23254 (let ((pos (point)))
23255 (org-element-swap-A-B prev-elem elem)
23256 (goto-char (+ (org-element-property :begin prev-elem)
23257 (- pos (org-element-property :begin elem)))))))))
23259 (defun org-drag-element-forward ()
23260 "Move forward element at point."
23261 (interactive)
23262 (let* ((pos (point))
23263 (elem (org-element-at-point)))
23264 (when (= (point-max) (org-element-property :end elem))
23265 (user-error "Cannot drag element forward"))
23266 (goto-char (org-element-property :end elem))
23267 (let ((next-elem (org-element-at-point)))
23268 (when (or (org-element-nested-p elem next-elem)
23269 (and (eq (org-element-type next-elem) 'headline)
23270 (not (eq (org-element-type elem) 'headline))))
23271 (goto-char pos)
23272 (user-error "Cannot drag element forward"))
23273 ;; Compute new position of point: it's shifted by NEXT-ELEM
23274 ;; body's length (without final blanks) and by the length of
23275 ;; blanks between ELEM and NEXT-ELEM.
23276 (let ((size-next (- (save-excursion
23277 (goto-char (org-element-property :end next-elem))
23278 (skip-chars-backward " \r\t\n")
23279 (forward-line)
23280 ;; Small correction if buffer doesn't end
23281 ;; with a newline character.
23282 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23283 (org-element-property :begin next-elem)))
23284 (size-blank (- (org-element-property :end elem)
23285 (save-excursion
23286 (goto-char (org-element-property :end elem))
23287 (skip-chars-backward " \r\t\n")
23288 (forward-line)
23289 (point)))))
23290 (org-element-swap-A-B elem next-elem)
23291 (goto-char (+ pos size-next size-blank))))))
23293 (defun org-drag-line-forward (arg)
23294 "Drag the line at point ARG lines forward."
23295 (interactive "p")
23296 (dotimes (n (abs arg))
23297 (let ((c (current-column)))
23298 (if (< 0 arg)
23299 (progn
23300 (beginning-of-line 2)
23301 (transpose-lines 1)
23302 (beginning-of-line 0))
23303 (transpose-lines 1)
23304 (beginning-of-line -1))
23305 (org-move-to-column c))))
23307 (defun org-drag-line-backward (arg)
23308 "Drag the line at point ARG lines backward."
23309 (interactive "p")
23310 (org-drag-line-forward (- arg)))
23312 (defun org-mark-element ()
23313 "Put point at beginning of this element, mark at end.
23315 Interactively, if this command is repeated or (in Transient Mark
23316 mode) if the mark is active, it marks the next element after the
23317 ones already marked."
23318 (interactive)
23319 (let (deactivate-mark)
23320 (if (and (org-called-interactively-p 'any)
23321 (or (and (eq last-command this-command) (mark t))
23322 (and transient-mark-mode mark-active)))
23323 (set-mark
23324 (save-excursion
23325 (goto-char (mark))
23326 (goto-char (org-element-property :end (org-element-at-point)))))
23327 (let ((element (org-element-at-point)))
23328 (end-of-line)
23329 (push-mark (org-element-property :end element) t t)
23330 (goto-char (org-element-property :begin element))))))
23332 (defun org-narrow-to-element ()
23333 "Narrow buffer to current element."
23334 (interactive)
23335 (let ((elem (org-element-at-point)))
23336 (cond
23337 ((eq (car elem) 'headline)
23338 (narrow-to-region
23339 (org-element-property :begin elem)
23340 (org-element-property :end elem)))
23341 ((memq (car elem) org-element-greater-elements)
23342 (narrow-to-region
23343 (org-element-property :contents-begin elem)
23344 (org-element-property :contents-end elem)))
23346 (narrow-to-region
23347 (org-element-property :begin elem)
23348 (org-element-property :end elem))))))
23350 (defun org-transpose-element ()
23351 "Transpose current and previous elements, keeping blank lines between.
23352 Point is moved after both elements."
23353 (interactive)
23354 (org-skip-whitespace)
23355 (let ((end (org-element-property :end (org-element-at-point))))
23356 (org-drag-element-backward)
23357 (goto-char end)))
23359 (defun org-unindent-buffer ()
23360 "Un-indent the visible part of the buffer.
23361 Relative indentation (between items, inside blocks, etc.) isn't
23362 modified."
23363 (interactive)
23364 (unless (eq major-mode 'org-mode)
23365 (user-error "Cannot un-indent a buffer not in Org mode"))
23366 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23367 unindent-tree ; For byte-compiler.
23368 (unindent-tree
23369 (function
23370 (lambda (contents)
23371 (mapc
23372 (lambda (element)
23373 (if (memq (org-element-type element) '(headline section))
23374 (funcall unindent-tree (org-element-contents element))
23375 (save-excursion
23376 (save-restriction
23377 (narrow-to-region
23378 (org-element-property :begin element)
23379 (org-element-property :end element))
23380 (org-do-remove-indentation)))))
23381 (reverse contents))))))
23382 (funcall unindent-tree (org-element-contents parse-tree))))
23384 (defun org-show-subtree ()
23385 "Show everything after this heading at deeper levels."
23386 (interactive)
23387 (outline-flag-region
23388 (point)
23389 (save-excursion
23390 (org-end-of-subtree t t))
23391 nil))
23393 (defun org-show-entry ()
23394 "Show the body directly following this heading.
23395 Show the heading too, if it is currently invisible."
23396 (interactive)
23397 (save-excursion
23398 (condition-case nil
23399 (progn
23400 (org-back-to-heading t)
23401 (outline-flag-region
23402 (max (point-min) (1- (point)))
23403 (save-excursion
23404 (if (re-search-forward
23405 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23406 (match-beginning 1)
23407 (point-max)))
23408 nil)
23409 (org-cycle-hide-drawers 'children))
23410 (error nil))))
23412 (defun org-make-options-regexp (kwds &optional extra)
23413 "Make a regular expression for keyword lines."
23414 (concat
23415 "^#\\+\\("
23416 (mapconcat 'regexp-quote kwds "\\|")
23417 (if extra (concat "\\|" extra))
23418 "\\):[ \t]*\\(.*\\)"))
23420 ;; Make isearch reveal the necessary context
23421 (defun org-isearch-end ()
23422 "Reveal context after isearch exits."
23423 (when isearch-success ; only if search was successful
23424 (if (featurep 'xemacs)
23425 ;; Under XEmacs, the hook is run in the correct place,
23426 ;; we directly show the context.
23427 (org-show-context 'isearch)
23428 ;; In Emacs the hook runs *before* restoring the overlays.
23429 ;; So we have to use a one-time post-command-hook to do this.
23430 ;; (Emacs 22 has a special variable, see function `org-mode')
23431 (unless (and (boundp 'isearch-mode-end-hook-quit)
23432 isearch-mode-end-hook-quit)
23433 ;; Only when the isearch was not quitted.
23434 (org-add-hook 'post-command-hook 'org-isearch-post-command
23435 'append 'local)))
23436 (org-fix-ellipsis-at-bol)))
23438 (defun org-isearch-post-command ()
23439 "Remove self from hook, and show context."
23440 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23441 (org-show-context 'isearch))
23444 ;;;; Integration with and fixes for other packages
23446 ;;; Imenu support
23448 (defvar org-imenu-markers nil
23449 "All markers currently used by Imenu.")
23450 (make-variable-buffer-local 'org-imenu-markers)
23452 (defun org-imenu-new-marker (&optional pos)
23453 "Return a new marker for use by Imenu, and remember the marker."
23454 (let ((m (make-marker)))
23455 (move-marker m (or pos (point)))
23456 (push m org-imenu-markers)
23459 (defun org-imenu-get-tree ()
23460 "Produce the index for Imenu."
23461 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23462 (setq org-imenu-markers nil)
23463 (let* ((n org-imenu-depth)
23464 (re (concat "^" (org-get-limited-outline-regexp)))
23465 (subs (make-vector (1+ n) nil))
23466 (last-level 0)
23467 m level head0 head)
23468 (save-excursion
23469 (save-restriction
23470 (widen)
23471 (goto-char (point-max))
23472 (while (re-search-backward re nil t)
23473 (setq level (org-reduced-level (funcall outline-level)))
23474 (when (and (<= level n)
23475 (looking-at org-complex-heading-regexp)
23476 (setq head0 (org-match-string-no-properties 4)))
23477 (setq head (org-link-display-format head0)
23478 m (org-imenu-new-marker))
23479 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23480 (if (>= level last-level)
23481 (push (cons head m) (aref subs level))
23482 (push (cons head (aref subs (1+ level))) (aref subs level))
23483 (loop for i from (1+ level) to n do (aset subs i nil)))
23484 (setq last-level level)))))
23485 (aref subs 1)))
23487 (eval-after-load "imenu"
23488 '(progn
23489 (add-hook 'imenu-after-jump-hook
23490 (lambda ()
23491 (if (derived-mode-p 'org-mode)
23492 (org-show-context 'org-goto))))))
23494 (defun org-link-display-format (link)
23495 "Replace a link with its the description.
23496 If there is no description, use the link target."
23497 (save-match-data
23498 (if (string-match org-bracket-link-analytic-regexp link)
23499 (replace-match (if (match-end 5)
23500 (match-string 5 link)
23501 (concat (match-string 1 link)
23502 (match-string 3 link)))
23503 nil t link)
23504 link)))
23506 (defun org-toggle-link-display ()
23507 "Toggle the literal or descriptive display of links."
23508 (interactive)
23509 (if org-descriptive-links
23510 (progn (org-remove-from-invisibility-spec '(org-link))
23511 (org-restart-font-lock)
23512 (setq org-descriptive-links nil))
23513 (progn (add-to-invisibility-spec '(org-link))
23514 (org-restart-font-lock)
23515 (setq org-descriptive-links t))))
23517 ;; Speedbar support
23519 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23520 "Overlay marking the agenda restriction line in speedbar.")
23521 (overlay-put org-speedbar-restriction-lock-overlay
23522 'face 'org-agenda-restriction-lock)
23523 (overlay-put org-speedbar-restriction-lock-overlay
23524 'help-echo "Agendas are currently limited to this item.")
23525 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23527 (defun org-speedbar-set-agenda-restriction ()
23528 "Restrict future agenda commands to the location at point in speedbar.
23529 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23530 (interactive)
23531 (require 'org-agenda)
23532 (let (p m tp np dir txt)
23533 (cond
23534 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23535 'org-imenu t))
23536 (setq m (get-text-property p 'org-imenu-marker))
23537 (with-current-buffer (marker-buffer m)
23538 (goto-char m)
23539 (org-agenda-set-restriction-lock 'subtree)))
23540 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23541 'speedbar-function 'speedbar-find-file))
23542 (setq tp (previous-single-property-change
23543 (1+ p) 'speedbar-function)
23544 np (next-single-property-change
23545 tp 'speedbar-function)
23546 dir (speedbar-line-directory)
23547 txt (buffer-substring-no-properties (or tp (point-min))
23548 (or np (point-max))))
23549 (with-current-buffer (find-file-noselect
23550 (let ((default-directory dir))
23551 (expand-file-name txt)))
23552 (unless (derived-mode-p 'org-mode)
23553 (user-error "Cannot restrict to non-Org-mode file"))
23554 (org-agenda-set-restriction-lock 'file)))
23555 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23556 (move-overlay org-speedbar-restriction-lock-overlay
23557 (point-at-bol) (point-at-eol))
23558 (setq current-prefix-arg nil)
23559 (org-agenda-maybe-redo)))
23561 (defvar speedbar-file-key-map)
23562 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23563 (eval-after-load "speedbar"
23564 '(progn
23565 (speedbar-add-supported-extension ".org")
23566 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23567 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23568 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23569 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23570 (add-hook 'speedbar-visiting-tag-hook
23571 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23573 ;;; Fixes and Hacks for problems with other packages
23575 ;; Make flyspell not check words in links, to not mess up our keymap
23576 (defvar org-element-affiliated-keywords) ; From org-element.el
23577 (defvar org-element-block-name-alist) ; From org-element.el
23578 (defun org-mode-flyspell-verify ()
23579 "Don't let flyspell put overlays at active buttons, or on
23580 {todo,all-time,additional-option-like}-keywords."
23581 (require 'org-element) ; For `org-element-affiliated-keywords'
23582 (let ((pos (max (1- (point)) (point-min)))
23583 (word (thing-at-point 'word)))
23584 (and (not (get-text-property pos 'keymap))
23585 (not (get-text-property pos 'org-no-flyspell))
23586 (not (member word org-todo-keywords-1))
23587 (not (member word org-all-time-keywords))
23588 (not (member word org-options-keywords))
23589 (not (member word (mapcar 'car org-startup-options)))
23590 (not (member-ignore-case word org-element-affiliated-keywords))
23591 (not (member-ignore-case word (org-get-export-keywords)))
23592 (not (member-ignore-case
23593 word (mapcar 'car org-element-block-name-alist)))
23594 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23596 (defun org-remove-flyspell-overlays-in (beg end)
23597 "Remove flyspell overlays in region."
23598 (and (org-bound-and-true-p flyspell-mode)
23599 (fboundp 'flyspell-delete-region-overlays)
23600 (flyspell-delete-region-overlays beg end))
23601 (add-text-properties beg end '(org-no-flyspell t)))
23603 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23604 (eval-after-load "bookmark"
23605 '(if (boundp 'bookmark-after-jump-hook)
23606 ;; We can use the hook
23607 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23608 ;; Hook not available, use advice
23609 (defadvice bookmark-jump (after org-make-visible activate)
23610 "Make the position visible."
23611 (org-bookmark-jump-unhide))))
23613 ;; Make sure saveplace shows the location if it was hidden
23614 (eval-after-load "saveplace"
23615 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23616 "Make the position visible."
23617 (org-bookmark-jump-unhide)))
23619 ;; Make sure ecb shows the location if it was hidden
23620 (eval-after-load "ecb"
23621 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23622 "Make hierarchy visible when jumping into location from ECB tree buffer."
23623 (if (derived-mode-p 'org-mode)
23624 (org-show-context))))
23626 (defun org-bookmark-jump-unhide ()
23627 "Unhide the current position, to show the bookmark location."
23628 (and (derived-mode-p 'org-mode)
23629 (or (outline-invisible-p)
23630 (save-excursion (goto-char (max (point-min) (1- (point))))
23631 (outline-invisible-p)))
23632 (org-show-context 'bookmark-jump)))
23634 ;; Make session.el ignore our circular variable
23635 (defvar session-globals-exclude)
23636 (eval-after-load "session"
23637 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23639 ;;;; Finish up
23641 (provide 'org)
23643 (run-hooks 'org-load-hook)
23645 ;;; org.el ends here