Let =`latexmk'= be an option to =`org-latex-pdf-process'=.
[org-mode.git] / lisp / org.el
blob97773a0989922367479707046f51ca3939e25fe9
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 '(choice (const nil) (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 '(choice (const nil) (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 vm-imap)
1771 (choice
1772 (const vm-visit-imap-folder)
1773 (const vm-visit-imap-folder-other-window)
1774 (const vm-visit-imap-folder-other-frame)))
1775 (cons (const gnus)
1776 (choice
1777 (const gnus)
1778 (const gnus-other-frame)
1779 (const org-gnus-no-new-news)))
1780 (cons (const file)
1781 (choice
1782 (const find-file)
1783 (const find-file-other-window)
1784 (const find-file-other-frame)))
1785 (cons (const wl)
1786 (choice
1787 (const wl)
1788 (const wl-other-frame)))))
1790 (defcustom org-display-internal-link-with-indirect-buffer nil
1791 "Non-nil means use indirect buffer to display infile links.
1792 Activating internal links (from one location in a file to another location
1793 in the same file) normally just jumps to the location. When the link is
1794 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1795 is displayed in
1796 another window. When this option is set, the other window actually displays
1797 an indirect buffer clone of the current buffer, to avoid any visibility
1798 changes to the current buffer."
1799 :group 'org-link-follow
1800 :type 'boolean)
1802 (defcustom org-open-non-existing-files nil
1803 "Non-nil means `org-open-file' will open non-existing files.
1804 When nil, an error will be generated.
1805 This variable applies only to external applications because they
1806 might choke on non-existing files. If the link is to a file that
1807 will be opened in Emacs, the variable is ignored."
1808 :group 'org-link-follow
1809 :type 'boolean)
1811 (defcustom org-open-directory-means-index-dot-org nil
1812 "Non-nil means a link to a directory really means to index.org.
1813 When nil, following a directory link will run dired or open a finder/explorer
1814 window on that directory."
1815 :group 'org-link-follow
1816 :type 'boolean)
1818 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1819 "Function and arguments to call for following mailto links.
1820 This is a list with the first element being a Lisp function, and the
1821 remaining elements being arguments to the function. In string arguments,
1822 %a will be replaced by the address, and %s will be replaced by the subject
1823 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1824 :group 'org-link-follow
1825 :type '(choice
1826 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1827 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1828 (const :tag "message-mail" (message-mail "%a" "%s"))
1829 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1831 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1832 "Non-nil means ask for confirmation before executing shell links.
1833 Shell links can be dangerous: just think about a link
1835 [[shell:rm -rf ~/*][Google Search]]
1837 This link would show up in your Org-mode document as \"Google Search\",
1838 but really it would remove your entire home directory.
1839 Therefore we advise against setting this variable to nil.
1840 Just change it to `y-or-n-p' if you want to confirm with a
1841 single keystroke rather than having to type \"yes\"."
1842 :group 'org-link-follow
1843 :type '(choice
1844 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1845 (const :tag "with y-or-n (faster)" y-or-n-p)
1846 (const :tag "no confirmation (dangerous)" nil)))
1847 (put 'org-confirm-shell-link-function
1848 'safe-local-variable
1849 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1851 (defcustom org-confirm-shell-link-not-regexp ""
1852 "A regexp to skip confirmation for shell links."
1853 :group 'org-link-follow
1854 :version "24.1"
1855 :type 'regexp)
1857 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1858 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1859 Elisp links can be dangerous: just think about a link
1861 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1863 This link would show up in your Org-mode document as \"Google Search\",
1864 but really it would remove your entire home directory.
1865 Therefore we advise against setting this variable to nil.
1866 Just change it to `y-or-n-p' if you want to confirm with a
1867 single keystroke rather than having to type \"yes\"."
1868 :group 'org-link-follow
1869 :type '(choice
1870 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1871 (const :tag "with y-or-n (faster)" y-or-n-p)
1872 (const :tag "no confirmation (dangerous)" nil)))
1873 (put 'org-confirm-shell-link-function
1874 'safe-local-variable
1875 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1877 (defcustom org-confirm-elisp-link-not-regexp ""
1878 "A regexp to skip confirmation for Elisp links."
1879 :group 'org-link-follow
1880 :version "24.1"
1881 :type 'regexp)
1883 (defconst org-file-apps-defaults-gnu
1884 '((remote . emacs)
1885 (system . mailcap)
1886 (t . mailcap))
1887 "Default file applications on a UNIX or GNU/Linux system.
1888 See `org-file-apps'.")
1890 (defconst org-file-apps-defaults-macosx
1891 '((remote . emacs)
1892 (t . "open %s")
1893 (system . "open %s")
1894 ("ps.gz" . "gv %s")
1895 ("eps.gz" . "gv %s")
1896 ("dvi" . "xdvi %s")
1897 ("fig" . "xfig %s"))
1898 "Default file applications on a MacOS X system.
1899 The system \"open\" is known as a default, but we use X11 applications
1900 for some files for which the OS does not have a good default.
1901 See `org-file-apps'.")
1903 (defconst org-file-apps-defaults-windowsnt
1904 (list
1905 '(remote . emacs)
1906 (cons t
1907 (list (if (featurep 'xemacs)
1908 'mswindows-shell-execute
1909 'w32-shell-execute)
1910 "open" 'file))
1911 (cons 'system
1912 (list (if (featurep 'xemacs)
1913 'mswindows-shell-execute
1914 'w32-shell-execute)
1915 "open" 'file)))
1916 "Default file applications on a Windows NT system.
1917 The system \"open\" is used for most files.
1918 See `org-file-apps'.")
1920 (defcustom org-file-apps
1921 '((auto-mode . emacs)
1922 ("\\.mm\\'" . default)
1923 ("\\.x?html?\\'" . default)
1924 ("\\.pdf\\'" . default))
1925 "External applications for opening `file:path' items in a document.
1926 Org-mode uses system defaults for different file types, but
1927 you can use this variable to set the application for a given file
1928 extension. The entries in this list are cons cells where the car identifies
1929 files and the cdr the corresponding command. Possible values for the
1930 file identifier are
1931 \"string\" A string as a file identifier can be interpreted in different
1932 ways, depending on its contents:
1934 - Alphanumeric characters only:
1935 Match links with this file extension.
1936 Example: (\"pdf\" . \"evince %s\")
1937 to open PDFs with evince.
1939 - Regular expression: Match links where the
1940 filename matches the regexp. If you want to
1941 use groups here, use shy groups.
1943 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1944 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1945 to open *.html and *.xhtml with firefox.
1947 - Regular expression which contains (non-shy) groups:
1948 Match links where the whole link, including \"::\", and
1949 anything after that, matches the regexp.
1950 In a custom command string, %1, %2, etc. are replaced with
1951 the parts of the link that were matched by the groups.
1952 For backwards compatibility, if a command string is given
1953 that does not use any of the group matches, this case is
1954 handled identically to the second one (i.e. match against
1955 file name only).
1956 In a custom lisp form, you can access the group matches with
1957 (match-string n link).
1959 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1960 to open [[file:document.pdf::5]] with evince at page 5.
1962 `directory' Matches a directory
1963 `remote' Matches a remote file, accessible through tramp or efs.
1964 Remote files most likely should be visited through Emacs
1965 because external applications cannot handle such paths.
1966 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1967 so all files Emacs knows how to handle. Using this with
1968 command `emacs' will open most files in Emacs. Beware that this
1969 will also open html files inside Emacs, unless you add
1970 (\"html\" . default) to the list as well.
1971 t Default for files not matched by any of the other options.
1972 `system' The system command to open files, like `open' on Windows
1973 and Mac OS X, and mailcap under GNU/Linux. This is the command
1974 that will be selected if you call `C-c C-o' with a double
1975 \\[universal-argument] \\[universal-argument] prefix.
1977 Possible values for the command are:
1978 `emacs' The file will be visited by the current Emacs process.
1979 `default' Use the default application for this file type, which is the
1980 association for t in the list, most likely in the system-specific
1981 part.
1982 This can be used to overrule an unwanted setting in the
1983 system-specific variable.
1984 `system' Use the system command for opening files, like \"open\".
1985 This command is specified by the entry whose car is `system'.
1986 Most likely, the system-specific version of this variable
1987 does define this command, but you can overrule/replace it
1988 here.
1989 string A command to be executed by a shell; %s will be replaced
1990 by the path to the file.
1991 sexp A Lisp form which will be evaluated. The file path will
1992 be available in the Lisp variable `file'.
1993 For more examples, see the system specific constants
1994 `org-file-apps-defaults-macosx'
1995 `org-file-apps-defaults-windowsnt'
1996 `org-file-apps-defaults-gnu'."
1997 :group 'org-link-follow
1998 :type '(repeat
1999 (cons (choice :value ""
2000 (string :tag "Extension")
2001 (const :tag "System command to open files" system)
2002 (const :tag "Default for unrecognized files" t)
2003 (const :tag "Remote file" remote)
2004 (const :tag "Links to a directory" directory)
2005 (const :tag "Any files that have Emacs modes"
2006 auto-mode))
2007 (choice :value ""
2008 (const :tag "Visit with Emacs" emacs)
2009 (const :tag "Use default" default)
2010 (const :tag "Use the system command" system)
2011 (string :tag "Command")
2012 (sexp :tag "Lisp form")))))
2014 (defcustom org-doi-server-url "http://dx.doi.org/"
2015 "The URL of the DOI server."
2016 :type 'string
2017 :version "24.3"
2018 :group 'org-link-follow)
2020 (defgroup org-refile nil
2021 "Options concerning refiling entries in Org-mode."
2022 :tag "Org Refile"
2023 :group 'org)
2025 (defcustom org-directory "~/org"
2026 "Directory with org files.
2027 This is just a default location to look for Org files. There is no need
2028 at all to put your files into this directory. It is only used in the
2029 following situations:
2031 1. When a capture template specifies a target file that is not an
2032 absolute path. The path will then be interpreted relative to
2033 `org-directory'
2034 2. When a capture note is filed away in an interactive way (when exiting the
2035 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2036 with `org-directory' as the default path."
2037 :group 'org-refile
2038 :group 'org-remember
2039 :group 'org-capture
2040 :type 'directory)
2042 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2043 "Default target for storing notes.
2044 Used as a fall back file for org-remember.el and org-capture.el, for
2045 templates that do not specify a target file."
2046 :group 'org-refile
2047 :group 'org-remember
2048 :group 'org-capture
2049 :type '(choice
2050 (const :tag "Default from remember-data-file" nil)
2051 file))
2053 (defcustom org-goto-interface 'outline
2054 "The default interface to be used for `org-goto'.
2055 Allowed values are:
2056 outline The interface shows an outline of the relevant file
2057 and the correct heading is found by moving through
2058 the outline or by searching with incremental search.
2059 outline-path-completion Headlines in the current buffer are offered via
2060 completion. This is the interface also used by
2061 the refile command."
2062 :group 'org-refile
2063 :type '(choice
2064 (const :tag "Outline" outline)
2065 (const :tag "Outline-path-completion" outline-path-completion)))
2067 (defcustom org-goto-max-level 5
2068 "Maximum target level when running `org-goto' with refile interface."
2069 :group 'org-refile
2070 :type 'integer)
2072 (defcustom org-reverse-note-order nil
2073 "Non-nil means store new notes at the beginning of a file or entry.
2074 When nil, new notes will be filed to the end of a file or entry.
2075 This can also be a list with cons cells of regular expressions that
2076 are matched against file names, and values."
2077 :group 'org-remember
2078 :group 'org-capture
2079 :group 'org-refile
2080 :type '(choice
2081 (const :tag "Reverse always" t)
2082 (const :tag "Reverse never" nil)
2083 (repeat :tag "By file name regexp"
2084 (cons regexp boolean))))
2086 (defcustom org-log-refile nil
2087 "Information to record when a task is refiled.
2089 Possible values are:
2091 nil Don't add anything
2092 time Add a time stamp to the task
2093 note Prompt for a note and add it with template `org-log-note-headings'
2095 This option can also be set with on a per-file-basis with
2097 #+STARTUP: nologrefile
2098 #+STARTUP: logrefile
2099 #+STARTUP: lognoterefile
2101 You can have local logging settings for a subtree by setting the LOGGING
2102 property to one or more of these keywords.
2104 When bulk-refiling from the agenda, the value `note' is forbidden and
2105 will temporarily be changed to `time'."
2106 :group 'org-refile
2107 :group 'org-progress
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "No logging" nil)
2111 (const :tag "Record timestamp" time)
2112 (const :tag "Record timestamp with note." note)))
2114 (defcustom org-refile-targets nil
2115 "Targets for refiling entries with \\[org-refile].
2116 This is a list of cons cells. Each cell contains:
2117 - a specification of the files to be considered, either a list of files,
2118 or a symbol whose function or variable value will be used to retrieve
2119 a file name or a list of file names. If you use `org-agenda-files' for
2120 that, all agenda files will be scanned for targets. Nil means consider
2121 headings in the current buffer.
2122 - A specification of how to find candidate refile targets. This may be
2123 any of:
2124 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2125 This tag has to be present in all target headlines, inheritance will
2126 not be considered.
2127 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2128 todo keyword.
2129 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2130 headlines that are refiling targets.
2131 - a cons cell (:level . N). Any headline of level N is considered a target.
2132 Note that, when `org-odd-levels-only' is set, level corresponds to
2133 order in hierarchy, not to the number of stars.
2134 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2135 Note that, when `org-odd-levels-only' is set, level corresponds to
2136 order in hierarchy, not to the number of stars.
2138 Each element of this list generates a set of possible targets.
2139 The union of these sets is presented (with completion) to
2140 the user by `org-refile'.
2142 You can set the variable `org-refile-target-verify-function' to a function
2143 to verify each headline found by the simple criteria above.
2145 When this variable is nil, all top-level headlines in the current buffer
2146 are used, equivalent to the value `((nil . (:level . 1))'."
2147 :group 'org-refile
2148 :type '(repeat
2149 (cons
2150 (choice :value org-agenda-files
2151 (const :tag "All agenda files" org-agenda-files)
2152 (const :tag "Current buffer" nil)
2153 (function) (variable) (file))
2154 (choice :tag "Identify target headline by"
2155 (cons :tag "Specific tag" (const :value :tag) (string))
2156 (cons :tag "TODO keyword" (const :value :todo) (string))
2157 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2158 (cons :tag "Level number" (const :value :level) (integer))
2159 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2161 (defcustom org-refile-target-verify-function nil
2162 "Function to verify if the headline at point should be a refile target.
2163 The function will be called without arguments, with point at the
2164 beginning of the headline. It should return t and leave point
2165 where it is if the headline is a valid target for refiling.
2167 If the target should not be selected, the function must return nil.
2168 In addition to this, it may move point to a place from where the search
2169 should be continued. For example, the function may decide that the entire
2170 subtree of the current entry should be excluded and move point to the end
2171 of the subtree."
2172 :group 'org-refile
2173 :type '(choice
2174 (const nil)
2175 (function)))
2177 (defcustom org-refile-use-cache nil
2178 "Non-nil means cache refile targets to speed up the process.
2179 The cache for a particular file will be updated automatically when
2180 the buffer has been killed, or when any of the marker used for flagging
2181 refile targets no longer points at a live buffer.
2182 If you have added new entries to a buffer that might themselves be targets,
2183 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2184 find that easier, `C-u C-u C-u C-c C-w'."
2185 :group 'org-refile
2186 :version "24.1"
2187 :type 'boolean)
2189 (defcustom org-refile-use-outline-path nil
2190 "Non-nil means provide refile targets as paths.
2191 So a level 3 headline will be available as level1/level2/level3.
2193 When the value is `file', also include the file name (without directory)
2194 into the path. In this case, you can also stop the completion after
2195 the file name, to get entries inserted as top level in the file.
2197 When `full-file-path', include the full file path."
2198 :group 'org-refile
2199 :type '(choice
2200 (const :tag "Not" nil)
2201 (const :tag "Yes" t)
2202 (const :tag "Start with file name" file)
2203 (const :tag "Start with full file path" full-file-path)))
2205 (defcustom org-outline-path-complete-in-steps t
2206 "Non-nil means complete the outline path in hierarchical steps.
2207 When Org-mode uses the refile interface to select an outline path
2208 \(see variable `org-refile-use-outline-path'), the completion of
2209 the path can be done is a single go, or if can be done in steps down
2210 the headline hierarchy. Going in steps is probably the best if you
2211 do not use a special completion package like `ido' or `icicles'.
2212 However, when using these packages, going in one step can be very
2213 fast, while still showing the whole path to the entry."
2214 :group 'org-refile
2215 :type 'boolean)
2217 (defcustom org-refile-allow-creating-parent-nodes nil
2218 "Non-nil means allow to create new nodes as refile targets.
2219 New nodes are then created by adding \"/new node name\" to the completion
2220 of an existing node. When the value of this variable is `confirm',
2221 new node creation must be confirmed by the user (recommended)
2222 When nil, the completion must match an existing entry.
2224 Note that, if the new heading is not seen by the criteria
2225 listed in `org-refile-targets', multiple instances of the same
2226 heading would be created by trying again to file under the new
2227 heading."
2228 :group 'org-refile
2229 :type '(choice
2230 (const :tag "Never" nil)
2231 (const :tag "Always" t)
2232 (const :tag "Prompt for confirmation" confirm)))
2234 (defcustom org-refile-active-region-within-subtree nil
2235 "Non-nil means also refile active region within a subtree.
2237 By default `org-refile' doesn't allow refiling regions if they
2238 don't contain a set of subtrees, but it might be convenient to
2239 do so sometimes: in that case, the first line of the region is
2240 converted to a headline before refiling."
2241 :group 'org-refile
2242 :version "24.1"
2243 :type 'boolean)
2245 (defgroup org-todo nil
2246 "Options concerning TODO items in Org-mode."
2247 :tag "Org TODO"
2248 :group 'org)
2250 (defgroup org-progress nil
2251 "Options concerning Progress logging in Org-mode."
2252 :tag "Org Progress"
2253 :group 'org-time)
2255 (defvar org-todo-interpretation-widgets
2256 '((:tag "Sequence (cycling hits every state)" sequence)
2257 (:tag "Type (cycling directly to DONE)" type))
2258 "The available interpretation symbols for customizing `org-todo-keywords'.
2259 Interested libraries should add to this list.")
2261 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2262 "List of TODO entry keyword sequences and their interpretation.
2263 \\<org-mode-map>This is a list of sequences.
2265 Each sequence starts with a symbol, either `sequence' or `type',
2266 indicating if the keywords should be interpreted as a sequence of
2267 action steps, or as different types of TODO items. The first
2268 keywords are states requiring action - these states will select a headline
2269 for inclusion into the global TODO list Org-mode produces. If one of
2270 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2271 signify that no further action is necessary. If \"|\" is not found,
2272 the last keyword is treated as the only DONE state of the sequence.
2274 The command \\[org-todo] cycles an entry through these states, and one
2275 additional state where no keyword is present. For details about this
2276 cycling, see the manual.
2278 TODO keywords and interpretation can also be set on a per-file basis with
2279 the special #+SEQ_TODO and #+TYP_TODO lines.
2281 Each keyword can optionally specify a character for fast state selection
2282 \(in combination with the variable `org-use-fast-todo-selection')
2283 and specifiers for state change logging, using the same syntax that
2284 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2285 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2286 indicates to record a time stamp each time this state is selected.
2288 Each keyword may also specify if a timestamp or a note should be
2289 recorded when entering or leaving the state, by adding additional
2290 characters in the parenthesis after the keyword. This looks like this:
2291 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2292 record only the time of the state change. With X and Y being either
2293 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2294 Y when leaving the state if and only if the *target* state does not
2295 define X. You may omit any of the fast-selection key or X or /Y,
2296 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2298 For backward compatibility, this variable may also be just a list
2299 of keywords. In this case the interpretation (sequence or type) will be
2300 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2301 :group 'org-todo
2302 :group 'org-keywords
2303 :type '(choice
2304 (repeat :tag "Old syntax, just keywords"
2305 (string :tag "Keyword"))
2306 (repeat :tag "New syntax"
2307 (cons
2308 (choice
2309 :tag "Interpretation"
2310 ;;Quick and dirty way to see
2311 ;;`org-todo-interpretations'. This takes the
2312 ;;place of item arguments
2313 :convert-widget
2314 (lambda (widget)
2315 (widget-put widget
2316 :args (mapcar
2317 #'(lambda (x)
2318 (widget-convert
2319 (cons 'const x)))
2320 org-todo-interpretation-widgets))
2321 widget))
2322 (repeat
2323 (string :tag "Keyword"))))))
2325 (defvar org-todo-keywords-1 nil
2326 "All TODO and DONE keywords active in a buffer.")
2327 (make-variable-buffer-local 'org-todo-keywords-1)
2328 (defvar org-todo-keywords-for-agenda nil)
2329 (defvar org-done-keywords-for-agenda nil)
2330 (defvar org-drawers-for-agenda nil)
2331 (defvar org-todo-keyword-alist-for-agenda nil)
2332 (defvar org-tag-alist-for-agenda nil
2333 "Alist of all tags from all agenda files.")
2334 (defvar org-tag-groups-alist-for-agenda nil
2335 "Alist of all groups tags from all current agenda files.")
2336 (defvar org-tag-groups-alist nil)
2337 (make-variable-buffer-local 'org-tag-groups-alist)
2338 (defvar org-agenda-contributing-files nil)
2339 (defvar org-not-done-keywords nil)
2340 (make-variable-buffer-local 'org-not-done-keywords)
2341 (defvar org-done-keywords nil)
2342 (make-variable-buffer-local 'org-done-keywords)
2343 (defvar org-todo-heads nil)
2344 (make-variable-buffer-local 'org-todo-heads)
2345 (defvar org-todo-sets nil)
2346 (make-variable-buffer-local 'org-todo-sets)
2347 (defvar org-todo-log-states nil)
2348 (make-variable-buffer-local 'org-todo-log-states)
2349 (defvar org-todo-kwd-alist nil)
2350 (make-variable-buffer-local 'org-todo-kwd-alist)
2351 (defvar org-todo-key-alist nil)
2352 (make-variable-buffer-local 'org-todo-key-alist)
2353 (defvar org-todo-key-trigger nil)
2354 (make-variable-buffer-local 'org-todo-key-trigger)
2356 (defcustom org-todo-interpretation 'sequence
2357 "Controls how TODO keywords are interpreted.
2358 This variable is in principle obsolete and is only used for
2359 backward compatibility, if the interpretation of todo keywords is
2360 not given already in `org-todo-keywords'. See that variable for
2361 more information."
2362 :group 'org-todo
2363 :group 'org-keywords
2364 :type '(choice (const sequence)
2365 (const type)))
2367 (defcustom org-use-fast-todo-selection t
2368 "Non-nil means use the fast todo selection scheme with C-c C-t.
2369 This variable describes if and under what circumstances the cycling
2370 mechanism for TODO keywords will be replaced by a single-key, direct
2371 selection scheme.
2373 When nil, fast selection is never used.
2375 When the symbol `prefix', it will be used when `org-todo' is called
2376 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2377 `C-u t' in an agenda buffer.
2379 When t, fast selection is used by default. In this case, the prefix
2380 argument forces cycling instead.
2382 In all cases, the special interface is only used if access keys have
2383 actually been assigned by the user, i.e. if keywords in the configuration
2384 are followed by a letter in parenthesis, like TODO(t)."
2385 :group 'org-todo
2386 :type '(choice
2387 (const :tag "Never" nil)
2388 (const :tag "By default" t)
2389 (const :tag "Only with C-u C-c C-t" prefix)))
2391 (defcustom org-provide-todo-statistics t
2392 "Non-nil means update todo statistics after insert and toggle.
2393 ALL-HEADLINES means update todo statistics by including headlines
2394 with no TODO keyword as well, counting them as not done.
2395 A list of TODO keywords means the same, but skip keywords that are
2396 not in this list.
2398 When this is set, todo statistics is updated in the parent of the
2399 current entry each time a todo state is changed."
2400 :group 'org-todo
2401 :type '(choice
2402 (const :tag "Yes, only for TODO entries" t)
2403 (const :tag "Yes, including all entries" 'all-headlines)
2404 (repeat :tag "Yes, for TODOs in this list"
2405 (string :tag "TODO keyword"))
2406 (other :tag "No TODO statistics" nil)))
2408 (defcustom org-hierarchical-todo-statistics t
2409 "Non-nil means TODO statistics covers just direct children.
2410 When nil, all entries in the subtree are considered.
2411 This has only an effect if `org-provide-todo-statistics' is set.
2412 To set this to nil for only a single subtree, use a COOKIE_DATA
2413 property and include the word \"recursive\" into the value."
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-after-todo-state-change-hook nil
2418 "Hook which is run after the state of a TODO item was changed.
2419 The new state (a string with a TODO keyword, or nil) is available in the
2420 Lisp variable `org-state'."
2421 :group 'org-todo
2422 :type 'hook)
2424 (defvar org-blocker-hook nil
2425 "Hook for functions that are allowed to block a state change.
2427 Functions in this hook should not modify the buffer.
2428 Each function gets as its single argument a property list,
2429 see `org-trigger-hook' for more information about this list.
2431 If any of the functions in this hook returns nil, the state change
2432 is blocked.")
2434 (defvar org-trigger-hook nil
2435 "Hook for functions that are triggered by a state change.
2437 Each function gets as its single argument a property list with at
2438 least the following elements:
2440 (:type type-of-change :position pos-at-entry-start
2441 :from old-state :to new-state)
2443 Depending on the type, more properties may be present.
2445 This mechanism is currently implemented for:
2447 TODO state changes
2448 ------------------
2449 :type todo-state-change
2450 :from previous state (keyword as a string), or nil, or a symbol
2451 'todo' or 'done', to indicate the general type of state.
2452 :to new state, like in :from")
2454 (defcustom org-enforce-todo-dependencies nil
2455 "Non-nil means undone TODO entries will block switching the parent to DONE.
2456 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2457 be blocked if any prior sibling is not yet done.
2458 Finally, if the parent is blocked because of ordered siblings of its own,
2459 the child will also be blocked."
2460 :set (lambda (var val)
2461 (set var val)
2462 (if val
2463 (add-hook 'org-blocker-hook
2464 'org-block-todo-from-children-or-siblings-or-parent)
2465 (remove-hook 'org-blocker-hook
2466 'org-block-todo-from-children-or-siblings-or-parent)))
2467 :group 'org-todo
2468 :type 'boolean)
2470 (defcustom org-enforce-todo-checkbox-dependencies nil
2471 "Non-nil means unchecked boxes will block switching the parent to DONE.
2472 When this is nil, checkboxes have no influence on switching TODO states.
2473 When non-nil, you first need to check off all check boxes before the TODO
2474 entry can be switched to DONE.
2475 This variable needs to be set before org.el is loaded, and you need to
2476 restart Emacs after a change to make the change effective. The only way
2477 to change is while Emacs is running is through the customize interface."
2478 :set (lambda (var val)
2479 (set var val)
2480 (if val
2481 (add-hook 'org-blocker-hook
2482 'org-block-todo-from-checkboxes)
2483 (remove-hook 'org-blocker-hook
2484 'org-block-todo-from-checkboxes)))
2485 :group 'org-todo
2486 :type 'boolean)
2488 (defcustom org-treat-insert-todo-heading-as-state-change nil
2489 "Non-nil means inserting a TODO heading is treated as state change.
2490 So when the command \\[org-insert-todo-heading] is used, state change
2491 logging will apply if appropriate. When nil, the new TODO item will
2492 be inserted directly, and no logging will take place."
2493 :group 'org-todo
2494 :type 'boolean)
2496 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2497 "Non-nil means switching TODO states with S-cursor counts as state change.
2498 This is the default behavior. However, setting this to nil allows a
2499 convenient way to select a TODO state and bypass any logging associated
2500 with that."
2501 :group 'org-todo
2502 :type 'boolean)
2504 (defcustom org-todo-state-tags-triggers nil
2505 "Tag changes that should be triggered by TODO state changes.
2506 This is a list. Each entry is
2508 (state-change (tag . flag) .......)
2510 State-change can be a string with a state, and empty string to indicate the
2511 state that has no TODO keyword, or it can be one of the symbols `todo'
2512 or `done', meaning any not-done or done state, respectively."
2513 :group 'org-todo
2514 :group 'org-tags
2515 :type '(repeat
2516 (cons (choice :tag "When changing to"
2517 (const :tag "Not-done state" todo)
2518 (const :tag "Done state" done)
2519 (string :tag "State"))
2520 (repeat
2521 (cons :tag "Tag action"
2522 (string :tag "Tag")
2523 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2525 (defcustom org-log-done nil
2526 "Information to record when a task moves to the DONE state.
2528 Possible values are:
2530 nil Don't add anything, just change the keyword
2531 time Add a time stamp to the task
2532 note Prompt for a note and add it with template `org-log-note-headings'
2534 This option can also be set with on a per-file-basis with
2536 #+STARTUP: nologdone
2537 #+STARTUP: logdone
2538 #+STARTUP: lognotedone
2540 You can have local logging settings for a subtree by setting the LOGGING
2541 property to one or more of these keywords."
2542 :group 'org-todo
2543 :group 'org-progress
2544 :type '(choice
2545 (const :tag "No logging" nil)
2546 (const :tag "Record CLOSED timestamp" time)
2547 (const :tag "Record CLOSED timestamp with note." note)))
2549 ;; Normalize old uses of org-log-done.
2550 (cond
2551 ((eq org-log-done t) (setq org-log-done 'time))
2552 ((and (listp org-log-done) (memq 'done org-log-done))
2553 (setq org-log-done 'note)))
2555 (defcustom org-log-reschedule nil
2556 "Information to record when the scheduling date of a tasks is modified.
2558 Possible values are:
2560 nil Don't add anything, just change the date
2561 time Add a time stamp to the task
2562 note Prompt for a note and add it with template `org-log-note-headings'
2564 This option can also be set with on a per-file-basis with
2566 #+STARTUP: nologreschedule
2567 #+STARTUP: logreschedule
2568 #+STARTUP: lognotereschedule"
2569 :group 'org-todo
2570 :group 'org-progress
2571 :type '(choice
2572 (const :tag "No logging" nil)
2573 (const :tag "Record timestamp" time)
2574 (const :tag "Record timestamp with note." note)))
2576 (defcustom org-log-redeadline nil
2577 "Information to record when the deadline date of a tasks is modified.
2579 Possible values are:
2581 nil Don't add anything, just change the date
2582 time Add a time stamp to the task
2583 note Prompt for a note and add it with template `org-log-note-headings'
2585 This option can also be set with on a per-file-basis with
2587 #+STARTUP: nologredeadline
2588 #+STARTUP: logredeadline
2589 #+STARTUP: lognoteredeadline
2591 You can have local logging settings for a subtree by setting the LOGGING
2592 property to one or more of these keywords."
2593 :group 'org-todo
2594 :group 'org-progress
2595 :type '(choice
2596 (const :tag "No logging" nil)
2597 (const :tag "Record timestamp" time)
2598 (const :tag "Record timestamp with note." note)))
2600 (defcustom org-log-note-clock-out nil
2601 "Non-nil means record a note when clocking out of an item.
2602 This can also be configured on a per-file basis by adding one of
2603 the following lines anywhere in the buffer:
2605 #+STARTUP: lognoteclock-out
2606 #+STARTUP: nolognoteclock-out"
2607 :group 'org-todo
2608 :group 'org-progress
2609 :type 'boolean)
2611 (defcustom org-log-done-with-time t
2612 "Non-nil means the CLOSED time stamp will contain date and time.
2613 When nil, only the date will be recorded."
2614 :group 'org-progress
2615 :type 'boolean)
2617 (defcustom org-log-note-headings
2618 '((done . "CLOSING NOTE %t")
2619 (state . "State %-12s from %-12S %t")
2620 (note . "Note taken on %t")
2621 (reschedule . "Rescheduled from %S on %t")
2622 (delschedule . "Not scheduled, was %S on %t")
2623 (redeadline . "New deadline from %S on %t")
2624 (deldeadline . "Removed deadline, was %S on %t")
2625 (refile . "Refiled on %t")
2626 (clock-out . ""))
2627 "Headings for notes added to entries.
2628 The value is an alist, with the car being a symbol indicating the note
2629 context, and the cdr is the heading to be used. The heading may also be the
2630 empty string.
2631 %t in the heading will be replaced by a time stamp.
2632 %T will be an active time stamp instead the default inactive one
2633 %d will be replaced by a short-format time stamp.
2634 %D will be replaced by an active short-format time stamp.
2635 %s will be replaced by the new TODO state, in double quotes.
2636 %S will be replaced by the old TODO state, in double quotes.
2637 %u will be replaced by the user name.
2638 %U will be replaced by the full user name.
2640 In fact, it is not a good idea to change the `state' entry, because
2641 agenda log mode depends on the format of these entries."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type '(list :greedy t
2645 (cons (const :tag "Heading when closing an item" done) string)
2646 (cons (const :tag
2647 "Heading when changing todo state (todo sequence only)"
2648 state) string)
2649 (cons (const :tag "Heading when just taking a note" note) string)
2650 (cons (const :tag "Heading when clocking out" clock-out) string)
2651 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2652 (cons (const :tag "Heading when rescheduling" reschedule) string)
2653 (cons (const :tag "Heading when changing deadline" redeadline) string)
2654 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2655 (cons (const :tag "Heading when refiling" refile) string)))
2657 (unless (assq 'note org-log-note-headings)
2658 (push '(note . "%t") org-log-note-headings))
2660 (defcustom org-log-into-drawer nil
2661 "Non-nil means insert state change notes and time stamps into a drawer.
2662 When nil, state changes notes will be inserted after the headline and
2663 any scheduling and clock lines, but not inside a drawer.
2665 The value of this variable should be the name of the drawer to use.
2666 LOGBOOK is proposed as the default drawer for this purpose, you can
2667 also set this to a string to define the drawer of your choice.
2669 A value of t is also allowed, representing \"LOGBOOK\".
2671 A value of t or nil can also be set with on a per-file-basis with
2673 #+STARTUP: logdrawer
2674 #+STARTUP: nologdrawer
2676 If this variable is set, `org-log-state-notes-insert-after-drawers'
2677 will be ignored.
2679 You can set the property LOG_INTO_DRAWER to overrule this setting for
2680 a subtree."
2681 :group 'org-todo
2682 :group 'org-progress
2683 :type '(choice
2684 (const :tag "Not into a drawer" nil)
2685 (const :tag "LOGBOOK" t)
2686 (string :tag "Other")))
2688 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2690 (defun org-log-into-drawer ()
2691 "Return the value of `org-log-into-drawer', but let properties overrule.
2692 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2693 used instead of the default value."
2694 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2695 (cond
2696 ((not p) org-log-into-drawer)
2697 ((equal p "nil") nil)
2698 ((equal p "t") "LOGBOOK")
2699 (t p))))
2701 (defcustom org-log-state-notes-insert-after-drawers nil
2702 "Non-nil means insert state change notes after any drawers in entry.
2703 Only the drawers that *immediately* follow the headline and the
2704 deadline/scheduled line are skipped.
2705 When nil, insert notes right after the heading and perhaps the line
2706 with deadline/scheduling if present.
2708 This variable will have no effect if `org-log-into-drawer' is
2709 set."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type 'boolean)
2714 (defcustom org-log-states-order-reversed t
2715 "Non-nil means the latest state note will be directly after heading.
2716 When nil, the state change notes will be ordered according to time.
2718 This option can also be set with on a per-file-basis with
2720 #+STARTUP: logstatesreversed
2721 #+STARTUP: nologstatesreversed"
2722 :group 'org-todo
2723 :group 'org-progress
2724 :type 'boolean)
2726 (defcustom org-todo-repeat-to-state nil
2727 "The TODO state to which a repeater should return the repeating task.
2728 By default this is the first task in a TODO sequence, or the previous state
2729 in a TODO_TYP set. But you can specify another task here.
2730 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2731 :group 'org-todo
2732 :version "24.1"
2733 :type '(choice (const :tag "Head of sequence" nil)
2734 (string :tag "Specific state")))
2736 (defcustom org-log-repeat 'time
2737 "Non-nil means record moving through the DONE state when triggering repeat.
2738 An auto-repeating task is immediately switched back to TODO when
2739 marked DONE. If you are not logging state changes (by adding \"@\"
2740 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2741 record a closing note, there will be no record of the task moving
2742 through DONE. This variable forces taking a note anyway.
2744 nil Don't force a record
2745 time Record a time stamp
2746 note Prompt for a note and add it with template `org-log-note-headings'
2748 This option can also be set with on a per-file-basis with
2750 #+STARTUP: nologrepeat
2751 #+STARTUP: logrepeat
2752 #+STARTUP: lognoterepeat
2754 You can have local logging settings for a subtree by setting the LOGGING
2755 property to one or more of these keywords."
2756 :group 'org-todo
2757 :group 'org-progress
2758 :type '(choice
2759 (const :tag "Don't force a record" nil)
2760 (const :tag "Force recording the DONE state" time)
2761 (const :tag "Force recording a note with the DONE state" note)))
2764 (defgroup org-priorities nil
2765 "Priorities in Org-mode."
2766 :tag "Org Priorities"
2767 :group 'org-todo)
2769 (defcustom org-enable-priority-commands t
2770 "Non-nil means priority commands are active.
2771 When nil, these commands will be disabled, so that you never accidentally
2772 set a priority."
2773 :group 'org-priorities
2774 :type 'boolean)
2776 (defcustom org-highest-priority ?A
2777 "The highest priority of TODO items. A character like ?A, ?B etc.
2778 Must have a smaller ASCII number than `org-lowest-priority'."
2779 :group 'org-priorities
2780 :type 'character)
2782 (defcustom org-lowest-priority ?C
2783 "The lowest priority of TODO items. A character like ?A, ?B etc.
2784 Must have a larger ASCII number than `org-highest-priority'."
2785 :group 'org-priorities
2786 :type 'character)
2788 (defcustom org-default-priority ?B
2789 "The default priority of TODO items.
2790 This is the priority an item gets if no explicit priority is given.
2791 When starting to cycle on an empty priority the first step in the cycle
2792 depends on `org-priority-start-cycle-with-default'. The resulting first
2793 step priority must not exceed the range from `org-highest-priority' to
2794 `org-lowest-priority' which means that `org-default-priority' has to be
2795 in this range exclusive or inclusive the range boundaries. Else the
2796 first step refuses to set the default and the second will fall back
2797 to (depending on the command used) the highest or lowest priority."
2798 :group 'org-priorities
2799 :type 'character)
2801 (defcustom org-priority-start-cycle-with-default t
2802 "Non-nil means start with default priority when starting to cycle.
2803 When this is nil, the first step in the cycle will be (depending on the
2804 command used) one higher or lower than the default priority.
2805 See also `org-default-priority'."
2806 :group 'org-priorities
2807 :type 'boolean)
2809 (defcustom org-get-priority-function nil
2810 "Function to extract the priority from a string.
2811 The string is normally the headline. If this is nil Org computes the
2812 priority from the priority cookie like [#A] in the headline. It returns
2813 an integer, increasing by 1000 for each priority level.
2814 The user can set a different function here, which should take a string
2815 as an argument and return the numeric priority."
2816 :group 'org-priorities
2817 :version "24.1"
2818 :type '(choice
2819 (const nil)
2820 (function)))
2822 (defgroup org-time nil
2823 "Options concerning time stamps and deadlines in Org-mode."
2824 :tag "Org Time"
2825 :group 'org)
2827 (defcustom org-insert-labeled-timestamps-at-point nil
2828 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2829 When nil, these labeled time stamps are forces into the second line of an
2830 entry, just after the headline. When scheduling from the global TODO list,
2831 the time stamp will always be forced into the second line."
2832 :group 'org-time
2833 :type 'boolean)
2835 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2836 "Formats for `format-time-string' which are used for time stamps.
2837 It is not recommended to change this constant.")
2839 (defcustom org-time-stamp-rounding-minutes '(0 5)
2840 "Number of minutes to round time stamps to.
2841 These are two values, the first applies when first creating a time stamp.
2842 The second applies when changing it with the commands `S-up' and `S-down'.
2843 When changing the time stamp, this means that it will change in steps
2844 of N minutes, as given by the second value.
2846 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2847 numbers should be factors of 60, so for example 5, 10, 15.
2849 When this is larger than 1, you can still force an exact time stamp by using
2850 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2851 and by using a prefix arg to `S-up/down' to specify the exact number
2852 of minutes to shift."
2853 :group 'org-time
2854 :get #'(lambda (var) ; Make sure both elements are there
2855 (if (integerp (default-value var))
2856 (list (default-value var) 5)
2857 (default-value var)))
2858 :type '(list
2859 (integer :tag "when inserting times")
2860 (integer :tag "when modifying times")))
2862 ;; Normalize old customizations of this variable.
2863 (when (integerp org-time-stamp-rounding-minutes)
2864 (setq org-time-stamp-rounding-minutes
2865 (list org-time-stamp-rounding-minutes
2866 org-time-stamp-rounding-minutes)))
2868 (defcustom org-display-custom-times nil
2869 "Non-nil means overlay custom formats over all time stamps.
2870 The formats are defined through the variable `org-time-stamp-custom-formats'.
2871 To turn this on on a per-file basis, insert anywhere in the file:
2872 #+STARTUP: customtime"
2873 :group 'org-time
2874 :set 'set-default
2875 :type 'sexp)
2876 (make-variable-buffer-local 'org-display-custom-times)
2878 (defcustom org-time-stamp-custom-formats
2879 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2880 "Custom formats for time stamps. See `format-time-string' for the syntax.
2881 These are overlaid over the default ISO format if the variable
2882 `org-display-custom-times' is set. Time like %H:%M should be at the
2883 end of the second format. The custom formats are also honored by export
2884 commands, if custom time display is turned on at the time of export."
2885 :group 'org-time
2886 :type 'sexp)
2888 (defun org-time-stamp-format (&optional long inactive)
2889 "Get the right format for a time string."
2890 (let ((f (if long (cdr org-time-stamp-formats)
2891 (car org-time-stamp-formats))))
2892 (if inactive
2893 (concat "[" (substring f 1 -1) "]")
2894 f)))
2896 (defcustom org-time-clocksum-format
2897 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2898 "The format string used when creating CLOCKSUM lines.
2899 This is also used when Org mode generates a time duration.
2901 The value can be a single format string containing two
2902 %-sequences, which will be filled with the number of hours and
2903 minutes in that order.
2905 Alternatively, the value can be a plist associating any of the
2906 keys :years, :months, :weeks, :days, :hours or :minutes with
2907 format strings. The time duration is formatted using only the
2908 time components that are needed and concatenating the results.
2909 If a time unit in absent, it falls back to the next smallest
2910 unit.
2912 The keys :require-years, :require-months, :require-days,
2913 :require-weeks, :require-hours, :require-minutes are also
2914 meaningful. A non-nil value for these keys indicates that the
2915 corresponding time component should always be included, even if
2916 its value is 0.
2919 For example,
2921 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2922 :require-minutes t)
2924 means durations longer than a day will be expressed in days,
2925 hours and minutes, and durations less than a day will always be
2926 expressed in hours and minutes (even for durations less than an
2927 hour).
2929 The value
2931 \(:days \"%dd\" :minutes \"%dm\")
2933 means durations longer than a day will be expressed in days and
2934 minutes, and durations less than a day will be expressed entirely
2935 in minutes (even for durations longer than an hour)."
2936 :group 'org-time
2937 :group 'org-clock
2938 :version "24.4"
2939 :package-version '(Org . "8.0")
2940 :type '(choice (string :tag "Format string")
2941 (set :tag "Plist"
2942 (group :inline t (const :tag "Years" :years)
2943 (string :tag "Format string"))
2944 (group :inline t
2945 (const :tag "Always show years" :require-years)
2946 (const t))
2947 (group :inline t (const :tag "Months" :months)
2948 (string :tag "Format string"))
2949 (group :inline t
2950 (const :tag "Always show months" :require-months)
2951 (const t))
2952 (group :inline t (const :tag "Weeks" :weeks)
2953 (string :tag "Format string"))
2954 (group :inline t
2955 (const :tag "Always show weeks" :require-weeks)
2956 (const t))
2957 (group :inline t (const :tag "Days" :days)
2958 (string :tag "Format string"))
2959 (group :inline t
2960 (const :tag "Always show days" :require-days)
2961 (const t))
2962 (group :inline t (const :tag "Hours" :hours)
2963 (string :tag "Format string"))
2964 (group :inline t
2965 (const :tag "Always show hours" :require-hours)
2966 (const t))
2967 (group :inline t (const :tag "Minutes" :minutes)
2968 (string :tag "Format string"))
2969 (group :inline t
2970 (const :tag "Always show minutes" :require-minutes)
2971 (const t)))))
2973 (defcustom org-time-clocksum-use-fractional nil
2974 "When non-nil, \\[org-clock-display] uses fractional times.
2975 See `org-time-clocksum-format' for more on time clock formats."
2976 :group 'org-time
2977 :group 'org-clock
2978 :version "24.3"
2979 :type 'boolean)
2981 (defcustom org-time-clocksum-use-effort-durations nil
2982 "When non-nil, \\[org-clock-display] uses effort durations.
2983 E.g. by default, one day is considered to be a 8 hours effort,
2984 so a task that has been clocked for 16 hours will be displayed
2985 as during 2 days in the clock display or in the clocktable.
2987 See `org-effort-durations' on how to set effort durations
2988 and `org-time-clocksum-format' for more on time clock formats."
2989 :group 'org-time
2990 :group 'org-clock
2991 :version "24.4"
2992 :package-version '(Org . "8.0")
2993 :type 'boolean)
2995 (defcustom org-time-clocksum-fractional-format "%.2f"
2996 "The format string used when creating CLOCKSUM lines,
2997 or when Org mode generates a time duration, if
2998 `org-time-clocksum-use-fractional' is enabled.
3000 The value can be a single format string containing one
3001 %-sequence, which will be filled with the number of hours as
3002 a float.
3004 Alternatively, the value can be a plist associating any of the
3005 keys :years, :months, :weeks, :days, :hours or :minutes with
3006 a format string. The time duration is formatted using the
3007 largest time unit which gives a non-zero integer part. If all
3008 specified formats have zero integer part, the smallest time unit
3009 is used."
3010 :group 'org-time
3011 :type '(choice (string :tag "Format string")
3012 (set (group :inline t (const :tag "Years" :years)
3013 (string :tag "Format string"))
3014 (group :inline t (const :tag "Months" :months)
3015 (string :tag "Format string"))
3016 (group :inline t (const :tag "Weeks" :weeks)
3017 (string :tag "Format string"))
3018 (group :inline t (const :tag "Days" :days)
3019 (string :tag "Format string"))
3020 (group :inline t (const :tag "Hours" :hours)
3021 (string :tag "Format string"))
3022 (group :inline t (const :tag "Minutes" :minutes)
3023 (string :tag "Format string")))))
3025 (defcustom org-deadline-warning-days 14
3026 "Number of days before expiration during which a deadline becomes active.
3027 This variable governs the display in sparse trees and in the agenda.
3028 When 0 or negative, it means use this number (the absolute value of it)
3029 even if a deadline has a different individual lead time specified.
3031 Custom commands can set this variable in the options section."
3032 :group 'org-time
3033 :group 'org-agenda-daily/weekly
3034 :type 'integer)
3036 (defcustom org-scheduled-delay-days 0
3037 "Number of days before a scheduled item becomes active.
3038 This variable governs the display in sparse trees and in the agenda.
3039 The default value (i.e. 0) means: don't delay scheduled item.
3040 When negative, it means use this number (the absolute value of it)
3041 even if a scheduled item has a different individual delay time
3042 specified.
3044 Custom commands can set this variable in the options section."
3045 :group 'org-time
3046 :group 'org-agenda-daily/weekly
3047 :version "24.4"
3048 :package-version '(Org . "8.0")
3049 :type 'integer)
3051 (defcustom org-read-date-prefer-future t
3052 "Non-nil means assume future for incomplete date input from user.
3053 This affects the following situations:
3054 1. The user gives a month but not a year.
3055 For example, if it is April and you enter \"feb 2\", this will be read
3056 as Feb 2, *next* year. \"May 5\", however, will be this year.
3057 2. The user gives a day, but no month.
3058 For example, if today is the 15th, and you enter \"3\", Org-mode will
3059 read this as the third of *next* month. However, if you enter \"17\",
3060 it will be considered as *this* month.
3062 If you set this variable to the symbol `time', then also the following
3063 will work:
3065 3. If the user gives a time.
3066 If the time is before now, it will be interpreted as tomorrow.
3068 Currently none of this works for ISO week specifications.
3070 When this option is nil, the current day, month and year will always be
3071 used as defaults.
3073 See also `org-agenda-jump-prefer-future'."
3074 :group 'org-time
3075 :type '(choice
3076 (const :tag "Never" nil)
3077 (const :tag "Check month and day" t)
3078 (const :tag "Check month, day, and time" time)))
3080 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3081 "Should the agenda jump command prefer the future for incomplete dates?
3082 The default is to do the same as configured in `org-read-date-prefer-future'.
3083 But you can also set a deviating value here.
3084 This may t or nil, or the symbol `org-read-date-prefer-future'."
3085 :group 'org-agenda
3086 :group 'org-time
3087 :version "24.1"
3088 :type '(choice
3089 (const :tag "Use org-read-date-prefer-future"
3090 org-read-date-prefer-future)
3091 (const :tag "Never" nil)
3092 (const :tag "Always" t)))
3094 (defcustom org-read-date-force-compatible-dates t
3095 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3097 Depending on the system Emacs is running on, certain dates cannot
3098 be represented with the type used internally to represent time.
3099 Dates between 1970-1-1 and 2038-1-1 can always be represented
3100 correctly. Some systems allow for earlier dates, some for later,
3101 some for both. One way to find out it to insert any date into an
3102 Org buffer, putting the cursor on the year and hitting S-up and
3103 S-down to test the range.
3105 When this variable is set to t, the date/time prompt will not let
3106 you specify dates outside the 1970-2037 range, so it is certain that
3107 these dates will work in whatever version of Emacs you are
3108 running, and also that you can move a file from one Emacs implementation
3109 to another. WHenever Org is forcing the year for you, it will display
3110 a message and beep.
3112 When this variable is nil, Org will check if the date is
3113 representable in the specific Emacs implementation you are using.
3114 If not, it will force a year, usually the current year, and beep
3115 to remind you. Currently this setting is not recommended because
3116 the likelihood that you will open your Org files in an Emacs that
3117 has limited date range is not negligible.
3119 A workaround for this problem is to use diary sexp dates for time
3120 stamps outside of this range."
3121 :group 'org-time
3122 :version "24.1"
3123 :type 'boolean)
3125 (defcustom org-read-date-display-live t
3126 "Non-nil means display current interpretation of date prompt live.
3127 This display will be in an overlay, in the minibuffer."
3128 :group 'org-time
3129 :type 'boolean)
3131 (defcustom org-read-date-popup-calendar t
3132 "Non-nil means pop up a calendar when prompting for a date.
3133 In the calendar, the date can be selected with mouse-1. However, the
3134 minibuffer will also be active, and you can simply enter the date as well.
3135 When nil, only the minibuffer will be available."
3136 :group 'org-time
3137 :type 'boolean)
3138 (org-defvaralias 'org-popup-calendar-for-date-prompt
3139 'org-read-date-popup-calendar)
3141 (make-obsolete-variable
3142 'org-read-date-minibuffer-setup-hook
3143 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3144 (defcustom org-read-date-minibuffer-setup-hook nil
3145 "Hook to be used to set up keys for the date/time interface.
3146 Add key definitions to `minibuffer-local-map', which will be a
3147 temporary copy.
3149 WARNING: This option is obsolete, you should use
3150 `org-read-date-minibuffer-local-map' to set up keys."
3151 :group 'org-time
3152 :type 'hook)
3154 (defcustom org-extend-today-until 0
3155 "The hour when your day really ends. Must be an integer.
3156 This has influence for the following applications:
3157 - When switching the agenda to \"today\". It it is still earlier than
3158 the time given here, the day recognized as TODAY is actually yesterday.
3159 - When a date is read from the user and it is still before the time given
3160 here, the current date and time will be assumed to be yesterday, 23:59.
3161 Also, timestamps inserted in capture templates follow this rule.
3163 IMPORTANT: This is a feature whose implementation is and likely will
3164 remain incomplete. Really, it is only here because past midnight seems to
3165 be the favorite working time of John Wiegley :-)"
3166 :group 'org-time
3167 :type 'integer)
3169 (defcustom org-use-effective-time nil
3170 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3171 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3172 \"effective time\" of any timestamps between midnight and 8am will be
3173 23:59 of the previous day."
3174 :group 'org-time
3175 :version "24.1"
3176 :type 'boolean)
3178 (defcustom org-use-last-clock-out-time-as-effective-time nil
3179 "When non-nil, use the last clock out time for `org-todo'.
3180 Note that this option has precedence over the combined use of
3181 `org-use-effective-time' and `org-extend-today-until'."
3182 :group 'org-time
3183 :version "24.4"
3184 :package-version '(Org . "8.0")
3185 :type 'boolean)
3187 (defcustom org-edit-timestamp-down-means-later nil
3188 "Non-nil means S-down will increase the time in a time stamp.
3189 When nil, S-up will increase."
3190 :group 'org-time
3191 :type 'boolean)
3193 (defcustom org-calendar-follow-timestamp-change t
3194 "Non-nil means make the calendar window follow timestamp changes.
3195 When a timestamp is modified and the calendar window is visible, it will be
3196 moved to the new date."
3197 :group 'org-time
3198 :type 'boolean)
3200 (defgroup org-tags nil
3201 "Options concerning tags in Org-mode."
3202 :tag "Org Tags"
3203 :group 'org)
3205 (defcustom org-tag-alist nil
3206 "List of tags allowed in Org-mode files.
3207 When this list is nil, Org-mode will base TAG input on what is already in the
3208 buffer.
3209 The value of this variable is an alist, the car of each entry must be a
3210 keyword as a string, the cdr may be a character that is used to select
3211 that tag through the fast-tag-selection interface.
3212 See the manual for details."
3213 :group 'org-tags
3214 :type '(repeat
3215 (choice
3216 (cons (string :tag "Tag name")
3217 (character :tag "Access char"))
3218 (list :tag "Start radio group"
3219 (const :startgroup)
3220 (option (string :tag "Group description")))
3221 (list :tag "Group tags delimiter"
3222 (const :grouptags))
3223 (list :tag "End radio group"
3224 (const :endgroup)
3225 (option (string :tag "Group description")))
3226 (const :tag "New line" (:newline)))))
3228 (defcustom org-tag-persistent-alist nil
3229 "List of tags that will always appear in all Org-mode files.
3230 This is in addition to any in buffer settings or customizations
3231 of `org-tag-alist'.
3232 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3233 The value of this variable is an alist, the car of each entry must be a
3234 keyword as a string, the cdr may be a character that is used to select
3235 that tag through the fast-tag-selection interface.
3236 See the manual for details.
3237 To disable these tags on a per-file basis, insert anywhere in the file:
3238 #+STARTUP: noptag"
3239 :group 'org-tags
3240 :type '(repeat
3241 (choice
3242 (cons (string :tag "Tag name")
3243 (character :tag "Access char"))
3244 (const :tag "Start radio group" (:startgroup))
3245 (const :tag "Group tags delimiter" (:grouptags))
3246 (const :tag "End radio group" (:endgroup))
3247 (const :tag "New line" (:newline)))))
3249 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3250 "If non-nil, always offer completion for all tags of all agenda files.
3251 Instead of customizing this variable directly, you might want to
3252 set it locally for capture buffers, because there no list of
3253 tags in that file can be created dynamically (there are none).
3255 (add-hook 'org-capture-mode-hook
3256 (lambda ()
3257 (set (make-local-variable
3258 'org-complete-tags-always-offer-all-agenda-tags)
3259 t)))"
3260 :group 'org-tags
3261 :version "24.1"
3262 :type 'boolean)
3264 (defvar org-file-tags nil
3265 "List of tags that can be inherited by all entries in the file.
3266 The tags will be inherited if the variable `org-use-tag-inheritance'
3267 says they should be.
3268 This variable is populated from #+FILETAGS lines.")
3270 (defcustom org-use-fast-tag-selection 'auto
3271 "Non-nil means use fast tag selection scheme.
3272 This is a special interface to select and deselect tags with single keys.
3273 When nil, fast selection is never used.
3274 When the symbol `auto', fast selection is used if and only if selection
3275 characters for tags have been configured, either through the variable
3276 `org-tag-alist' or through a #+TAGS line in the buffer.
3277 When t, fast selection is always used and selection keys are assigned
3278 automatically if necessary."
3279 :group 'org-tags
3280 :type '(choice
3281 (const :tag "Always" t)
3282 (const :tag "Never" nil)
3283 (const :tag "When selection characters are configured" auto)))
3285 (defcustom org-fast-tag-selection-single-key nil
3286 "Non-nil means fast tag selection exits after first change.
3287 When nil, you have to press RET to exit it.
3288 During fast tag selection, you can toggle this flag with `C-c'.
3289 This variable can also have the value `expert'. In this case, the window
3290 displaying the tags menu is not even shown, until you press C-c again."
3291 :group 'org-tags
3292 :type '(choice
3293 (const :tag "No" nil)
3294 (const :tag "Yes" t)
3295 (const :tag "Expert" expert)))
3297 (defvar org-fast-tag-selection-include-todo nil
3298 "Non-nil means fast tags selection interface will also offer TODO states.
3299 This is an undocumented feature, you should not rely on it.")
3301 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3302 "The column to which tags should be indented in a headline.
3303 If this number is positive, it specifies the column. If it is negative,
3304 it means that the tags should be flushright to that column. For example,
3305 -80 works well for a normal 80 character screen.
3306 When 0, place tags directly after headline text, with only one space in
3307 between."
3308 :group 'org-tags
3309 :type 'integer)
3311 (defcustom org-auto-align-tags t
3312 "Non-nil keeps tags aligned when modifying headlines.
3313 Some operations (i.e. demoting) change the length of a headline and
3314 therefore shift the tags around. With this option turned on, after
3315 each such operation the tags are again aligned to `org-tags-column'."
3316 :group 'org-tags
3317 :type 'boolean)
3319 (defcustom org-use-tag-inheritance t
3320 "Non-nil means tags in levels apply also for sublevels.
3321 When nil, only the tags directly given in a specific line apply there.
3322 This may also be a list of tags that should be inherited, or a regexp that
3323 matches tags that should be inherited. Additional control is possible
3324 with the variable `org-tags-exclude-from-inheritance' which gives an
3325 explicit list of tags to be excluded from inheritance, even if the value of
3326 `org-use-tag-inheritance' would select it for inheritance.
3328 If this option is t, a match early-on in a tree can lead to a large
3329 number of matches in the subtree when constructing the agenda or creating
3330 a sparse tree. If you only want to see the first match in a tree during
3331 a search, check out the variable `org-tags-match-list-sublevels'."
3332 :group 'org-tags
3333 :type '(choice
3334 (const :tag "Not" nil)
3335 (const :tag "Always" t)
3336 (repeat :tag "Specific tags" (string :tag "Tag"))
3337 (regexp :tag "Tags matched by regexp")))
3339 (defcustom org-tags-exclude-from-inheritance nil
3340 "List of tags that should never be inherited.
3341 This is a way to exclude a few tags from inheritance. For way to do
3342 the opposite, to actively allow inheritance for selected tags,
3343 see the variable `org-use-tag-inheritance'."
3344 :group 'org-tags
3345 :type '(repeat (string :tag "Tag")))
3347 (defun org-tag-inherit-p (tag)
3348 "Check if TAG is one that should be inherited."
3349 (cond
3350 ((member tag org-tags-exclude-from-inheritance) nil)
3351 ((eq org-use-tag-inheritance t) t)
3352 ((not org-use-tag-inheritance) nil)
3353 ((stringp org-use-tag-inheritance)
3354 (string-match org-use-tag-inheritance tag))
3355 ((listp org-use-tag-inheritance)
3356 (member tag org-use-tag-inheritance))
3357 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3359 (defcustom org-tags-match-list-sublevels t
3360 "Non-nil means list also sublevels of headlines matching a search.
3361 This variable applies to tags/property searches, and also to stuck
3362 projects because this search is based on a tags match as well.
3364 When set to the symbol `indented', sublevels are indented with
3365 leading dots.
3367 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3368 the sublevels of a headline matching a tag search often also match
3369 the same search. Listing all of them can create very long lists.
3370 Setting this variable to nil causes subtrees of a match to be skipped.
3372 This variable is semi-obsolete and probably should always be true. It
3373 is better to limit inheritance to certain tags using the variables
3374 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3375 :group 'org-tags
3376 :type '(choice
3377 (const :tag "No, don't list them" nil)
3378 (const :tag "Yes, do list them" t)
3379 (const :tag "List them, indented with leading dots" indented)))
3381 (defcustom org-tags-sort-function nil
3382 "When set, tags are sorted using this function as a comparator."
3383 :group 'org-tags
3384 :type '(choice
3385 (const :tag "No sorting" nil)
3386 (const :tag "Alphabetical" string<)
3387 (const :tag "Reverse alphabetical" string>)
3388 (function :tag "Custom function" nil)))
3390 (defvar org-tags-history nil
3391 "History of minibuffer reads for tags.")
3392 (defvar org-last-tags-completion-table nil
3393 "The last used completion table for tags.")
3394 (defvar org-after-tags-change-hook nil
3395 "Hook that is run after the tags in a line have changed.")
3397 (defgroup org-properties nil
3398 "Options concerning properties in Org-mode."
3399 :tag "Org Properties"
3400 :group 'org)
3402 (defcustom org-property-format "%-10s %s"
3403 "How property key/value pairs should be formatted by `indent-line'.
3404 When `indent-line' hits a property definition, it will format the line
3405 according to this format, mainly to make sure that the values are
3406 lined-up with respect to each other."
3407 :group 'org-properties
3408 :type 'string)
3410 (defcustom org-properties-postprocess-alist nil
3411 "Alist of properties and functions to adjust inserted values.
3412 Elements of this alist must be of the form
3414 ([string] [function])
3416 where [string] must be a property name and [function] must be a
3417 lambda expression: this lambda expression must take one argument,
3418 the value to adjust, and return the new value as a string.
3420 For example, this element will allow the property \"Remaining\"
3421 to be updated wrt the relation between the \"Effort\" property
3422 and the clock summary:
3424 ((\"Remaining\" (lambda(value)
3425 (let ((clocksum (org-clock-sum-current-item))
3426 (effort (org-duration-string-to-minutes
3427 (org-entry-get (point) \"Effort\"))))
3428 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3429 :group 'org-properties
3430 :version "24.1"
3431 :type '(alist :key-type (string :tag "Property")
3432 :value-type (function :tag "Function")))
3434 (defcustom org-use-property-inheritance nil
3435 "Non-nil means properties apply also for sublevels.
3437 This setting is chiefly used during property searches. Turning it on can
3438 cause significant overhead when doing a search, which is why it is not
3439 on by default.
3441 When nil, only the properties directly given in the current entry count.
3442 When t, every property is inherited. The value may also be a list of
3443 properties that should have inheritance, or a regular expression matching
3444 properties that should be inherited.
3446 However, note that some special properties use inheritance under special
3447 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3448 and the properties ending in \"_ALL\" when they are used as descriptor
3449 for valid values of a property.
3451 Note for programmers:
3452 When querying an entry with `org-entry-get', you can control if inheritance
3453 should be used. By default, `org-entry-get' looks only at the local
3454 properties. You can request inheritance by setting the inherit argument
3455 to t (to force inheritance) or to `selective' (to respect the setting
3456 in this variable)."
3457 :group 'org-properties
3458 :type '(choice
3459 (const :tag "Not" nil)
3460 (const :tag "Always" t)
3461 (repeat :tag "Specific properties" (string :tag "Property"))
3462 (regexp :tag "Properties matched by regexp")))
3464 (defun org-property-inherit-p (property)
3465 "Check if PROPERTY is one that should be inherited."
3466 (cond
3467 ((eq org-use-property-inheritance t) t)
3468 ((not org-use-property-inheritance) nil)
3469 ((stringp org-use-property-inheritance)
3470 (string-match org-use-property-inheritance property))
3471 ((listp org-use-property-inheritance)
3472 (member property org-use-property-inheritance))
3473 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3475 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3476 "The default column format, if no other format has been defined.
3477 This variable can be set on the per-file basis by inserting a line
3479 #+COLUMNS: %25ITEM ....."
3480 :group 'org-properties
3481 :type 'string)
3483 (defcustom org-columns-ellipses ".."
3484 "The ellipses to be used when a field in column view is truncated.
3485 When this is the empty string, as many characters as possible are shown,
3486 but then there will be no visual indication that the field has been truncated.
3487 When this is a string of length N, the last N characters of a truncated
3488 field are replaced by this string. If the column is narrower than the
3489 ellipses string, only part of the ellipses string will be shown."
3490 :group 'org-properties
3491 :type 'string)
3493 (defcustom org-columns-modify-value-for-display-function nil
3494 "Function that modifies values for display in column view.
3495 For example, it can be used to cut out a certain part from a time stamp.
3496 The function must take 2 arguments:
3498 column-title The title of the column (*not* the property name)
3499 value The value that should be modified.
3501 The function should return the value that should be displayed,
3502 or nil if the normal value should be used."
3503 :group 'org-properties
3504 :type '(choice (const nil) (function)))
3506 (defcustom org-effort-property "Effort"
3507 "The property that is being used to keep track of effort estimates.
3508 Effort estimates given in this property need to have the format H:MM."
3509 :group 'org-properties
3510 :group 'org-progress
3511 :type '(string :tag "Property"))
3513 (defconst org-global-properties-fixed
3514 '(("VISIBILITY_ALL" . "folded children content all")
3515 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3516 "List of property/value pairs that can be inherited by any entry.
3518 These are fixed values, for the preset properties. The user variable
3519 that can be used to add to this list is `org-global-properties'.
3521 The entries in this list are cons cells where the car is a property
3522 name and cdr is a string with the value. If the value represents
3523 multiple items like an \"_ALL\" property, separate the items by
3524 spaces.")
3526 (defcustom org-global-properties nil
3527 "List of property/value pairs that can be inherited by any entry.
3529 This list will be combined with the constant `org-global-properties-fixed'.
3531 The entries in this list are cons cells where the car is a property
3532 name and cdr is a string with the value.
3534 You can set buffer-local values for the same purpose in the variable
3535 `org-file-properties' this by adding lines like
3537 #+PROPERTY: NAME VALUE"
3538 :group 'org-properties
3539 :type '(repeat
3540 (cons (string :tag "Property")
3541 (string :tag "Value"))))
3543 (defvar org-file-properties nil
3544 "List of property/value pairs that can be inherited by any entry.
3545 Valid for the current buffer.
3546 This variable is populated from #+PROPERTY lines.")
3547 (make-variable-buffer-local 'org-file-properties)
3549 (defgroup org-agenda nil
3550 "Options concerning agenda views in Org-mode."
3551 :tag "Org Agenda"
3552 :group 'org)
3554 (defvar org-category nil
3555 "Variable used by org files to set a category for agenda display.
3556 Such files should use a file variable to set it, for example
3558 # -*- mode: org; org-category: \"ELisp\"
3560 or contain a special line
3562 #+CATEGORY: ELisp
3564 If the file does not specify a category, then file's base name
3565 is used instead.")
3566 (make-variable-buffer-local 'org-category)
3567 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3569 (defcustom org-agenda-files nil
3570 "The files to be used for agenda display.
3571 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3572 \\[org-remove-file]. You can also use customize to edit the list.
3574 If an entry is a directory, all files in that directory that are matched by
3575 `org-agenda-file-regexp' will be part of the file list.
3577 If the value of the variable is not a list but a single file name, then
3578 the list of agenda files is actually stored and maintained in that file, one
3579 agenda file per line. In this file paths can be given relative to
3580 `org-directory'. Tilde expansion and environment variable substitution
3581 are also made."
3582 :group 'org-agenda
3583 :type '(choice
3584 (repeat :tag "List of files and directories" file)
3585 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3587 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3588 "Regular expression to match files for `org-agenda-files'.
3589 If any element in the list in that variable contains a directory instead
3590 of a normal file, all files in that directory that are matched by this
3591 regular expression will be included."
3592 :group 'org-agenda
3593 :type 'regexp)
3595 (defcustom org-agenda-text-search-extra-files nil
3596 "List of extra files to be searched by text search commands.
3597 These files will be searched in addition to the agenda files by the
3598 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3599 Note that these files will only be searched for text search commands,
3600 not for the other agenda views like todo lists, tag searches or the weekly
3601 agenda. This variable is intended to list notes and possibly archive files
3602 that should also be searched by these two commands.
3603 In fact, if the first element in the list is the symbol `agenda-archives',
3604 then all archive files of all agenda files will be added to the search
3605 scope."
3606 :group 'org-agenda
3607 :type '(set :greedy t
3608 (const :tag "Agenda Archives" agenda-archives)
3609 (repeat :inline t (file))))
3611 (org-defvaralias 'org-agenda-multi-occur-extra-files
3612 'org-agenda-text-search-extra-files)
3614 (defcustom org-agenda-skip-unavailable-files nil
3615 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3616 A nil value means to remove them, after a query, from the list."
3617 :group 'org-agenda
3618 :type 'boolean)
3620 (defcustom org-calendar-to-agenda-key [?c]
3621 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3622 The command `org-calendar-goto-agenda' will be bound to this key. The
3623 default is the character `c' because then `c' can be used to switch back and
3624 forth between agenda and calendar."
3625 :group 'org-agenda
3626 :type 'sexp)
3628 (defcustom org-calendar-insert-diary-entry-key [?i]
3629 "The key to be installed in `calendar-mode-map' for adding diary entries.
3630 This option is irrelevant until `org-agenda-diary-file' has been configured
3631 to point to an Org-mode file. When that is the case, the command
3632 `org-agenda-diary-entry' will be bound to the key given here, by default
3633 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3634 if you want to continue doing this, you need to change this to a different
3635 key."
3636 :group 'org-agenda
3637 :type 'sexp)
3639 (defcustom org-agenda-diary-file 'diary-file
3640 "File to which to add new entries with the `i' key in agenda and calendar.
3641 When this is the symbol `diary-file', the functionality in the Emacs
3642 calendar will be used to add entries to the `diary-file'. But when this
3643 points to a file, `org-agenda-diary-entry' will be used instead."
3644 :group 'org-agenda
3645 :type '(choice
3646 (const :tag "The standard Emacs diary file" diary-file)
3647 (file :tag "Special Org file diary entries")))
3649 (eval-after-load "calendar"
3650 '(progn
3651 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3652 'org-calendar-goto-agenda)
3653 (add-hook 'calendar-mode-hook
3654 (lambda ()
3655 (unless (eq org-agenda-diary-file 'diary-file)
3656 (define-key calendar-mode-map
3657 org-calendar-insert-diary-entry-key
3658 'org-agenda-diary-entry))))))
3660 (defgroup org-latex nil
3661 "Options for embedding LaTeX code into Org-mode."
3662 :tag "Org LaTeX"
3663 :group 'org)
3665 (defcustom org-format-latex-options
3666 '(:foreground default :background default :scale 1.0
3667 :html-foreground "Black" :html-background "Transparent"
3668 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3669 "Options for creating images from LaTeX fragments.
3670 This is a property list with the following properties:
3671 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3672 `default' means use the foreground of the default face.
3673 `auto' means use the foreground from the text face.
3674 :background the background color, or \"Transparent\".
3675 `default' means use the background of the default face.
3676 `auto' means use the background from the text face.
3677 :scale a scaling factor for the size of the images, to get more pixels
3678 :html-foreground, :html-background, :html-scale
3679 the same numbers for HTML export.
3680 :matchers a list indicating which matchers should be used to
3681 find LaTeX fragments. Valid members of this list are:
3682 \"begin\" find environments
3683 \"$1\" find single characters surrounded by $.$
3684 \"$\" find math expressions surrounded by $...$
3685 \"$$\" find math expressions surrounded by $$....$$
3686 \"\\(\" find math expressions surrounded by \\(...\\)
3687 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3688 :group 'org-latex
3689 :type 'plist)
3691 (defcustom org-format-latex-signal-error t
3692 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3693 When nil, just push out a message."
3694 :group 'org-latex
3695 :version "24.1"
3696 :type 'boolean)
3698 (defcustom org-latex-to-mathml-jar-file nil
3699 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3700 Use this to specify additional executable file say a jar file.
3702 When using MathToWeb as the converter, specify the full-path to
3703 your mathtoweb.jar file."
3704 :group 'org-latex
3705 :version "24.1"
3706 :type '(choice
3707 (const :tag "None" nil)
3708 (file :tag "JAR file" :must-match t)))
3710 (defcustom org-latex-to-mathml-convert-command nil
3711 "Command to convert LaTeX fragments to MathML.
3712 Replace format-specifiers in the command as noted below and use
3713 `shell-command' to convert LaTeX to MathML.
3714 %j: Executable file in fully expanded form as specified by
3715 `org-latex-to-mathml-jar-file'.
3716 %I: Input LaTeX file in fully expanded form
3717 %o: Output MathML file
3718 This command is used by `org-create-math-formula'.
3720 When using MathToWeb as the converter, set this to
3721 \"java -jar %j -unicode -force -df %o %I\"."
3722 :group 'org-latex
3723 :version "24.1"
3724 :type '(choice
3725 (const :tag "None" nil)
3726 (string :tag "\nShell command")))
3728 (defcustom org-latex-create-formula-image-program 'dvipng
3729 "Program to convert LaTeX fragments with.
3731 dvipng Process the LaTeX fragments to dvi file, then convert
3732 dvi files to png files using dvipng.
3733 This will also include processing of non-math environments.
3734 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3735 to convert pdf files to png files"
3736 :group 'org-latex
3737 :version "24.1"
3738 :type '(choice
3739 (const :tag "dvipng" dvipng)
3740 (const :tag "imagemagick" imagemagick)))
3742 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3743 "Path to store latex preview images.
3744 A relative path here creates many directories relative to the
3745 processed org files paths. An absolute path puts all preview
3746 images at the same place."
3747 :group 'org-latex
3748 :version "24.3"
3749 :type 'string)
3751 (defun org-format-latex-mathml-available-p ()
3752 "Return t if `org-latex-to-mathml-convert-command' is usable."
3753 (save-match-data
3754 (when (and (boundp 'org-latex-to-mathml-convert-command)
3755 org-latex-to-mathml-convert-command)
3756 (let ((executable (car (split-string
3757 org-latex-to-mathml-convert-command))))
3758 (when (executable-find executable)
3759 (if (string-match
3760 "%j" org-latex-to-mathml-convert-command)
3761 (file-readable-p org-latex-to-mathml-jar-file)
3762 t))))))
3764 (defcustom org-format-latex-header "\\documentclass{article}
3765 \\usepackage[usenames]{color}
3766 \\usepackage{amsmath}
3767 \\usepackage[mathscr]{eucal}
3768 \\pagestyle{empty} % do not remove
3769 \[PACKAGES]
3770 \[DEFAULT-PACKAGES]
3771 % The settings below are copied from fullpage.sty
3772 \\setlength{\\textwidth}{\\paperwidth}
3773 \\addtolength{\\textwidth}{-3cm}
3774 \\setlength{\\oddsidemargin}{1.5cm}
3775 \\addtolength{\\oddsidemargin}{-2.54cm}
3776 \\setlength{\\evensidemargin}{\\oddsidemargin}
3777 \\setlength{\\textheight}{\\paperheight}
3778 \\addtolength{\\textheight}{-\\headheight}
3779 \\addtolength{\\textheight}{-\\headsep}
3780 \\addtolength{\\textheight}{-\\footskip}
3781 \\addtolength{\\textheight}{-3cm}
3782 \\setlength{\\topmargin}{1.5cm}
3783 \\addtolength{\\topmargin}{-2.54cm}"
3784 "The document header used for processing LaTeX fragments.
3785 It is imperative that this header make sure that no page number
3786 appears on the page. The package defined in the variables
3787 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3788 will either replace the placeholder \"[PACKAGES]\" in this
3789 header, or they will be appended."
3790 :group 'org-latex
3791 :type 'string)
3793 (defun org-set-packages-alist (var val)
3794 "Set the packages alist and make sure it has 3 elements per entry."
3795 (set var (mapcar (lambda (x)
3796 (if (and (consp x) (= (length x) 2))
3797 (list (car x) (nth 1 x) t)
3799 val)))
3801 (defun org-get-packages-alist (var)
3802 "Get the packages alist and make sure it has 3 elements per entry."
3803 (mapcar (lambda (x)
3804 (if (and (consp x) (= (length x) 2))
3805 (list (car x) (nth 1 x) t)
3807 (default-value var)))
3809 (defcustom org-latex-default-packages-alist
3810 '(("AUTO" "inputenc" t)
3811 ("T1" "fontenc" t)
3812 ("" "fixltx2e" nil)
3813 ("" "graphicx" t)
3814 ("" "longtable" nil)
3815 ("" "float" nil)
3816 ("" "wrapfig" nil)
3817 ("normalem" "ulem" t)
3818 ("" "textcomp" t)
3819 ("" "marvosym" t)
3820 ("" "wasysym" t)
3821 ("" "latexsym" t)
3822 ("" "amssymb" t)
3823 ("" "amstext" nil)
3824 ("" "hyperref" nil)
3825 "\\tolerance=1000")
3826 "Alist of default packages to be inserted in the header.
3828 Change this only if one of the packages here causes an
3829 incompatibility with another package you are using.
3831 The packages in this list are needed by one part or another of
3832 Org mode to function properly:
3834 - inputenc, fontenc: for basic font and character selection
3835 - amstext: for subscript and superscript
3836 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3837 symbols used for interpreting the entities in `org-entities'.
3838 You can skip some of these packages if you don't use any of the
3839 symbols in it.
3840 - ulem: for underline and strike-through
3841 - graphicx: for including images
3842 - float, wrapfig: for figure placement
3843 - longtable: for long tables
3844 - hyperref: for cross references
3846 Therefore you should not modify this variable unless you know
3847 what you are doing. The one reason to change it anyway is that
3848 you might be loading some other package that conflicts with one
3849 of the default packages. Each cell is of the format
3850 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3851 the package also needs to be included when compiling LaTeX
3852 snippets into images for inclusion into non-LaTeX output."
3853 :group 'org-latex
3854 :group 'org-export-latex
3855 :set 'org-set-packages-alist
3856 :get 'org-get-packages-alist
3857 :version "24.1"
3858 :type '(repeat
3859 (choice
3860 (list :tag "options/package pair"
3861 (string :tag "options")
3862 (string :tag "package")
3863 (boolean :tag "Snippet"))
3864 (string :tag "A line of LaTeX"))))
3866 (defcustom org-latex-packages-alist nil
3867 "Alist of packages to be inserted in every LaTeX header.
3869 These will be inserted after `org-latex-default-packages-alist'.
3870 Each cell is of the format:
3872 \(\"options\" \"package\" snippet-flag)
3874 SNIPPET-FLAG, when t, indicates that this package is also needed
3875 when turning LaTeX snippets into images for inclusion into
3876 non-LaTeX output.
3878 Make sure that you only list packages here which:
3880 - you want in every file
3881 - do not conflict with the setup in `org-format-latex-header'.
3882 - do not conflict with the default packages in
3883 `org-latex-default-packages-alist'."
3884 :group 'org-latex
3885 :group 'org-export-latex
3886 :set 'org-set-packages-alist
3887 :get 'org-get-packages-alist
3888 :type '(repeat
3889 (choice
3890 (list :tag "options/package pair"
3891 (string :tag "options")
3892 (string :tag "package")
3893 (boolean :tag "Snippet"))
3894 (string :tag "A line of LaTeX"))))
3896 (defgroup org-appearance nil
3897 "Settings for Org-mode appearance."
3898 :tag "Org Appearance"
3899 :group 'org)
3901 (defcustom org-level-color-stars-only nil
3902 "Non-nil means fontify only the stars in each headline.
3903 When nil, the entire headline is fontified.
3904 Changing it requires restart of `font-lock-mode' to become effective
3905 also in regions already fontified."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-hide-leading-stars nil
3910 "Non-nil means hide the first N-1 stars in a headline.
3911 This works by using the face `org-hide' for these stars. This
3912 face is white for a light background, and black for a dark
3913 background. You may have to customize the face `org-hide' to
3914 make this work.
3915 Changing it requires restart of `font-lock-mode' to become effective
3916 also in regions already fontified.
3917 You may also set this on a per-file basis by adding one of the following
3918 lines to the buffer:
3920 #+STARTUP: hidestars
3921 #+STARTUP: showstars"
3922 :group 'org-appearance
3923 :type 'boolean)
3925 (defcustom org-hidden-keywords nil
3926 "List of symbols corresponding to keywords to be hidden the org buffer.
3927 For example, a value '(title) for this list will make the document's title
3928 appear in the buffer without the initial #+TITLE: keyword."
3929 :group 'org-appearance
3930 :version "24.1"
3931 :type '(set (const :tag "#+AUTHOR" author)
3932 (const :tag "#+DATE" date)
3933 (const :tag "#+EMAIL" email)
3934 (const :tag "#+TITLE" title)))
3936 (defcustom org-custom-properties nil
3937 "List of properties (as strings) with a special meaning.
3938 The default use of these custom properties is to let the user
3939 hide them with `org-toggle-custom-properties-visibility'."
3940 :group 'org-properties
3941 :group 'org-appearance
3942 :version "24.3"
3943 :type '(repeat (string :tag "Property Name")))
3945 (defcustom org-fontify-done-headline nil
3946 "Non-nil means change the face of a headline if it is marked DONE.
3947 Normally, only the TODO/DONE keyword indicates the state of a headline.
3948 When this is non-nil, the headline after the keyword is set to the
3949 `org-headline-done' as an additional indication."
3950 :group 'org-appearance
3951 :type 'boolean)
3953 (defcustom org-fontify-emphasized-text t
3954 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3955 Changing this variable requires a restart of Emacs to take effect."
3956 :group 'org-appearance
3957 :type 'boolean)
3959 (defcustom org-fontify-whole-heading-line nil
3960 "Non-nil means fontify the whole line for headings.
3961 This is useful when setting a background color for the
3962 org-level-* faces."
3963 :group 'org-appearance
3964 :type 'boolean)
3966 (defcustom org-highlight-latex-and-related nil
3967 "Non-nil means highlight LaTeX related syntax in the buffer.
3968 When non nil, the value should be a list containing any of the
3969 following symbols:
3970 `latex' Highlight LaTeX snippets and environments.
3971 `script' Highlight subscript and superscript.
3972 `entities' Highlight entities."
3973 :group 'org-appearance
3974 :version "24.4"
3975 :package-version '(Org . "8.0")
3976 :type '(choice
3977 (const :tag "No highlighting" nil)
3978 (set :greedy t :tag "Highlight"
3979 (const :tag "LaTeX snippets and environments" latex)
3980 (const :tag "Subscript and superscript" script)
3981 (const :tag "Entities" entities))))
3983 (defcustom org-hide-emphasis-markers nil
3984 "Non-nil mean font-lock should hide the emphasis marker characters."
3985 :group 'org-appearance
3986 :type 'boolean)
3988 (defcustom org-pretty-entities nil
3989 "Non-nil means show entities as UTF8 characters.
3990 When nil, the \\name form remains in the buffer."
3991 :group 'org-appearance
3992 :version "24.1"
3993 :type 'boolean)
3995 (defcustom org-pretty-entities-include-sub-superscripts t
3996 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3997 :group 'org-appearance
3998 :version "24.1"
3999 :type 'boolean)
4001 (defvar org-emph-re nil
4002 "Regular expression for matching emphasis.
4003 After a match, the match groups contain these elements:
4004 0 The match of the full regular expression, including the characters
4005 before and after the proper match
4006 1 The character before the proper match, or empty at beginning of line
4007 2 The proper match, including the leading and trailing markers
4008 3 The leading marker like * or /, indicating the type of highlighting
4009 4 The text between the emphasis markers, not including the markers
4010 5 The character after the match, empty at the end of a line")
4011 (defvar org-verbatim-re nil
4012 "Regular expression for matching verbatim text.")
4013 (defvar org-emphasis-regexp-components) ; defined just below
4014 (defvar org-emphasis-alist) ; defined just below
4015 (defun org-set-emph-re (var val)
4016 "Set variable and compute the emphasis regular expression."
4017 (set var val)
4018 (when (and (boundp 'org-emphasis-alist)
4019 (boundp 'org-emphasis-regexp-components)
4020 org-emphasis-alist org-emphasis-regexp-components)
4021 (let* ((e org-emphasis-regexp-components)
4022 (pre (car e))
4023 (post (nth 1 e))
4024 (border (nth 2 e))
4025 (body (nth 3 e))
4026 (nl (nth 4 e))
4027 (body1 (concat body "*?"))
4028 (markers (mapconcat 'car org-emphasis-alist ""))
4029 (vmarkers (mapconcat
4030 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4031 org-emphasis-alist "")))
4032 ;; make sure special characters appear at the right position in the class
4033 (if (string-match "\\^" markers)
4034 (setq markers (concat (replace-match "" t t markers) "^")))
4035 (if (string-match "-" markers)
4036 (setq markers (concat (replace-match "" t t markers) "-")))
4037 (if (string-match "\\^" vmarkers)
4038 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4039 (if (string-match "-" vmarkers)
4040 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4041 (if (> nl 0)
4042 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4043 (int-to-string nl) "\\}")))
4044 ;; Make the regexp
4045 (setq org-emph-re
4046 (concat "\\([" pre "]\\|^\\)"
4047 "\\("
4048 "\\([" markers "]\\)"
4049 "\\("
4050 "[^" border "]\\|"
4051 "[^" border "]"
4052 body1
4053 "[^" border "]"
4054 "\\)"
4055 "\\3\\)"
4056 "\\([" post "]\\|$\\)"))
4057 (setq org-verbatim-re
4058 (concat "\\([" pre "]\\|^\\)"
4059 "\\("
4060 "\\([" vmarkers "]\\)"
4061 "\\("
4062 "[^" border "]\\|"
4063 "[^" border "]"
4064 body1
4065 "[^" border "]"
4066 "\\)"
4067 "\\3\\)"
4068 "\\([" post "]\\|$\\)")))))
4070 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4071 ;; set this option proved cumbersome. See this message/thread:
4072 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4073 (defvar org-emphasis-regexp-components
4074 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4075 "Components used to build the regular expression for emphasis.
4076 This is a list with five entries. Terminology: In an emphasis string
4077 like \" *strong word* \", we call the initial space PREMATCH, the final
4078 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4079 and \"trong wor\" is the body. The different components in this variable
4080 specify what is allowed/forbidden in each part:
4082 pre Chars allowed as prematch. Beginning of line will be allowed too.
4083 post Chars allowed as postmatch. End of line will be allowed too.
4084 border The chars *forbidden* as border characters.
4085 body-regexp A regexp like \".\" to match a body character. Don't use
4086 non-shy groups here, and don't allow newline here.
4087 newline The maximum number of newlines allowed in an emphasis exp.
4089 You need to reload Org or to restart Emacs after customizing this.")
4091 (defcustom org-emphasis-alist
4092 `(("*" bold)
4093 ("/" italic)
4094 ("_" underline)
4095 ("=" org-code verbatim)
4096 ("~" org-verbatim verbatim)
4097 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4098 "Alist of characters and faces to emphasize text.
4099 Text starting and ending with a special character will be emphasized,
4100 for example *bold*, _underlined_ and /italic/. This variable sets the
4101 marker characters and the face to be used by font-lock for highlighting
4102 in Org-mode Emacs buffers.
4104 You need to reload Org or to restart Emacs after customizing this."
4105 :group 'org-appearance
4106 :set 'org-set-emph-re
4107 :version "24.4"
4108 :package-version '(Org . "8.0")
4109 :type '(repeat
4110 (list
4111 (string :tag "Marker character")
4112 (choice
4113 (face :tag "Font-lock-face")
4114 (plist :tag "Face property list"))
4115 (option (const verbatim)))))
4117 (defvar org-protecting-blocks
4118 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4119 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4120 This is needed for font-lock setup.")
4122 ;;; Miscellaneous options
4124 (defgroup org-completion nil
4125 "Completion in Org-mode."
4126 :tag "Org Completion"
4127 :group 'org)
4129 (defcustom org-completion-use-ido nil
4130 "Non-nil means use ido completion wherever possible.
4131 Note that `ido-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 See also `org-completion-use-iswitchb'."
4135 :group 'org-completion
4136 :type 'boolean)
4138 (defcustom org-completion-use-iswitchb nil
4139 "Non-nil means use iswitchb completion wherever possible.
4140 Note that `iswitchb-mode' must be active for this variable to be relevant.
4141 If you decide to turn this variable on, you might well want to turn off
4142 `org-outline-path-complete-in-steps'.
4143 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4144 :group 'org-completion
4145 :type 'boolean)
4147 (defcustom org-completion-fallback-command 'hippie-expand
4148 "The expansion command called by \\[pcomplete] in normal context.
4149 Normal means, no org-mode-specific context."
4150 :group 'org-completion
4151 :type 'function)
4153 ;;; Functions and variables from their packages
4154 ;; Declared here to avoid compiler warnings
4156 ;; XEmacs only
4157 (defvar outline-mode-menu-heading)
4158 (defvar outline-mode-menu-show)
4159 (defvar outline-mode-menu-hide)
4160 (defvar zmacs-regions) ; XEmacs regions
4162 ;; Emacs only
4163 (defvar mark-active)
4165 ;; Various packages
4166 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4167 (declare-function calendar-forward-day "cal-move" (arg))
4168 (declare-function calendar-goto-date "cal-move" (date))
4169 (declare-function calendar-goto-today "cal-move" ())
4170 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4171 (defvar calc-embedded-close-formula)
4172 (defvar calc-embedded-open-formula)
4173 (declare-function cdlatex-tab "ext:cdlatex" ())
4174 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4175 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4176 (defvar font-lock-unfontify-region-function)
4177 (declare-function iswitchb-read-buffer "iswitchb"
4178 (prompt &optional default require-match start matches-set))
4179 (defvar iswitchb-temp-buflist)
4180 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4181 (defvar org-agenda-tags-todo-honor-ignore-options)
4182 (declare-function org-agenda-skip "org-agenda" ())
4183 (declare-function
4184 org-agenda-format-item "org-agenda"
4185 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4186 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4187 (declare-function org-agenda-change-all-lines "org-agenda"
4188 (newhead hdmarker &optional fixface just-this))
4189 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4190 (declare-function org-agenda-maybe-redo "org-agenda" ())
4191 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4192 (beg end))
4193 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4194 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4195 "org-agenda" (&optional end))
4196 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4197 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4198 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4199 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4200 (declare-function org-indent-mode "org-indent" (&optional arg))
4201 (declare-function parse-time-string "parse-time" (string))
4202 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4203 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4204 (defvar remember-data-file)
4205 (defvar texmathp-why)
4206 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4207 (declare-function table--at-cell-p "table" (position &optional object at-column))
4209 (defvar org-latex-regexps)
4211 ;;; Autoload and prepare some org modules
4213 ;; Some table stuff that needs to be defined here, because it is used
4214 ;; by the functions setting up org-mode or checking for table context.
4216 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4217 "Detect an org-type or table-type table.")
4218 (defconst org-table-line-regexp "^[ \t]*|"
4219 "Detect an org-type table line.")
4220 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4221 "Detect an org-type table line.")
4222 (defconst org-table-hline-regexp "^[ \t]*|-"
4223 "Detect an org-type table hline.")
4224 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4225 "Detect a table-type table hline.")
4226 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4227 "Detect the first line outside a table when searching from within it.
4228 This works for both table types.")
4230 ;; Autoload the functions in org-table.el that are needed by functions here.
4232 (eval-and-compile
4233 (org-autoload "org-table"
4234 '(org-table-begin org-table-blank-field org-table-end)))
4236 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4237 "Detect a #+TBLFM line.")
4239 ;;;###autoload
4240 (defun turn-on-orgtbl ()
4241 "Unconditionally turn on `orgtbl-mode'."
4242 (require 'org-table)
4243 (orgtbl-mode 1))
4245 (defun org-at-table-p (&optional table-type)
4246 "Return t if the cursor is inside an org-type table.
4247 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4248 (if org-enable-table-editor
4249 (save-excursion
4250 (beginning-of-line 1)
4251 (looking-at (if table-type org-table-any-line-regexp
4252 org-table-line-regexp)))
4253 nil))
4254 (defsubst org-table-p () (org-at-table-p))
4256 (defun org-at-table.el-p ()
4257 "Return t if and only if we are at a table.el table."
4258 (and (org-at-table-p 'any)
4259 (save-excursion
4260 (goto-char (org-table-begin 'any))
4261 (looking-at org-table1-hline-regexp))))
4263 (defun org-table-recognize-table.el ()
4264 "If there is a table.el table nearby, recognize it and move into it."
4265 (if org-table-tab-recognizes-table.el
4266 (if (org-at-table.el-p)
4267 (progn
4268 (beginning-of-line 1)
4269 (if (looking-at org-table-dataline-regexp)
4271 (if (looking-at org-table1-hline-regexp)
4272 (progn
4273 (beginning-of-line 2)
4274 (if (looking-at org-table-any-border-regexp)
4275 (beginning-of-line -1)))))
4276 (if (re-search-forward "|" (org-table-end t) t)
4277 (progn
4278 (require 'table)
4279 (if (table--at-cell-p (point))
4281 (message "recognizing table.el table...")
4282 (table-recognize-table)
4283 (message "recognizing table.el table...done")))
4284 (error "This should not happen"))
4286 nil)
4287 nil))
4289 (defun org-at-table-hline-p ()
4290 "Return t if the cursor is inside a hline in a table."
4291 (if org-enable-table-editor
4292 (save-excursion
4293 (beginning-of-line 1)
4294 (looking-at org-table-hline-regexp))
4295 nil))
4297 (defun org-table-map-tables (function &optional quietly)
4298 "Apply FUNCTION to the start of all tables in the buffer."
4299 (save-excursion
4300 (save-restriction
4301 (widen)
4302 (goto-char (point-min))
4303 (while (re-search-forward org-table-any-line-regexp nil t)
4304 (unless quietly
4305 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4306 (beginning-of-line 1)
4307 (when (and (looking-at org-table-line-regexp)
4308 ;; Exclude tables in src/example/verbatim/clocktable blocks
4309 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4310 (save-excursion (funcall function))
4311 (or (looking-at org-table-line-regexp)
4312 (forward-char 1)))
4313 (re-search-forward org-table-any-border-regexp nil 1))))
4314 (unless quietly (message "Mapping tables: done")))
4316 ;; Declare and autoload functions from org-agenda.el
4318 (eval-and-compile
4319 (org-autoload "org-agenda"
4320 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4322 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4323 (declare-function org-clock-update-mode-line "org-clock" ())
4324 (declare-function org-resolve-clocks "org-clock"
4325 (&optional also-non-dangling-p prompt last-valid))
4327 (defun org-at-TBLFM-p (&optional pos)
4328 "Return t when point (or POS) is in #+TBLFM line."
4329 (save-excursion
4330 (let ((pos pos)))
4331 (goto-char (or pos (point)))
4332 (beginning-of-line 1)
4333 (looking-at org-TBLFM-regexp)))
4335 (defvar org-clock-start-time)
4336 (defvar org-clock-marker (make-marker)
4337 "Marker recording the last clock-in.")
4338 (defvar org-clock-hd-marker (make-marker)
4339 "Marker recording the last clock-in, but the headline position.")
4340 (defvar org-clock-heading ""
4341 "The heading of the current clock entry.")
4342 (defun org-clock-is-active ()
4343 "Return non-nil if clock is currently running.
4344 The return value is actually the clock marker."
4345 (marker-buffer org-clock-marker))
4347 (eval-and-compile
4348 (org-autoload "org-clock" '(org-clock-remove-overlays
4349 org-clock-update-time-maybe
4350 org-clocktable-shift)))
4352 (defun org-check-running-clock ()
4353 "Check if the current buffer contains the running clock.
4354 If yes, offer to stop it and to save the buffer with the changes."
4355 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4356 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4357 (buffer-name))))
4358 (org-clock-out)
4359 (when (y-or-n-p "Save changed buffer?")
4360 (save-buffer))))
4362 (defun org-clocktable-try-shift (dir n)
4363 "Check if this line starts a clock table, if yes, shift the time block."
4364 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4365 (org-clocktable-shift dir n)))
4367 ;;;###autoload
4368 (defun org-clock-persistence-insinuate ()
4369 "Set up hooks for clock persistence."
4370 (require 'org-clock)
4371 (add-hook 'org-mode-hook 'org-clock-load)
4372 (add-hook 'kill-emacs-hook 'org-clock-save))
4374 ;; Define the variable already here, to make sure we have it.
4375 (defvar org-indent-mode nil
4376 "Non-nil if Org-Indent mode is enabled.
4377 Use the command `org-indent-mode' to change this variable.")
4379 ;; Autoload archiving code
4380 ;; The stuff that is needed for cycling and tags has to be defined here.
4382 (defgroup org-archive nil
4383 "Options concerning archiving in Org-mode."
4384 :tag "Org Archive"
4385 :group 'org-structure)
4387 (defcustom org-archive-location "%s_archive::"
4388 "The location where subtrees should be archived.
4390 The value of this variable is a string, consisting of two parts,
4391 separated by a double-colon. The first part is a filename and
4392 the second part is a headline.
4394 When the filename is omitted, archiving happens in the same file.
4395 %s in the filename will be replaced by the current file
4396 name (without the directory part). Archiving to a different file
4397 is useful to keep archived entries from contributing to the
4398 Org-mode Agenda.
4400 The archived entries will be filed as subtrees of the specified
4401 headline. When the headline is omitted, the subtrees are simply
4402 filed away at the end of the file, as top-level entries. Also in
4403 the heading you can use %s to represent the file name, this can be
4404 useful when using the same archive for a number of different files.
4406 Here are a few examples:
4407 \"%s_archive::\"
4408 If the current file is Projects.org, archive in file
4409 Projects.org_archive, as top-level trees. This is the default.
4411 \"::* Archived Tasks\"
4412 Archive in the current file, under the top-level headline
4413 \"* Archived Tasks\".
4415 \"~/org/archive.org::\"
4416 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4418 \"~/org/archive.org::* From %s\"
4419 Archive in file ~/org/archive.org (absolute path), under headlines
4420 \"From FILENAME\" where file name is the current file name.
4422 \"~/org/datetree.org::datetree/* Finished Tasks\"
4423 The \"datetree/\" string is special, signifying to archive
4424 items to the datetree. Items are placed in either the CLOSED
4425 date of the item, or the current date if there is no CLOSED date.
4426 The heading will be a subentry to the current date. There doesn't
4427 need to be a heading, but there always needs to be a slash after
4428 datetree. For example, to store archived items directly in the
4429 datetree, use \"~/org/datetree.org::datetree/\".
4431 \"basement::** Finished Tasks\"
4432 Archive in file ./basement (relative path), as level 3 trees
4433 below the level 2 heading \"** Finished Tasks\".
4435 You may set this option on a per-file basis by adding to the buffer a
4436 line like
4438 #+ARCHIVE: basement::** Finished Tasks
4440 You may also define it locally for a subtree by setting an ARCHIVE property
4441 in the entry. If such a property is found in an entry, or anywhere up
4442 the hierarchy, it will be used."
4443 :group 'org-archive
4444 :type 'string)
4446 (defcustom org-archive-tag "ARCHIVE"
4447 "The tag that marks a subtree as archived.
4448 An archived subtree does not open during visibility cycling, and does
4449 not contribute to the agenda listings.
4450 After changing this, font-lock must be restarted in the relevant buffers to
4451 get the proper fontification."
4452 :group 'org-archive
4453 :group 'org-keywords
4454 :type 'string)
4456 (defcustom org-agenda-skip-archived-trees t
4457 "Non-nil means the agenda will skip any items located in archived trees.
4458 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4459 variable is no longer recommended, you should leave it at the value t.
4460 Instead, use the key `v' to cycle the archives-mode in the agenda."
4461 :group 'org-archive
4462 :group 'org-agenda-skip
4463 :type 'boolean)
4465 (defcustom org-columns-skip-archived-trees t
4466 "Non-nil means ignore archived trees when creating column view."
4467 :group 'org-archive
4468 :group 'org-properties
4469 :type 'boolean)
4471 (defcustom org-cycle-open-archived-trees nil
4472 "Non-nil means `org-cycle' will open archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE.
4474 When nil, archived trees will stay folded. You can still open them with
4475 normal outline commands like `show-all', but not with the cycling commands."
4476 :group 'org-archive
4477 :group 'org-cycle
4478 :type 'boolean)
4480 (defcustom org-sparse-tree-open-archived-trees nil
4481 "Non-nil means sparse tree construction shows matches in archived trees.
4482 When nil, matches in these trees are highlighted, but the trees are kept in
4483 collapsed state."
4484 :group 'org-archive
4485 :group 'org-sparse-trees
4486 :type 'boolean)
4488 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4489 "The default date type when building a sparse tree.
4490 When this is nil, a date is a scheduled or a deadline timestamp.
4491 Otherwise, these types are allowed:
4493 all: all timestamps
4494 active: only active timestamps (<...>)
4495 inactive: only inactive timestamps (<...)
4496 scheduled: only scheduled timestamps
4497 deadline: only deadline timestamps"
4498 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4499 (const :tag "All timestamps" all)
4500 (const :tag "Only active timestamps" active)
4501 (const :tag "Only inactive timestamps" inactive)
4502 (const :tag "Only scheduled timestamps" scheduled)
4503 (const :tag "Only deadline timestamps" deadline)
4504 (const :tag "Only closed timestamps" closed))
4505 :version "24.3"
4506 :group 'org-sparse-trees)
4508 (defun org-cycle-hide-archived-subtrees (state)
4509 "Re-hide all archived subtrees after a visibility state change."
4510 (when (and (not org-cycle-open-archived-trees)
4511 (not (memq state '(overview folded))))
4512 (save-excursion
4513 (let* ((globalp (memq state '(contents all)))
4514 (beg (if globalp (point-min) (point)))
4515 (end (if globalp (point-max) (org-end-of-subtree t))))
4516 (org-hide-archived-subtrees beg end)
4517 (goto-char beg)
4518 (if (looking-at (concat ".*:" org-archive-tag ":"))
4519 (message "%s" (substitute-command-keys
4520 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4522 (defun org-force-cycle-archived ()
4523 "Cycle subtree even if it is archived."
4524 (interactive)
4525 (setq this-command 'org-cycle)
4526 (let ((org-cycle-open-archived-trees t))
4527 (call-interactively 'org-cycle)))
4529 (defun org-hide-archived-subtrees (beg end)
4530 "Re-hide all archived subtrees after a visibility state change."
4531 (save-excursion
4532 (let* ((re (concat ":" org-archive-tag ":")))
4533 (goto-char beg)
4534 (while (re-search-forward re end t)
4535 (when (org-at-heading-p)
4536 (org-flag-subtree t)
4537 (org-end-of-subtree t))))))
4539 (declare-function outline-end-of-heading "outline" ())
4540 (declare-function outline-flag-region "outline" (from to flag))
4541 (defun org-flag-subtree (flag)
4542 (save-excursion
4543 (org-back-to-heading t)
4544 (outline-end-of-heading)
4545 (outline-flag-region (point)
4546 (progn (org-end-of-subtree t) (point))
4547 flag)))
4549 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4551 (eval-and-compile
4552 (org-autoload "org-archive"
4553 '(org-add-archive-files)))
4555 ;; Autoload Column View Code
4557 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4558 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4559 (declare-function org-columns-compute "org-colview" (property))
4561 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4562 '(org-columns-number-to-string
4563 org-columns-get-format-and-top-level
4564 org-columns-compute
4565 org-columns-remove-overlays))
4567 ;; Autoload ID code
4569 (declare-function org-id-store-link "org-id")
4570 (declare-function org-id-locations-load "org-id")
4571 (declare-function org-id-locations-save "org-id")
4572 (defvar org-id-track-globally)
4573 (org-autoload "org-id"
4574 '(org-id-new
4575 org-id-copy
4576 org-id-get-with-outline-path-completion
4577 org-id-get-with-outline-drilling))
4579 ;;; Variables for pre-computed regular expressions, all buffer local
4581 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4582 "Matches first line of a hidden block.")
4583 (make-variable-buffer-local 'org-drawer-regexp)
4584 (defvar org-todo-regexp nil
4585 "Matches any of the TODO state keywords.")
4586 (make-variable-buffer-local 'org-todo-regexp)
4587 (defvar org-not-done-regexp nil
4588 "Matches any of the TODO state keywords except the last one.")
4589 (make-variable-buffer-local 'org-not-done-regexp)
4590 (defvar org-not-done-heading-regexp nil
4591 "Matches a TODO headline that is not done.")
4592 (make-variable-buffer-local 'org-not-done-regexp)
4593 (defvar org-todo-line-regexp nil
4594 "Matches a headline and puts TODO state into group 2 if present.")
4595 (make-variable-buffer-local 'org-todo-line-regexp)
4596 (defvar org-complex-heading-regexp nil
4597 "Matches a headline and puts everything into groups:
4598 group 1: the stars
4599 group 2: The todo keyword, maybe
4600 group 3: Priority cookie
4601 group 4: True headline
4602 group 5: Tags")
4603 (make-variable-buffer-local 'org-complex-heading-regexp)
4604 (defvar org-complex-heading-regexp-format nil
4605 "Printf format to make regexp to match an exact headline.
4606 This regexp will match the headline of any node which has the
4607 exact headline text that is put into the format, but may have any
4608 TODO state, priority and tags.")
4609 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4610 (defvar org-todo-line-tags-regexp nil
4611 "Matches a headline and puts TODO state into group 2 if present.
4612 Also put tags into group 4 if tags are present.")
4613 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4614 (defvar org-ds-keyword-length 12
4615 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4616 (make-variable-buffer-local 'org-ds-keyword-length)
4617 (defvar org-deadline-regexp nil
4618 "Matches the DEADLINE keyword.")
4619 (make-variable-buffer-local 'org-deadline-regexp)
4620 (defvar org-deadline-time-regexp nil
4621 "Matches the DEADLINE keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-deadline-time-regexp)
4623 (defvar org-deadline-time-hour-regexp nil
4624 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4626 (defvar org-deadline-line-regexp nil
4627 "Matches the DEADLINE keyword and the rest of the line.")
4628 (make-variable-buffer-local 'org-deadline-line-regexp)
4629 (defvar org-scheduled-regexp nil
4630 "Matches the SCHEDULED keyword.")
4631 (make-variable-buffer-local 'org-scheduled-regexp)
4632 (defvar org-scheduled-time-regexp nil
4633 "Matches the SCHEDULED keyword together with a time stamp.")
4634 (make-variable-buffer-local 'org-scheduled-time-regexp)
4635 (defvar org-scheduled-time-hour-regexp nil
4636 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4637 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4638 (defvar org-closed-time-regexp nil
4639 "Matches the CLOSED keyword together with a time stamp.")
4640 (make-variable-buffer-local 'org-closed-time-regexp)
4642 (defvar org-keyword-time-regexp nil
4643 "Matches any of the 4 keywords, together with the time stamp.")
4644 (make-variable-buffer-local 'org-keyword-time-regexp)
4645 (defvar org-keyword-time-not-clock-regexp nil
4646 "Matches any of the 3 keywords, together with the time stamp.")
4647 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4648 (defvar org-maybe-keyword-time-regexp nil
4649 "Matches a timestamp, possibly preceded by a keyword.")
4650 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4651 (defvar org-all-time-keywords nil
4652 "List of time keywords.")
4653 (make-variable-buffer-local 'org-all-time-keywords)
4655 (defconst org-plain-time-of-day-regexp
4656 (concat
4657 "\\(\\<[012]?[0-9]"
4658 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4659 "\\(--?"
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\)?")
4663 "Regular expression to match a plain time or time range.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 1 the first time, range or not
4668 8 the second time, if it is a range.")
4670 (defconst org-plain-time-extension-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4675 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4676 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4677 groups carry important information:
4678 0 the full match
4679 7 hours of duration
4680 9 minutes of duration")
4682 (defconst org-stamp-time-of-day-regexp
4683 (concat
4684 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4685 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4686 "\\(--?"
4687 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4688 "Regular expression to match a timestamp time or time range.
4689 After a match, the following groups carry important information:
4690 0 the full match
4691 1 date plus weekday, for back referencing to make sure both times are on the same day
4692 2 the first time, range or not
4693 4 the second time, if it is a range.")
4695 (defconst org-startup-options
4696 '(("fold" org-startup-folded t)
4697 ("overview" org-startup-folded t)
4698 ("nofold" org-startup-folded nil)
4699 ("showall" org-startup-folded nil)
4700 ("showeverything" org-startup-folded showeverything)
4701 ("content" org-startup-folded content)
4702 ("indent" org-startup-indented t)
4703 ("noindent" org-startup-indented nil)
4704 ("hidestars" org-hide-leading-stars t)
4705 ("showstars" org-hide-leading-stars nil)
4706 ("odd" org-odd-levels-only t)
4707 ("oddeven" org-odd-levels-only nil)
4708 ("align" org-startup-align-all-tables t)
4709 ("noalign" org-startup-align-all-tables nil)
4710 ("inlineimages" org-startup-with-inline-images t)
4711 ("noinlineimages" org-startup-with-inline-images nil)
4712 ("latexpreview" org-startup-with-latex-preview t)
4713 ("nolatexpreview" org-startup-with-latex-preview nil)
4714 ("customtime" org-display-custom-times t)
4715 ("logdone" org-log-done time)
4716 ("lognotedone" org-log-done note)
4717 ("nologdone" org-log-done nil)
4718 ("lognoteclock-out" org-log-note-clock-out t)
4719 ("nolognoteclock-out" org-log-note-clock-out nil)
4720 ("logrepeat" org-log-repeat state)
4721 ("lognoterepeat" org-log-repeat note)
4722 ("logdrawer" org-log-into-drawer t)
4723 ("nologdrawer" org-log-into-drawer nil)
4724 ("logstatesreversed" org-log-states-order-reversed t)
4725 ("nologstatesreversed" org-log-states-order-reversed nil)
4726 ("nologrepeat" org-log-repeat nil)
4727 ("logreschedule" org-log-reschedule time)
4728 ("lognotereschedule" org-log-reschedule note)
4729 ("nologreschedule" org-log-reschedule nil)
4730 ("logredeadline" org-log-redeadline time)
4731 ("lognoteredeadline" org-log-redeadline note)
4732 ("nologredeadline" org-log-redeadline nil)
4733 ("logrefile" org-log-refile time)
4734 ("lognoterefile" org-log-refile note)
4735 ("nologrefile" org-log-refile nil)
4736 ("fninline" org-footnote-define-inline t)
4737 ("nofninline" org-footnote-define-inline nil)
4738 ("fnlocal" org-footnote-section nil)
4739 ("fnauto" org-footnote-auto-label t)
4740 ("fnprompt" org-footnote-auto-label nil)
4741 ("fnconfirm" org-footnote-auto-label confirm)
4742 ("fnplain" org-footnote-auto-label plain)
4743 ("fnadjust" org-footnote-auto-adjust t)
4744 ("nofnadjust" org-footnote-auto-adjust nil)
4745 ("constcgs" constants-unit-system cgs)
4746 ("constSI" constants-unit-system SI)
4747 ("noptag" org-tag-persistent-alist nil)
4748 ("hideblocks" org-hide-block-startup t)
4749 ("nohideblocks" org-hide-block-startup nil)
4750 ("beamer" org-startup-with-beamer-mode t)
4751 ("entitiespretty" org-pretty-entities t)
4752 ("entitiesplain" org-pretty-entities nil))
4753 "Variable associated with STARTUP options for org-mode.
4754 Each element is a list of three items: the startup options (as written
4755 in the #+STARTUP line), the corresponding variable, and the value to set
4756 this variable to if the option is found. An optional forth element PUSH
4757 means to push this value onto the list in the variable.")
4759 (defun org-update-property-plist (key val props)
4760 "Update PROPS with KEY and VAL."
4761 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4762 (key (if appending (substring key 0 (- (length key) 1)) key))
4763 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4764 (previous (cdr (assoc key props))))
4765 (if appending
4766 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4767 (cons (cons key val) remainder))))
4769 (defconst org-block-regexp
4770 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4771 "Regular expression for hiding blocks.")
4772 (defconst org-heading-keyword-regexp-format
4773 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4774 "Printf format for a regexp matching a headline with some keyword.
4775 This regexp will match the headline of any node which has the
4776 exact keyword that is put into the format. The keyword isn't in
4777 any group by default, but the stars and the body are.")
4778 (defconst org-heading-keyword-maybe-regexp-format
4779 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4780 "Printf format for a regexp matching a headline, possibly with some keyword.
4781 This regexp can match any headline with the specified keyword, or
4782 without a keyword. The keyword isn't in any group by default,
4783 but the stars and the body are.")
4785 (defcustom org-group-tags t
4786 "When non-nil (the default), use group tags.
4787 This can be turned on/off through `org-toggle-tags-groups'."
4788 :group 'org-tags
4789 :group 'org-startup
4790 :type 'boolean)
4792 (defun org-toggle-tags-groups ()
4793 "Toggle support for group tags.
4794 Support for group tags is controlled by the option
4795 `org-group-tags', which is non-nil by default."
4796 (interactive)
4797 (setq org-group-tags (not org-group-tags))
4798 (cond ((and (derived-mode-p 'org-agenda-mode)
4799 org-group-tags)
4800 (org-agenda-redo))
4801 ((derived-mode-p 'org-mode)
4802 (let ((org-inhibit-startup t)) (org-mode))))
4803 (message "Groups tags support has been turned %s"
4804 (if org-group-tags "on" "off")))
4806 (defun org-set-regexps-and-options-for-tags ()
4807 "Precompute regular expressions used for tags in the current buffer."
4808 (when (derived-mode-p 'org-mode)
4809 (org-set-local 'org-file-tags nil)
4810 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4811 (splitre "[ \t]+")
4812 (start 0)
4813 tags ftags key value)
4814 (save-excursion
4815 (save-restriction
4816 (widen)
4817 (goto-char (point-min))
4818 (while (re-search-forward re nil t)
4819 (setq key (upcase (org-match-string-no-properties 1))
4820 value (org-match-string-no-properties 2))
4821 (if (stringp value) (setq value (org-trim value)))
4822 (cond
4823 ((equal key "TAGS")
4824 (setq tags (append tags (if tags '("\\n") nil)
4825 (org-split-string value splitre))))
4826 ((equal key "FILETAGS")
4827 (when (string-match "\\S-" value)
4828 (setq ftags
4829 (append
4830 ftags
4831 (apply 'append
4832 (mapcar (lambda (x) (org-split-string x ":"))
4833 (org-split-string value)))))))))))
4834 ;; Process the file tags.
4835 (and ftags (org-set-local 'org-file-tags
4836 (mapcar 'org-add-prop-inherited ftags)))
4837 (org-set-local 'org-tag-groups-alist nil)
4838 ;; Process the tags.
4839 ;; FIXME
4840 (when tags
4841 (let (e tgs g)
4842 (while (setq e (pop tags))
4843 (cond
4844 ((equal e "{")
4845 (progn (push '(:startgroup) tgs)
4846 (when (equal (nth 1 tags) ":")
4847 (push (list (replace-regexp-in-string
4848 "(.+)$" "" (nth 0 tags)))
4849 org-tag-groups-alist)
4850 (setq g 0))))
4851 ((equal e ":") (push '(:grouptags) tgs))
4852 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4853 ((equal e "\\n") (push '(:newline) tgs))
4854 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4855 (push (cons (match-string 1 e)
4856 (string-to-char (match-string 2 e))) tgs)
4857 (if (and g (> g 0))
4858 (setcar org-tag-groups-alist
4859 (append (car org-tag-groups-alist)
4860 (list (match-string 1 e)))))
4861 (if g (setq g (1+ g))))
4862 (t (push (list e) tgs)
4863 (if (and g (> g 0))
4864 (setcar org-tag-groups-alist
4865 (append (car org-tag-groups-alist) (list e))))
4866 (if g (setq g (1+ g))))))
4867 (org-set-local 'org-tag-alist nil)
4868 (while (setq e (pop tgs))
4869 (or (and (stringp (car e))
4870 (assoc (car e) org-tag-alist))
4871 (push e org-tag-alist)))
4872 ;; Return a list with tag variables
4873 (list org-file-tags org-tag-alist org-tag-groups-alist))))))
4875 (defun org-set-regexps-and-options ()
4876 "Precompute regular expressions used in the current buffer."
4877 (when (derived-mode-p 'org-mode)
4878 (org-set-local 'org-todo-kwd-alist nil)
4879 (org-set-local 'org-todo-key-alist nil)
4880 (org-set-local 'org-todo-key-trigger nil)
4881 (org-set-local 'org-todo-keywords-1 nil)
4882 (org-set-local 'org-done-keywords nil)
4883 (org-set-local 'org-todo-heads nil)
4884 (org-set-local 'org-todo-sets nil)
4885 (org-set-local 'org-todo-log-states nil)
4886 (org-set-local 'org-file-properties nil)
4887 (let ((re (org-make-options-regexp
4888 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4889 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4890 "SETUPFILE" "OPTIONS")
4891 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4892 (splitre "[ \t]+")
4893 (scripts org-use-sub-superscripts)
4894 kwds kws0 kwsa key log value cat arch const links hw dws
4895 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4896 (start 0))
4897 (save-excursion
4898 (save-restriction
4899 (widen)
4900 (goto-char (point-min))
4901 (while
4902 (or (and
4903 ext-setup-or-nil
4904 (let (ret)
4905 (with-temp-buffer
4906 (insert ext-setup-or-nil)
4907 (let ((major-mode 'org-mode))
4908 (setq ret (save-match-data
4909 (org-set-regexps-and-options-for-tags)))))
4910 ;; Append setupfile tags to existing tags
4911 (setq org-file-tags
4912 (delq nil (append org-file-tags (nth 0 ret)))
4913 org-tag-alist
4914 (delq nil (append org-tag-alist (nth 1 ret)))
4915 org-tag-groups-alist
4916 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4917 (and ext-setup-or-nil
4918 (string-match re ext-setup-or-nil start)
4919 (setq start (match-end 0)))
4920 (and (setq ext-setup-or-nil nil start 0)
4921 (re-search-forward re nil t)))
4922 (setq key (upcase (match-string 1 ext-setup-or-nil))
4923 value (org-match-string-no-properties 2 ext-setup-or-nil))
4924 (if (stringp value) (setq value (org-trim value)))
4925 (cond
4926 ((equal key "CATEGORY")
4927 (setq cat value))
4928 ((member key '("SEQ_TODO" "TODO"))
4929 (push (cons 'sequence (org-split-string value splitre)) kwds))
4930 ((equal key "TYP_TODO")
4931 (push (cons 'type (org-split-string value splitre)) kwds))
4932 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4933 ;; general TODO-like setup
4934 (push (cons (intern (downcase (match-string 1 key)))
4935 (org-split-string value splitre)) kwds))
4936 ((equal key "COLUMNS")
4937 (org-set-local 'org-columns-default-format value))
4938 ((equal key "LINK")
4939 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4940 (push (cons (match-string 1 value)
4941 (org-trim (match-string 2 value)))
4942 links)))
4943 ((equal key "PRIORITIES")
4944 (setq prio (org-split-string value " +")))
4945 ((equal key "PROPERTY")
4946 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4947 (setq props (org-update-property-plist (match-string 1 value)
4948 (match-string 2 value)
4949 props))))
4950 ((equal key "DRAWERS")
4951 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4952 ((equal key "CONSTANTS")
4953 (org-table-set-constants))
4954 ((equal key "STARTUP")
4955 (let ((opts (org-split-string value splitre))
4956 l var val)
4957 (while (setq l (pop opts))
4958 (when (setq l (assoc l org-startup-options))
4959 (setq var (nth 1 l) val (nth 2 l))
4960 (if (not (nth 3 l))
4961 (set (make-local-variable var) val)
4962 (if (not (listp (symbol-value var)))
4963 (set (make-local-variable var) nil))
4964 (set (make-local-variable var) (symbol-value var))
4965 (add-to-list var val))))))
4966 ((equal key "ARCHIVE")
4967 (setq arch value)
4968 (remove-text-properties 0 (length arch)
4969 '(face t fontified t) arch))
4970 ((equal key "OPTIONS")
4971 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4972 (setq scripts (read (match-string 2 value)))))
4973 ((and (equal key "SETUPFILE")
4974 ;; Prevent checking in Gnus messages
4975 (not buffer-read-only))
4976 (setq setup-contents (org-file-contents
4977 (expand-file-name
4978 (org-remove-double-quotes value))
4979 'noerror))
4980 (if (not ext-setup-or-nil)
4981 (setq ext-setup-or-nil setup-contents start 0)
4982 (setq ext-setup-or-nil
4983 (concat (substring ext-setup-or-nil 0 start)
4984 "\n" setup-contents "\n"
4985 (substring ext-setup-or-nil start)))))))
4986 ;; search for property blocks
4987 (goto-char (point-min))
4988 (while (re-search-forward org-block-regexp nil t)
4989 (when (equal "PROPERTY" (upcase (match-string 1)))
4990 (setq value (replace-regexp-in-string
4991 "[\n\r]" " " (match-string 4)))
4992 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4993 (setq props (org-update-property-plist (match-string 1 value)
4994 (match-string 2 value)
4995 props)))))))
4996 (org-set-local 'org-use-sub-superscripts scripts)
4997 (when cat
4998 (org-set-local 'org-category (intern cat))
4999 (push (cons "CATEGORY" cat) props))
5000 (when prio
5001 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5002 (setq prio (mapcar 'string-to-char prio))
5003 (org-set-local 'org-highest-priority (nth 0 prio))
5004 (org-set-local 'org-lowest-priority (nth 1 prio))
5005 (org-set-local 'org-default-priority (nth 2 prio)))
5006 (and props (org-set-local 'org-file-properties (nreverse props)))
5007 (and drawers (org-set-local 'org-drawers drawers))
5008 (and arch (org-set-local 'org-archive-location arch))
5009 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5010 ;; Process the TODO keywords
5011 (unless kwds
5012 ;; Use the global values as if they had been given locally.
5013 (setq kwds (default-value 'org-todo-keywords))
5014 (if (stringp (car kwds))
5015 (setq kwds (list (cons org-todo-interpretation
5016 (default-value 'org-todo-keywords)))))
5017 (setq kwds (reverse kwds)))
5018 (setq kwds (nreverse kwds))
5019 (let (inter kws kw)
5020 (while (setq kws (pop kwds))
5021 (let ((kws (or
5022 (run-hook-with-args-until-success
5023 'org-todo-setup-filter-hook kws)
5024 kws)))
5025 (setq inter (pop kws) sep (member "|" kws)
5026 kws0 (delete "|" (copy-sequence kws))
5027 kwsa nil
5028 kws1 (mapcar
5029 (lambda (x)
5030 ;; 1 2
5031 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5032 (progn
5033 (setq kw (match-string 1 x)
5034 key (and (match-end 2) (match-string 2 x))
5035 log (org-extract-log-state-settings x))
5036 (push (cons kw (and key (string-to-char key))) kwsa)
5037 (and log (push log org-todo-log-states))
5039 (error "Invalid TODO keyword %s" x)))
5040 kws0)
5041 kwsa (if kwsa (append '((:startgroup))
5042 (nreverse kwsa)
5043 '((:endgroup))))
5044 hw (car kws1)
5045 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5046 tail (list inter hw (car dws) (org-last dws))))
5047 (add-to-list 'org-todo-heads hw 'append)
5048 (push kws1 org-todo-sets)
5049 (setq org-done-keywords (append org-done-keywords dws nil))
5050 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5051 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5052 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5053 (setq org-todo-sets (nreverse org-todo-sets)
5054 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5055 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5056 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5057 ;; Compute the regular expressions and other local variables.
5058 ;; Using `org-outline-regexp-bol' would complicate them much,
5059 ;; because of the fixed white space at the end of that string.
5060 (if (not org-done-keywords)
5061 (setq org-done-keywords (and org-todo-keywords-1
5062 (list (org-last org-todo-keywords-1)))))
5063 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5064 (length org-scheduled-string)
5065 (length org-clock-string)
5066 (length org-closed-string)))
5067 org-drawer-regexp
5068 (concat "^[ \t]*:\\("
5069 (mapconcat 'regexp-quote org-drawers "\\|")
5070 "\\):[ \t]*$")
5071 org-not-done-keywords
5072 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5073 org-todo-regexp
5074 (concat "\\("
5075 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5076 "\\)")
5077 org-not-done-regexp
5078 (concat "\\("
5079 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5080 "\\)")
5081 org-not-done-heading-regexp
5082 (format org-heading-keyword-regexp-format org-not-done-regexp)
5083 org-todo-line-regexp
5084 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5085 org-complex-heading-regexp
5086 (concat "^\\(\\*+\\)"
5087 "\\(?: +" org-todo-regexp "\\)?"
5088 "\\(?: +\\(\\[#.\\]\\)\\)?"
5089 "\\(?: +\\(.*?\\)\\)??"
5090 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5091 "[ \t]*$")
5092 org-complex-heading-regexp-format
5093 (concat "^\\(\\*+\\)"
5094 "\\(?: +" org-todo-regexp "\\)?"
5095 "\\(?: +\\(\\[#.\\]\\)\\)?"
5096 "\\(?: +"
5097 ;; Stats cookies can be stuck to body.
5098 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5099 "\\(%s\\)"
5100 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5101 "\\)"
5102 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5103 "[ \t]*$")
5104 org-todo-line-tags-regexp
5105 (concat "^\\(\\*+\\)"
5106 "\\(?: +" org-todo-regexp "\\)?"
5107 "\\(?: +\\(.*?\\)\\)??"
5108 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5109 "[ \t]*$")
5110 org-deadline-regexp (concat "\\<" org-deadline-string)
5111 org-deadline-time-regexp
5112 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5113 org-deadline-time-hour-regexp
5114 (concat "\\<" org-deadline-string
5115 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5116 org-deadline-line-regexp
5117 (concat "\\<\\(" org-deadline-string "\\).*")
5118 org-scheduled-regexp
5119 (concat "\\<" org-scheduled-string)
5120 org-scheduled-time-regexp
5121 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5122 org-scheduled-time-hour-regexp
5123 (concat "\\<" org-scheduled-string
5124 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5125 org-closed-time-regexp
5126 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5127 org-keyword-time-regexp
5128 (concat "\\<\\(" org-scheduled-string
5129 "\\|" org-deadline-string
5130 "\\|" org-closed-string
5131 "\\|" org-clock-string "\\)"
5132 " *[[<]\\([^]>]+\\)[]>]")
5133 org-keyword-time-not-clock-regexp
5134 (concat "\\<\\(" org-scheduled-string
5135 "\\|" org-deadline-string
5136 "\\|" org-closed-string
5137 "\\)"
5138 " *[[<]\\([^]>]+\\)[]>]")
5139 org-maybe-keyword-time-regexp
5140 (concat "\\(\\<\\(" org-scheduled-string
5141 "\\|" org-deadline-string
5142 "\\|" org-closed-string
5143 "\\|" org-clock-string "\\)\\)?"
5144 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5145 org-all-time-keywords
5146 (mapcar (lambda (w) (substring w 0 -1))
5147 (list org-scheduled-string org-deadline-string
5148 org-clock-string org-closed-string)))
5149 (org-compute-latex-and-related-regexp)
5150 (org-set-font-lock-defaults))))
5152 (defun org-file-contents (file &optional noerror)
5153 "Return the contents of FILE, as a string."
5154 (if (or (not file)
5155 (not (file-readable-p file)))
5156 (if noerror
5157 (message "Cannot read file \"%s\"" file)
5158 (error "Cannot read file \"%s\"" file))
5159 (with-temp-buffer
5160 (insert-file-contents file)
5161 (buffer-string))))
5163 (defun org-extract-log-state-settings (x)
5164 "Extract the log state setting from a TODO keyword string.
5165 This will extract info from a string like \"WAIT(w@/!)\"."
5166 (let (kw key log1 log2)
5167 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5168 (setq kw (match-string 1 x)
5169 key (and (match-end 2) (match-string 2 x))
5170 log1 (and (match-end 3) (match-string 3 x))
5171 log2 (and (match-end 4) (match-string 4 x)))
5172 (and (or log1 log2)
5173 (list kw
5174 (and log1 (if (equal log1 "!") 'time 'note))
5175 (and log2 (if (equal log2 "!") 'time 'note)))))))
5177 (defun org-remove-keyword-keys (list)
5178 "Remove a pair of parenthesis at the end of each string in LIST."
5179 (mapcar (lambda (x)
5180 (if (string-match "(.*)$" x)
5181 (substring x 0 (match-beginning 0))
5183 list))
5185 (defun org-assign-fast-keys (alist)
5186 "Assign fast keys to a keyword-key alist.
5187 Respect keys that are already there."
5188 (let (new e (alt ?0))
5189 (while (setq e (pop alist))
5190 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5191 (cdr e)) ;; Key already assigned.
5192 (push e new)
5193 (let ((clist (string-to-list (downcase (car e))))
5194 (used (append new alist)))
5195 (when (= (car clist) ?@)
5196 (pop clist))
5197 (while (and clist (rassoc (car clist) used))
5198 (pop clist))
5199 (unless clist
5200 (while (rassoc alt used)
5201 (incf alt)))
5202 (push (cons (car e) (or (car clist) alt)) new))))
5203 (nreverse new)))
5205 ;;; Some variables used in various places
5207 (defvar org-window-configuration nil
5208 "Used in various places to store a window configuration.")
5209 (defvar org-selected-window nil
5210 "Used in various places to store a window configuration.")
5211 (defvar org-finish-function nil
5212 "Function to be called when `C-c C-c' is used.
5213 This is for getting out of special buffers like capture.")
5216 ;; FIXME: Occasionally check by commenting these, to make sure
5217 ;; no other functions uses these, forgetting to let-bind them.
5218 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5219 (defvar org-last-state)
5220 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5222 ;; Defined somewhere in this file, but used before definition.
5223 (defvar org-entities) ;; defined in org-entities.el
5224 (defvar org-struct-menu)
5225 (defvar org-org-menu)
5226 (defvar org-tbl-menu)
5228 ;;;; Define the Org-mode
5230 ;; We use a before-change function to check if a table might need
5231 ;; an update.
5232 (defvar org-table-may-need-update t
5233 "Indicates that a table might need an update.
5234 This variable is set by `org-before-change-function'.
5235 `org-table-align' sets it back to nil.")
5236 (defun org-before-change-function (beg end)
5237 "Every change indicates that a table might need an update."
5238 (setq org-table-may-need-update t))
5239 (defvar org-mode-map)
5240 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5241 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5242 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5243 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5244 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5245 (defvar org-table-buffer-is-an nil)
5247 (defvar bidi-paragraph-direction)
5248 (defvar buffer-face-mode-face)
5250 (require 'outline)
5251 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5252 (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"))
5253 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5255 ;; Other stuff we need.
5256 (require 'time-date)
5257 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5258 (require 'easymenu)
5259 (require 'overlay)
5261 ;; (require 'org-macs) moved higher up in the file before it is first used
5262 (require 'org-entities)
5263 ;; (require 'org-compat) moved higher up in the file before it is first used
5264 (require 'org-faces)
5265 (require 'org-list)
5266 (require 'org-pcomplete)
5267 (require 'org-src)
5268 (require 'org-footnote)
5269 (require 'org-macro)
5271 ;; babel
5272 (require 'ob)
5274 ;;;###autoload
5275 (define-derived-mode org-mode outline-mode "Org"
5276 "Outline-based notes management and organizer, alias
5277 \"Carsten's outline-mode for keeping track of everything.\"
5279 Org-mode develops organizational tasks around a NOTES file which
5280 contains information about projects as plain text. Org-mode is
5281 implemented on top of outline-mode, which is ideal to keep the content
5282 of large files well structured. It supports ToDo items, deadlines and
5283 time stamps, which magically appear in the diary listing of the Emacs
5284 calendar. Tables are easily created with a built-in table editor.
5285 Plain text URL-like links connect to websites, emails (VM), Usenet
5286 messages (Gnus), BBDB entries, and any files related to the project.
5287 For printing and sharing of notes, an Org-mode file (or a part of it)
5288 can be exported as a structured ASCII or HTML file.
5290 The following commands are available:
5292 \\{org-mode-map}"
5294 ;; Get rid of Outline menus, they are not needed
5295 ;; Need to do this here because define-derived-mode sets up
5296 ;; the keymap so late. Still, it is a waste to call this each time
5297 ;; we switch another buffer into org-mode.
5298 (if (featurep 'xemacs)
5299 (when (boundp 'outline-mode-menu-heading)
5300 ;; Assume this is Greg's port, it uses easymenu
5301 (easy-menu-remove outline-mode-menu-heading)
5302 (easy-menu-remove outline-mode-menu-show)
5303 (easy-menu-remove outline-mode-menu-hide))
5304 (define-key org-mode-map [menu-bar headings] 'undefined)
5305 (define-key org-mode-map [menu-bar hide] 'undefined)
5306 (define-key org-mode-map [menu-bar show] 'undefined))
5308 (org-load-modules-maybe)
5309 (easy-menu-add org-org-menu)
5310 (easy-menu-add org-tbl-menu)
5311 (org-install-agenda-files-menu)
5312 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5313 (add-to-invisibility-spec '(org-cwidth))
5314 (add-to-invisibility-spec '(org-hide-block . t))
5315 (when (featurep 'xemacs)
5316 (org-set-local 'line-move-ignore-invisible t))
5317 (org-set-local 'outline-regexp org-outline-regexp)
5318 (org-set-local 'outline-level 'org-outline-level)
5319 (setq bidi-paragraph-direction 'left-to-right)
5320 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5321 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5322 (when (and org-ellipsis
5323 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5324 (fboundp 'make-glyph-code))
5325 (unless org-display-table
5326 (setq org-display-table (make-display-table)))
5327 (set-display-table-slot
5328 org-display-table 4
5329 (vconcat (mapcar
5330 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5331 org-ellipsis)))
5332 (if (stringp org-ellipsis) org-ellipsis "..."))))
5333 (setq buffer-display-table org-display-table))
5334 (org-set-regexps-and-options-for-tags)
5335 (org-set-regexps-and-options)
5336 (when (and org-tag-faces (not org-tags-special-faces-re))
5337 ;; tag faces set outside customize.... force initialization.
5338 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5339 ;; Calc embedded
5340 (org-set-local 'calc-embedded-open-mode "# ")
5341 ;; Modify a few syntax entries
5342 (modify-syntax-entry ?@ "w")
5343 (modify-syntax-entry ?\" "\"")
5344 (if org-startup-truncated (setq truncate-lines t))
5345 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5346 (org-set-local 'font-lock-unfontify-region-function
5347 'org-unfontify-region)
5348 ;; Activate before-change-function
5349 (org-set-local 'org-table-may-need-update t)
5350 (org-add-hook 'before-change-functions 'org-before-change-function nil
5351 'local)
5352 ;; Check for running clock before killing a buffer
5353 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5354 ;; Initialize macros templates.
5355 (org-macro-initialize-templates)
5356 ;; Initialize radio targets.
5357 (org-update-radio-target-regexp)
5358 ;; Indentation.
5359 (org-set-local 'indent-line-function 'org-indent-line)
5360 (org-set-local 'indent-region-function 'org-indent-region)
5361 ;; Filling and auto-filling.
5362 (org-setup-filling)
5363 ;; Comments.
5364 (org-setup-comments-handling)
5365 ;; Beginning/end of defun
5366 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5367 (org-set-local 'end-of-defun-function 'org-forward-element)
5368 ;; Next error for sparse trees
5369 (org-set-local 'next-error-function 'org-occur-next-match)
5370 ;; Make sure dependence stuff works reliably, even for users who set it
5371 ;; too late :-(
5372 (if org-enforce-todo-dependencies
5373 (add-hook 'org-blocker-hook
5374 'org-block-todo-from-children-or-siblings-or-parent)
5375 (remove-hook 'org-blocker-hook
5376 'org-block-todo-from-children-or-siblings-or-parent))
5377 (if org-enforce-todo-checkbox-dependencies
5378 (add-hook 'org-blocker-hook
5379 'org-block-todo-from-checkboxes)
5380 (remove-hook 'org-blocker-hook
5381 'org-block-todo-from-checkboxes))
5383 ;; Align options lines
5384 (org-set-local
5385 'align-mode-rules-list
5386 '((org-in-buffer-settings
5387 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5388 (modes . '(org-mode)))))
5390 ;; Imenu
5391 (org-set-local 'imenu-create-index-function
5392 'org-imenu-get-tree)
5394 ;; Make isearch reveal context
5395 (if (or (featurep 'xemacs)
5396 (not (boundp 'outline-isearch-open-invisible-function)))
5397 ;; Emacs 21 and XEmacs make use of the hook
5398 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5399 ;; Emacs 22 deals with this through a special variable
5400 (org-set-local 'outline-isearch-open-invisible-function
5401 (lambda (&rest ignore) (org-show-context 'isearch)))
5402 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5404 ;; Setup the pcomplete hooks
5405 (set (make-local-variable 'pcomplete-command-completion-function)
5406 'org-pcomplete-initial)
5407 (set (make-local-variable 'pcomplete-command-name-function)
5408 'org-command-at-point)
5409 (set (make-local-variable 'pcomplete-default-completion-function)
5410 'ignore)
5411 (set (make-local-variable 'pcomplete-parse-arguments-function)
5412 'org-parse-arguments)
5413 (set (make-local-variable 'pcomplete-termination-string) "")
5414 (when (>= emacs-major-version 23)
5415 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5417 ;; If empty file that did not turn on org-mode automatically, make it to.
5418 (if (and org-insert-mode-line-in-empty-file
5419 (org-called-interactively-p 'any)
5420 (= (point-min) (point-max)))
5421 (insert "# -*- mode: org -*-\n\n"))
5422 (unless org-inhibit-startup
5423 (org-unmodified
5424 (and org-startup-with-beamer-mode (org-beamer-mode))
5425 (when org-startup-align-all-tables
5426 (org-table-map-tables 'org-table-align 'quietly))
5427 (when org-startup-with-inline-images
5428 (org-display-inline-images))
5429 (when org-startup-with-latex-preview
5430 (org-preview-latex-fragment))
5431 (unless org-inhibit-startup-visibility-stuff
5432 (org-set-startup-visibility))))
5433 ;; Try to set org-hide correctly
5434 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5436 ;; Update `customize-package-emacs-version-alist'
5437 (add-to-list 'customize-package-emacs-version-alist
5438 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5439 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5440 ("8.0" . "24.4")))
5442 (defvar org-mode-transpose-word-syntax-table
5443 (let ((st (make-syntax-table)))
5444 (mapc (lambda(c) (modify-syntax-entry
5445 (string-to-char (car c)) "w p" st))
5446 org-emphasis-alist)
5447 st))
5449 (when (fboundp 'abbrev-table-put)
5450 (abbrev-table-put org-mode-abbrev-table
5451 :parents (list text-mode-abbrev-table)))
5453 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5455 (defsubst org-fix-ellipsis-at-bol ()
5456 (save-excursion (goto-char (window-start)) (recenter 0)))
5458 (defun org-find-invisible-foreground ()
5459 (let ((candidates (remove
5460 "unspecified-bg"
5461 (nconc
5462 (list (face-background 'default)
5463 (face-background 'org-default))
5464 (mapcar
5465 (lambda (alist)
5466 (when (boundp alist)
5467 (cdr (assoc 'background-color (symbol-value alist)))))
5468 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5469 (list (face-foreground 'org-hide))))))
5470 (car (remove nil candidates))))
5472 (defun org-current-time (&optional rounding-minutes past)
5473 "Current time, possibly rounded to ROUNDING-MINUTES.
5474 When ROUNDING-MINUTES is not an integer, fall back on the car of
5475 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5476 the rounding returns a past time."
5477 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5478 (car org-time-stamp-rounding-minutes)))
5479 (time (decode-time)) res)
5480 (if (< r 1)
5481 (current-time)
5482 (setq res
5483 (apply 'encode-time
5484 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5485 (nthcdr 2 time))))
5486 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5487 (seconds-to-time (- (org-float-time res) (* r 60)))
5488 res))))
5490 (defun org-today ()
5491 "Return today date, considering `org-extend-today-until'."
5492 (time-to-days
5493 (time-subtract (current-time)
5494 (list 0 (* 3600 org-extend-today-until) 0))))
5496 ;;;; Font-Lock stuff, including the activators
5498 (defvar org-mouse-map (make-sparse-keymap))
5499 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5500 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5501 (when org-mouse-1-follows-link
5502 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5503 (when org-tab-follows-link
5504 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5505 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5507 (require 'font-lock)
5509 (defconst org-non-link-chars "]\t\n\r<>")
5510 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5511 "shell" "elisp" "doi" "message"))
5512 (defvar org-link-types-re nil
5513 "Matches a link that has a url-like prefix like \"http:\"")
5514 (defvar org-link-re-with-space nil
5515 "Matches a link with spaces, optional angular brackets around it.")
5516 (defvar org-link-re-with-space2 nil
5517 "Matches a link with spaces, optional angular brackets around it.")
5518 (defvar org-link-re-with-space3 nil
5519 "Matches a link with spaces, only for internal part in bracket links.")
5520 (defvar org-angle-link-re nil
5521 "Matches link with angular brackets, spaces are allowed.")
5522 (defvar org-plain-link-re nil
5523 "Matches plain link, without spaces.")
5524 (defvar org-bracket-link-regexp nil
5525 "Matches a link in double brackets.")
5526 (defvar org-bracket-link-analytic-regexp nil
5527 "Regular expression used to analyze links.
5528 Here is what the match groups contain after a match:
5529 1: http:
5530 2: http
5531 3: path
5532 4: [desc]
5533 5: desc")
5534 (defvar org-bracket-link-analytic-regexp++ nil
5535 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5536 (defvar org-any-link-re nil
5537 "Regular expression matching any link.")
5539 (defconst org-match-sexp-depth 3
5540 "Number of stacked braces for sub/superscript matching.")
5542 (defun org-create-multibrace-regexp (left right n)
5543 "Create a regular expression which will match a balanced sexp.
5544 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5545 as single character strings.
5546 The regexp returned will match the entire expression including the
5547 delimiters. It will also define a single group which contains the
5548 match except for the outermost delimiters. The maximum depth of
5549 stacked delimiters is N. Escaping delimiters is not possible."
5550 (let* ((nothing (concat "[^" left right "]*?"))
5551 (or "\\|")
5552 (re nothing)
5553 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5554 (while (> n 1)
5555 (setq n (1- n)
5556 re (concat re or next)
5557 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5558 (concat left "\\(" re "\\)" right)))
5560 (defvar org-match-substring-regexp
5561 (concat
5562 "\\(\\S-\\)\\([_^]\\)\\("
5563 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5564 "\\|"
5565 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5566 "\\|"
5567 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5568 "The regular expression matching a sub- or superscript.")
5570 (defvar org-match-substring-with-braces-regexp
5571 (concat
5572 "\\(\\S-\\)\\([_^]\\)\\("
5573 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5574 "\\)")
5575 "The regular expression matching a sub- or superscript, forcing braces.")
5577 (defun org-make-link-regexps ()
5578 "Update the link regular expressions.
5579 This should be called after the variable `org-link-types' has changed."
5580 (setq org-link-types-re
5581 (concat
5582 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5583 org-link-re-with-space
5584 (concat
5585 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5586 "\\([^" org-non-link-chars " ]"
5587 "[^" org-non-link-chars "]*"
5588 "[^" org-non-link-chars " ]\\)>?")
5589 org-link-re-with-space2
5590 (concat
5591 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5592 "\\([^" org-non-link-chars " ]"
5593 "[^\t\n\r]*"
5594 "[^" org-non-link-chars " ]\\)>?")
5595 org-link-re-with-space3
5596 (concat
5597 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5598 "\\([^" org-non-link-chars " ]"
5599 "[^\t\n\r]*\\)")
5600 org-angle-link-re
5601 (concat
5602 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5603 "\\([^" org-non-link-chars " ]"
5604 "[^" org-non-link-chars "]*"
5605 "\\)>")
5606 org-plain-link-re
5607 (concat
5608 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5609 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5610 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5611 org-bracket-link-regexp
5612 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5613 org-bracket-link-analytic-regexp
5614 (concat
5615 "\\[\\["
5616 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5617 "\\([^]]+\\)"
5618 "\\]"
5619 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5620 "\\]")
5621 org-bracket-link-analytic-regexp++
5622 (concat
5623 "\\[\\["
5624 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5625 "\\([^]]+\\)"
5626 "\\]"
5627 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5628 "\\]")
5629 org-any-link-re
5630 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5631 org-angle-link-re "\\)\\|\\("
5632 org-plain-link-re "\\)")))
5634 (org-make-link-regexps)
5636 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5637 "Regular expression for fast time stamp matching.")
5638 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5639 "Regular expression for fast time stamp matching.")
5640 (defconst org-ts-regexp0
5641 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5642 "Regular expression matching time strings for analysis.
5643 This one does not require the space after the date, so it can be used
5644 on a string that terminates immediately after the date.")
5645 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5646 "Regular expression matching time strings for analysis.")
5647 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5648 "Regular expression matching time stamps, with groups.")
5649 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5650 "Regular expression matching time stamps (also [..]), with groups.")
5651 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5652 "Regular expression matching a time stamp range.")
5653 (defconst org-tr-regexp-both
5654 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5655 "Regular expression matching a time stamp range.")
5656 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5657 org-ts-regexp "\\)?")
5658 "Regular expression matching a time stamp or time stamp range.")
5659 (defconst org-tsr-regexp-both
5660 (concat org-ts-regexp-both "\\(--?-?"
5661 org-ts-regexp-both "\\)?")
5662 "Regular expression matching a time stamp or time stamp range.
5663 The time stamps may be either active or inactive.")
5665 (defvar org-emph-face nil)
5667 (defun org-do-emphasis-faces (limit)
5668 "Run through the buffer and add overlays to emphasized strings."
5669 (let (rtn a)
5670 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5671 (if (not (= (char-after (match-beginning 3))
5672 (char-after (match-beginning 4))))
5673 (progn
5674 (setq rtn t)
5675 (setq a (assoc (match-string 3) org-emphasis-alist))
5676 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5677 'face
5678 (nth 1 a))
5679 (and (nth 4 a)
5680 (org-remove-flyspell-overlays-in
5681 (match-beginning 0) (match-end 0)))
5682 (add-text-properties (match-beginning 2) (match-end 2)
5683 '(font-lock-multiline t org-emphasis t))
5684 (when org-hide-emphasis-markers
5685 (add-text-properties (match-end 4) (match-beginning 5)
5686 '(invisible org-link))
5687 (add-text-properties (match-beginning 3) (match-end 3)
5688 '(invisible org-link)))))
5689 (backward-char 1))
5690 rtn))
5692 (defun org-emphasize (&optional char)
5693 "Insert or change an emphasis, i.e. a font like bold or italic.
5694 If there is an active region, change that region to a new emphasis.
5695 If there is no region, just insert the marker characters and position
5696 the cursor between them.
5697 CHAR should be the marker character. If it is a space, it means to
5698 remove the emphasis of the selected region.
5699 If CHAR is not given (for example in an interactive call) it will be
5700 prompted for."
5701 (interactive)
5702 (let ((erc org-emphasis-regexp-components)
5703 (prompt "")
5704 (string "") beg end move c s)
5705 (if (org-region-active-p)
5706 (setq beg (region-beginning) end (region-end)
5707 string (buffer-substring beg end))
5708 (setq move t))
5710 (unless char
5711 (message "Emphasis marker or tag: [%s]"
5712 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5713 (setq char (read-char-exclusive)))
5714 (if (equal char ?\ )
5715 (setq s "" move nil)
5716 (unless (assoc (char-to-string char) org-emphasis-alist)
5717 (user-error "No such emphasis marker: \"%c\"" char))
5718 (setq s (char-to-string char)))
5719 (while (and (> (length string) 1)
5720 (equal (substring string 0 1) (substring string -1))
5721 (assoc (substring string 0 1) org-emphasis-alist))
5722 (setq string (substring string 1 -1)))
5723 (setq string (concat s string s))
5724 (if beg (delete-region beg end))
5725 (unless (or (bolp)
5726 (string-match (concat "[" (nth 0 erc) "\n]")
5727 (char-to-string (char-before (point)))))
5728 (insert " "))
5729 (unless (or (eobp)
5730 (string-match (concat "[" (nth 1 erc) "\n]")
5731 (char-to-string (char-after (point)))))
5732 (insert " ") (backward-char 1))
5733 (insert string)
5734 (and move (backward-char 1))))
5736 (defconst org-nonsticky-props
5737 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5739 (defsubst org-rear-nonsticky-at (pos)
5740 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5742 (defun org-activate-plain-links (limit)
5743 "Run through the buffer and add overlays to links."
5744 (let (f hl)
5745 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5746 (not (org-in-src-block-p)))
5747 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5748 (setq f (get-text-property (match-beginning 0) 'face))
5749 (setq hl (org-match-string-no-properties 0))
5750 (if (or (eq f 'org-tag)
5751 (and (listp f) (memq 'org-tag f)))
5753 (add-text-properties (match-beginning 0) (match-end 0)
5754 (list 'mouse-face 'highlight
5755 'face 'org-link
5756 'htmlize-link `(:uri ,hl)
5757 'keymap org-mouse-map))
5758 (org-rear-nonsticky-at (match-end 0)))
5759 t)))
5761 (defun org-activate-code (limit)
5762 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5763 (progn
5764 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5765 (remove-text-properties (match-beginning 0) (match-end 0)
5766 '(display t invisible t intangible t))
5767 t)))
5769 (defcustom org-src-fontify-natively nil
5770 "When non-nil, fontify code in code blocks."
5771 :type 'boolean
5772 :version "24.1"
5773 :group 'org-appearance
5774 :group 'org-babel)
5776 (defcustom org-allow-promoting-top-level-subtree nil
5777 "When non-nil, allow promoting a top level subtree.
5778 The leading star of the top level headline will be replaced
5779 by a #."
5780 :type 'boolean
5781 :version "24.1"
5782 :group 'org-appearance)
5784 (defun org-fontify-meta-lines-and-blocks (limit)
5785 (condition-case nil
5786 (org-fontify-meta-lines-and-blocks-1 limit)
5787 (error (message "org-mode fontification error"))))
5789 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5790 "Fontify #+ lines and blocks."
5791 (let ((case-fold-search t))
5792 (if (re-search-forward
5793 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5794 limit t)
5795 (let ((beg (match-beginning 0))
5796 (block-start (match-end 0))
5797 (block-end nil)
5798 (lang (match-string 7))
5799 (beg1 (line-beginning-position 2))
5800 (dc1 (downcase (match-string 2)))
5801 (dc3 (downcase (match-string 3)))
5802 end end1 quoting block-type ovl)
5803 (cond
5804 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5805 ;; a single line of backend-specific content
5806 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5807 (remove-text-properties (match-beginning 0) (match-end 0)
5808 '(display t invisible t intangible t))
5809 (add-text-properties (match-beginning 1) (match-end 3)
5810 '(font-lock-fontified t face org-meta-line))
5811 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5812 '(font-lock-fontified t face org-block))
5813 ; for backend-specific code
5815 ((and (match-end 4) (equal dc3 "+begin"))
5816 ;; Truly a block
5817 (setq block-type (downcase (match-string 5))
5818 quoting (member block-type org-protecting-blocks))
5819 (when (re-search-forward
5820 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5821 nil t) ;; on purpose, we look further than LIMIT
5822 (setq end (min (point-max) (match-end 0))
5823 end1 (min (point-max) (1- (match-beginning 0))))
5824 (setq block-end (match-beginning 0))
5825 (when quoting
5826 (remove-text-properties beg end
5827 '(display t invisible t intangible t)))
5828 (add-text-properties
5829 beg end
5830 '(font-lock-fontified t font-lock-multiline t))
5831 (add-text-properties beg beg1 '(face org-meta-line))
5832 (add-text-properties end1 (min (point-max) (1+ end))
5833 '(face org-meta-line)) ; for end_src
5834 (cond
5835 ((and lang (not (string= lang "")) org-src-fontify-natively)
5836 (org-src-font-lock-fontify-block lang block-start block-end)
5837 ;; remove old background overlays
5838 (mapc (lambda (ov)
5839 (if (eq (overlay-get ov 'face) 'org-block-background)
5840 (delete-overlay ov)))
5841 (overlays-at (/ (+ beg1 block-end) 2)))
5842 ;; add a background overlay
5843 (setq ovl (make-overlay beg1 block-end))
5844 (overlay-put ovl 'face 'org-block-background)
5845 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5846 (quoting
5847 (add-text-properties beg1 (min (point-max) (1+ end1))
5848 '(face org-block))) ; end of source block
5849 ((not org-fontify-quote-and-verse-blocks))
5850 ((string= block-type "quote")
5851 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5852 ((string= block-type "verse")
5853 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5854 (add-text-properties beg beg1 '(face org-block-begin-line))
5855 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5856 '(face org-block-end-line))
5858 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5859 (add-text-properties
5860 beg (match-end 3)
5861 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5862 '(font-lock-fontified t invisible t)
5863 '(font-lock-fontified t face org-document-info-keyword)))
5864 (add-text-properties
5865 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5866 (if (string-equal dc1 "+title:")
5867 '(font-lock-fontified t face org-document-title)
5868 '(font-lock-fontified t face org-document-info))))
5869 ((or (equal dc1 "+results")
5870 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5871 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5872 "+call:" "+header:" "+headers:" "+name:"))
5873 (and (match-end 4) (equal dc3 "+attr")))
5874 (add-text-properties
5875 beg (match-end 0)
5876 '(font-lock-fontified t face org-meta-line))
5878 ((member dc3 '(" " ""))
5879 (add-text-properties
5880 beg (match-end 0)
5881 '(font-lock-fontified t face font-lock-comment-face)))
5882 ((not (member (char-after beg) '(?\ ?\t)))
5883 ;; just any other in-buffer setting, but not indented
5884 (add-text-properties
5885 beg (match-end 0)
5886 '(font-lock-fontified t face org-meta-line))
5888 (t nil))))))
5890 (defun org-activate-angle-links (limit)
5891 "Run through the buffer and add overlays to links."
5892 (if (and (re-search-forward org-angle-link-re limit t)
5893 (not (org-in-src-block-p)))
5894 (progn
5895 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5896 (add-text-properties (match-beginning 0) (match-end 0)
5897 (list 'mouse-face 'highlight
5898 'keymap org-mouse-map))
5899 (org-rear-nonsticky-at (match-end 0))
5900 t)))
5902 (defun org-activate-footnote-links (limit)
5903 "Run through the buffer and add overlays to footnotes."
5904 (let ((fn (org-footnote-next-reference-or-definition limit)))
5905 (when fn
5906 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5907 (org-remove-flyspell-overlays-in beg end)
5908 (add-text-properties beg end
5909 (list 'mouse-face 'highlight
5910 'keymap org-mouse-map
5911 'help-echo
5912 (if (= (point-at-bol) beg)
5913 "Footnote definition"
5914 "Footnote reference")
5915 'font-lock-fontified t
5916 'font-lock-multiline t
5917 'face 'org-footnote))))))
5919 (defun org-activate-bracket-links (limit)
5920 "Run through the buffer and add overlays to bracketed links."
5921 (if (and (re-search-forward org-bracket-link-regexp limit t)
5922 (not (org-in-src-block-p)))
5923 (let* ((hl (org-match-string-no-properties 1))
5924 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5925 (ip (org-maybe-intangible
5926 (list 'invisible 'org-link
5927 'keymap org-mouse-map 'mouse-face 'highlight
5928 'font-lock-multiline t 'help-echo help
5929 'htmlize-link `(:uri ,hl))))
5930 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5931 'font-lock-multiline t 'help-echo help
5932 'htmlize-link `(:uri ,hl))))
5933 ;; We need to remove the invisible property here. Table narrowing
5934 ;; may have made some of this invisible.
5935 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5936 (remove-text-properties (match-beginning 0) (match-end 0)
5937 '(invisible nil))
5938 (if (match-end 3)
5939 (progn
5940 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5941 (org-rear-nonsticky-at (match-beginning 3))
5942 (add-text-properties (match-beginning 3) (match-end 3) vp)
5943 (org-rear-nonsticky-at (match-end 3))
5944 (add-text-properties (match-end 3) (match-end 0) ip)
5945 (org-rear-nonsticky-at (match-end 0)))
5946 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5947 (org-rear-nonsticky-at (match-beginning 1))
5948 (add-text-properties (match-beginning 1) (match-end 1) vp)
5949 (org-rear-nonsticky-at (match-end 1))
5950 (add-text-properties (match-end 1) (match-end 0) ip)
5951 (org-rear-nonsticky-at (match-end 0)))
5952 t)))
5954 (defun org-activate-dates (limit)
5955 "Run through the buffer and add overlays to dates."
5956 (if (and (re-search-forward org-tsr-regexp-both limit t)
5957 (not (equal (char-before (match-beginning 0)) 91)))
5958 (progn
5959 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5960 (add-text-properties (match-beginning 0) (match-end 0)
5961 (list 'mouse-face 'highlight
5962 'keymap org-mouse-map))
5963 (org-rear-nonsticky-at (match-end 0))
5964 (when org-display-custom-times
5965 (if (match-end 3)
5966 (org-display-custom-time (match-beginning 3) (match-end 3)))
5967 (org-display-custom-time (match-beginning 1) (match-end 1)))
5968 t)))
5970 (defvar org-target-link-regexp nil
5971 "Regular expression matching radio targets in plain text.")
5972 (make-variable-buffer-local 'org-target-link-regexp)
5973 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5974 "Regular expression matching a link target.")
5975 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5976 "Regular expression matching a radio target.")
5977 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5978 "Regular expression matching any target.")
5980 (defun org-activate-target-links (limit)
5981 "Run through the buffer and add overlays to target matches."
5982 (when org-target-link-regexp
5983 (let ((case-fold-search t))
5984 (if (re-search-forward org-target-link-regexp limit t)
5985 (progn
5986 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5987 (add-text-properties (match-beginning 0) (match-end 0)
5988 (list 'mouse-face 'highlight
5989 'keymap org-mouse-map
5990 'help-echo "Radio target link"
5991 'org-linked-text t))
5992 (org-rear-nonsticky-at (match-end 0))
5993 t)))))
5995 (defun org-update-radio-target-regexp ()
5996 "Find all radio targets in this file and update the regular expression."
5997 (interactive)
5998 (when (memq 'radio org-activate-links)
5999 (setq org-target-link-regexp
6000 (org-make-target-link-regexp (org-all-targets 'radio)))
6001 (org-restart-font-lock)))
6003 (defun org-hide-wide-columns (limit)
6004 (let (s e)
6005 (setq s (text-property-any (point) (or limit (point-max))
6006 'org-cwidth t))
6007 (when s
6008 (setq e (next-single-property-change s 'org-cwidth))
6009 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6010 (goto-char e)
6011 t)))
6013 (defvar org-latex-and-related-regexp nil
6014 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6015 (defvar org-match-substring-regexp)
6016 (defvar org-match-substring-with-braces-regexp)
6018 (defun org-compute-latex-and-related-regexp ()
6019 "Compute regular expression for LaTeX, entities and sub/superscript.
6020 Result depends on variable `org-highlight-latex-and-related'."
6021 (org-set-local
6022 'org-latex-and-related-regexp
6023 (let* ((re-sub
6024 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6025 ((eq org-use-sub-superscripts '{})
6026 (list org-match-substring-with-braces-regexp))
6027 (org-use-sub-superscripts (list org-match-substring-regexp))))
6028 (re-latex
6029 (when (memq 'latex org-highlight-latex-and-related)
6030 (let ((matchers (plist-get org-format-latex-options :matchers)))
6031 (delq nil
6032 (mapcar (lambda (x)
6033 (and (member (car x) matchers) (nth 1 x)))
6034 org-latex-regexps)))))
6035 (re-entities
6036 (when (memq 'entities org-highlight-latex-and-related)
6037 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6038 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6040 (defun org-do-latex-and-related (limit)
6041 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6042 LIMIT bounds the search for syntax to highlight. Stop at first
6043 highlighted object, if any. Return t if some highlighting was
6044 done, nil otherwise."
6045 (when (org-string-nw-p org-latex-and-related-regexp)
6046 (catch 'found
6047 (while (re-search-forward org-latex-and-related-regexp limit t)
6048 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6049 'face))
6050 '(org-code org-verbatim underline))
6051 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6052 '(?_ ?^))
6054 0)))
6055 (font-lock-prepend-text-property
6056 (+ offset (match-beginning 0)) (match-end 0)
6057 'face 'org-latex-and-related)
6058 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6059 '(font-lock-multiline t)))
6060 (throw 'found t)))
6061 nil)))
6063 (defun org-restart-font-lock ()
6064 "Restart `font-lock-mode', to force refontification."
6065 (when (and (boundp 'font-lock-mode) font-lock-mode)
6066 (font-lock-mode -1)
6067 (font-lock-mode 1)))
6069 (defun org-all-targets (&optional radio)
6070 "Return a list of all targets in this file.
6071 When optional argument RADIO is non-nil, only find radio
6072 targets."
6073 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6074 (save-excursion
6075 (goto-char (point-min))
6076 (while (re-search-forward re nil t)
6077 ;; Make sure point is really within the object.
6078 (backward-char)
6079 (let ((obj (org-element-context)))
6080 (when (memq (org-element-type obj) '(radio-target target))
6081 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6082 rtn)))
6084 (defun org-make-target-link-regexp (targets)
6085 "Make regular expression matching all strings in TARGETS.
6086 The regular expression finds the targets also if there is a line break
6087 between words."
6088 (and targets
6089 (concat
6090 "\\<\\("
6091 (mapconcat
6092 (lambda (x)
6093 (setq x (regexp-quote x))
6094 (while (string-match " +" x)
6095 (setq x (replace-match "\\s-+" t t x)))
6097 targets
6098 "\\|")
6099 "\\)\\>")))
6101 (defun org-activate-tags (limit)
6102 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6103 (progn
6104 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6105 (add-text-properties (match-beginning 1) (match-end 1)
6106 (list 'mouse-face 'highlight
6107 'keymap org-mouse-map))
6108 (org-rear-nonsticky-at (match-end 1))
6109 t)))
6111 (defun org-outline-level ()
6112 "Compute the outline level of the heading at point.
6113 If this is called at a normal headline, the level is the number of stars.
6114 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6115 (save-excursion
6116 (if (not (condition-case nil
6117 (org-back-to-heading t)
6118 (error nil)))
6120 (looking-at org-outline-regexp)
6121 (1- (- (match-end 0) (match-beginning 0))))))
6123 (defvar org-font-lock-keywords nil)
6125 (defconst org-property-re
6126 "^\\(?4:[ \t]*\\)\\(?1::\\(?2:.*?\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"
6127 "Regular expression matching a property line.
6128 There are four matching groups:
6129 1: :PROPKEY: including the leading and trailing colon,
6130 2: PROPKEY without the leading and trailing colon,
6131 3: PROPVAL without leading or trailing spaces,
6132 4: the indentation of the current line,
6133 5: trailing whitespace.")
6135 (defvar org-font-lock-hook nil
6136 "Functions to be called for special font lock stuff.")
6138 (defvar org-font-lock-set-keywords-hook nil
6139 "Functions that can manipulate `org-font-lock-extra-keywords'.
6140 This is called after `org-font-lock-extra-keywords' is defined, but before
6141 it is installed to be used by font lock. This can be useful if something
6142 needs to be inserted at a specific position in the font-lock sequence.")
6144 (defun org-font-lock-hook (limit)
6145 "Run `org-font-lock-hook' within LIMIT."
6146 (run-hook-with-args 'org-font-lock-hook limit))
6148 (defun org-set-font-lock-defaults ()
6149 "Set font lock defaults for the current buffer."
6150 (let* ((em org-fontify-emphasized-text)
6151 (lk org-activate-links)
6152 (org-font-lock-extra-keywords
6153 (list
6154 ;; Call the hook
6155 '(org-font-lock-hook)
6156 ;; Headlines
6157 `(,(if org-fontify-whole-heading-line
6158 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6159 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6160 (1 (org-get-level-face 1))
6161 (2 (org-get-level-face 2))
6162 (3 (org-get-level-face 3)))
6163 ;; Table lines
6164 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6165 (1 'org-table t))
6166 ;; Table internals
6167 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6168 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6169 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6170 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6171 ;; Drawers
6172 (list org-drawer-regexp '(0 'org-special-keyword t))
6173 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6174 ;; Properties
6175 (list org-property-re
6176 '(1 'org-special-keyword t)
6177 '(3 'org-property-value t))
6178 ;; Links
6179 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6180 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6181 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6182 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6183 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6184 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6185 (if (memq 'footnote lk) '(org-activate-footnote-links))
6186 ;; Targets.
6187 (list org-any-target-regexp '(0 'org-target t))
6188 ;; Diary sexps.
6189 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6190 ;; Macro
6191 '("{{{.+}}}" (0 'org-macro t))
6192 '(org-hide-wide-columns (0 nil append))
6193 ;; TODO keyword
6194 (list (format org-heading-keyword-regexp-format
6195 org-todo-regexp)
6196 '(2 (org-get-todo-face 2) t))
6197 ;; DONE
6198 (if org-fontify-done-headline
6199 (list (format org-heading-keyword-regexp-format
6200 (concat
6201 "\\(?:"
6202 (mapconcat 'regexp-quote org-done-keywords "\\|")
6203 "\\)"))
6204 '(2 'org-headline-done t))
6205 nil)
6206 ;; Priorities
6207 '(org-font-lock-add-priority-faces)
6208 ;; Tags
6209 '(org-font-lock-add-tag-faces)
6210 ;; Tags groups
6211 (if (and org-group-tags org-tag-groups-alist)
6212 (list (concat org-outline-regexp-bol ".+\\(:"
6213 (regexp-opt (mapcar 'car org-tag-groups-alist))
6214 ":\\).*$")
6215 '(1 'org-tag-group prepend)))
6216 ;; Special keywords
6217 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6218 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6219 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6220 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6221 ;; Emphasis
6222 (if em
6223 (if (featurep 'xemacs)
6224 '(org-do-emphasis-faces (0 nil append))
6225 '(org-do-emphasis-faces)))
6226 ;; Checkboxes
6227 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6228 1 'org-checkbox prepend)
6229 (if (cdr (assq 'checkbox org-list-automatic-rules))
6230 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6231 (0 (org-get-checkbox-statistics-face) t)))
6232 ;; Description list items
6233 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6234 1 'org-list-dt prepend)
6235 ;; ARCHIVEd headings
6236 (list (concat
6237 org-outline-regexp-bol
6238 "\\(.*:" org-archive-tag ":.*\\)")
6239 '(1 'org-archived prepend))
6240 ;; Specials
6241 '(org-do-latex-and-related)
6242 '(org-fontify-entities)
6243 '(org-raise-scripts)
6244 ;; Code
6245 '(org-activate-code (1 'org-code t))
6246 ;; COMMENT
6247 (list (format org-heading-keyword-regexp-format
6248 (concat "\\("
6249 org-comment-string "\\|" org-quote-string
6250 "\\)"))
6251 '(2 'org-special-keyword t))
6252 ;; Blocks and meta lines
6253 '(org-fontify-meta-lines-and-blocks))))
6254 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6255 (run-hooks 'org-font-lock-set-keywords-hook)
6256 ;; Now set the full font-lock-keywords
6257 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6258 (org-set-local 'font-lock-defaults
6259 '(org-font-lock-keywords t nil nil backward-paragraph))
6260 (kill-local-variable 'font-lock-keywords) nil))
6262 (defun org-toggle-pretty-entities ()
6263 "Toggle the composition display of entities as UTF8 characters."
6264 (interactive)
6265 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6266 (org-restart-font-lock)
6267 (if org-pretty-entities
6268 (message "Entities are now displayed as UTF8 characters")
6269 (save-restriction
6270 (widen)
6271 (org-decompose-region (point-min) (point-max))
6272 (message "Entities are now displayed as plain text"))))
6274 (defvar org-custom-properties-overlays nil
6275 "List of overlays used for custom properties.")
6276 (make-variable-buffer-local 'org-custom-properties-overlays)
6278 (defun org-toggle-custom-properties-visibility ()
6279 "Display or hide properties in `org-custom-properties'."
6280 (interactive)
6281 (if org-custom-properties-overlays
6282 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6283 (setq org-custom-properties-overlays nil))
6284 (unless (not org-custom-properties)
6285 (save-excursion
6286 (save-restriction
6287 (widen)
6288 (goto-char (point-min))
6289 (while (re-search-forward org-property-re nil t)
6290 (mapc (lambda(p)
6291 (when (equal p (substring (match-string 1) 1 -1))
6292 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6293 (overlay-put o 'invisible t)
6294 (overlay-put o 'org-custom-property t)
6295 (push o org-custom-properties-overlays))))
6296 org-custom-properties)))))))
6298 (defun org-fontify-entities (limit)
6299 "Find an entity to fontify."
6300 (let (ee)
6301 (when org-pretty-entities
6302 (catch 'match
6303 (while (re-search-forward
6304 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6305 limit t)
6306 (if (and (not (org-in-indented-comment-line))
6307 (setq ee (org-entity-get (match-string 1)))
6308 (= (length (nth 6 ee)) 1))
6309 (let*
6310 ((end (if (equal (match-string 2) "{}")
6311 (match-end 2)
6312 (match-end 1))))
6313 (add-text-properties
6314 (match-beginning 0) end
6315 (list 'font-lock-fontified t))
6316 (compose-region (match-beginning 0) end
6317 (nth 6 ee) nil)
6318 (backward-char 1)
6319 (throw 'match t))))
6320 nil))))
6322 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6323 "Fontify string S like in Org-mode."
6324 (with-temp-buffer
6325 (insert s)
6326 (let ((org-odd-levels-only odd-levels))
6327 (org-mode)
6328 (font-lock-fontify-buffer)
6329 (buffer-string))))
6331 (defvar org-m nil)
6332 (defvar org-l nil)
6333 (defvar org-f nil)
6334 (defun org-get-level-face (n)
6335 "Get the right face for match N in font-lock matching of headlines."
6336 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6337 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6338 (if org-cycle-level-faces
6339 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6340 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6341 (cond
6342 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6343 ((eq n 2) org-f)
6344 (t (if org-level-color-stars-only nil org-f))))
6347 (defun org-get-todo-face (kwd)
6348 "Get the right face for a TODO keyword KWD.
6349 If KWD is a number, get the corresponding match group."
6350 (if (numberp kwd) (setq kwd (match-string kwd)))
6351 (or (org-face-from-face-or-color
6352 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6353 (and (member kwd org-done-keywords) 'org-done)
6354 'org-todo))
6356 (defun org-face-from-face-or-color (context inherit face-or-color)
6357 "Create a face list that inherits INHERIT, but sets the foreground color.
6358 When FACE-OR-COLOR is not a string, just return it."
6359 (if (stringp face-or-color)
6360 (list :inherit inherit
6361 (cdr (assoc context org-faces-easy-properties))
6362 face-or-color)
6363 face-or-color))
6365 (defun org-font-lock-add-tag-faces (limit)
6366 "Add the special tag faces."
6367 (when (and org-tag-faces org-tags-special-faces-re)
6368 (while (re-search-forward org-tags-special-faces-re limit t)
6369 (add-text-properties (match-beginning 1) (match-end 1)
6370 (list 'face (org-get-tag-face 1)
6371 'font-lock-fontified t))
6372 (backward-char 1))))
6374 (defun org-font-lock-add-priority-faces (limit)
6375 "Add the special priority faces."
6376 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6377 (when (save-match-data (org-at-heading-p))
6378 (add-text-properties
6379 (match-beginning 0) (match-end 0)
6380 (list 'face (or (org-face-from-face-or-color
6381 'priority 'org-priority
6382 (cdr (assoc (char-after (match-beginning 1))
6383 org-priority-faces)))
6384 'org-priority)
6385 'font-lock-fontified t)))))
6387 (defun org-get-tag-face (kwd)
6388 "Get the right face for a TODO keyword KWD.
6389 If KWD is a number, get the corresponding match group."
6390 (if (numberp kwd) (setq kwd (match-string kwd)))
6391 (or (org-face-from-face-or-color
6392 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6393 'org-tag))
6395 (defun org-unfontify-region (beg end &optional maybe_loudly)
6396 "Remove fontification and activation overlays from links."
6397 (font-lock-default-unfontify-region beg end)
6398 (let* ((buffer-undo-list t)
6399 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6400 (inhibit-modification-hooks t)
6401 deactivate-mark buffer-file-name buffer-file-truename)
6402 (org-decompose-region beg end)
6403 (remove-text-properties beg end
6404 '(mouse-face t keymap t org-linked-text t
6405 invisible t intangible t
6406 org-no-flyspell t org-emphasis t))
6407 (org-remove-font-lock-display-properties beg end)))
6409 (defconst org-script-display '(((raise -0.3) (height 0.7))
6410 ((raise 0.3) (height 0.7))
6411 ((raise -0.5))
6412 ((raise 0.5)))
6413 "Display properties for showing superscripts and subscripts.")
6415 (defun org-remove-font-lock-display-properties (beg end)
6416 "Remove specific display properties that have been added by font lock.
6417 The will remove the raise properties that are used to show superscripts
6418 and subscripts."
6419 (let (next prop)
6420 (while (< beg end)
6421 (setq next (next-single-property-change beg 'display nil end)
6422 prop (get-text-property beg 'display))
6423 (if (member prop org-script-display)
6424 (put-text-property beg next 'display nil))
6425 (setq beg next))))
6427 (defun org-raise-scripts (limit)
6428 "Add raise properties to sub/superscripts."
6429 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6430 (if (re-search-forward
6431 (if (eq org-use-sub-superscripts t)
6432 org-match-substring-regexp
6433 org-match-substring-with-braces-regexp)
6434 limit t)
6435 (let* ((pos (point)) table-p comment-p
6436 (mpos (match-beginning 3))
6437 (emph-p (get-text-property mpos 'org-emphasis))
6438 (link-p (get-text-property mpos 'mouse-face))
6439 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6440 (goto-char (point-at-bol))
6441 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6442 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6443 (goto-char pos)
6444 ;; Handle a_b^c
6445 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6446 (if (or comment-p emph-p link-p keyw-p)
6448 (put-text-property (match-beginning 3) (match-end 0)
6449 'display
6450 (if (equal (char-after (match-beginning 2)) ?^)
6451 (nth (if table-p 3 1) org-script-display)
6452 (nth (if table-p 2 0) org-script-display)))
6453 (add-text-properties (match-beginning 2) (match-end 2)
6454 (list 'invisible t
6455 'org-dwidth t 'org-dwidth-n 1))
6456 (if (and (eq (char-after (match-beginning 3)) ?{)
6457 (eq (char-before (match-end 3)) ?}))
6458 (progn
6459 (add-text-properties
6460 (match-beginning 3) (1+ (match-beginning 3))
6461 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6462 (add-text-properties
6463 (1- (match-end 3)) (match-end 3)
6464 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6465 t)))))
6467 ;;;; Visibility cycling, including org-goto and indirect buffer
6469 ;;; Cycling
6471 (defvar org-cycle-global-status nil)
6472 (make-variable-buffer-local 'org-cycle-global-status)
6473 (put 'org-cycle-global-status 'org-state t)
6474 (defvar org-cycle-subtree-status nil)
6475 (make-variable-buffer-local 'org-cycle-subtree-status)
6476 (put 'org-cycle-subtree-status 'org-state t)
6478 (defvar org-inlinetask-min-level)
6480 ;;;###autoload
6481 (defun org-cycle (&optional arg)
6482 "TAB-action and visibility cycling for Org-mode.
6484 This is the command invoked in Org-mode by the TAB key. Its main purpose
6485 is outline visibility cycling, but it also invokes other actions
6486 in special contexts.
6488 - When this function is called with a prefix argument, rotate the entire
6489 buffer through 3 states (global cycling)
6490 1. OVERVIEW: Show only top-level headlines.
6491 2. CONTENTS: Show all headlines of all levels, but no body text.
6492 3. SHOW ALL: Show everything.
6493 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6494 determined by the variable `org-startup-folded', and by any VISIBILITY
6495 properties in the buffer.
6496 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6497 including any drawers.
6499 - When inside a table, re-align the table and move to the next field.
6501 - When point is at the beginning of a headline, rotate the subtree started
6502 by this line through 3 different states (local cycling)
6503 1. FOLDED: Only the main headline is shown.
6504 2. CHILDREN: The main headline and the direct children are shown.
6505 From this state, you can move to one of the children
6506 and zoom in further.
6507 3. SUBTREE: Show the entire subtree, including body text.
6508 If there is no subtree, switch directly from CHILDREN to FOLDED.
6510 - When point is at the beginning of an empty headline and the variable
6511 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6512 of the headline by demoting and promoting it to likely levels. This
6513 speeds up creation document structure by pressing TAB once or several
6514 times right after creating a new headline.
6516 - When there is a numeric prefix, go up to a heading with level ARG, do
6517 a `show-subtree' and return to the previous cursor position. If ARG
6518 is negative, go up that many levels.
6520 - When point is not at the beginning of a headline, execute the global
6521 binding for TAB, which is re-indenting the line. See the option
6522 `org-cycle-emulate-tab' for details.
6524 - Special case: if point is at the beginning of the buffer and there is
6525 no headline in line 1, this function will act as if called with prefix arg
6526 (C-u TAB, same as S-TAB) also when called without prefix arg.
6527 But only if also the variable `org-cycle-global-at-bob' is t."
6528 (interactive "P")
6529 (org-load-modules-maybe)
6530 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6531 (and org-cycle-level-after-item/entry-creation
6532 (or (org-cycle-level)
6533 (org-cycle-item-indentation))))
6534 (let* (message-log-max ; Don't populate the *Messages* buffer
6535 (limit-level
6536 (or org-cycle-max-level
6537 (and (boundp 'org-inlinetask-min-level)
6538 org-inlinetask-min-level
6539 (1- org-inlinetask-min-level))))
6540 (nstars (and limit-level
6541 (if org-odd-levels-only
6542 (and limit-level (1- (* limit-level 2)))
6543 limit-level)))
6544 (org-outline-regexp
6545 (if (not (derived-mode-p 'org-mode))
6546 outline-regexp
6547 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6548 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6549 (not (looking-at org-outline-regexp))))
6550 (org-cycle-hook
6551 (if bob-special
6552 (delq 'org-optimize-window-after-visibility-change
6553 (copy-sequence org-cycle-hook))
6554 org-cycle-hook))
6555 (pos (point)))
6557 (if (or bob-special (equal arg '(4)))
6558 ;; special case: use global cycling
6559 (setq arg t))
6561 (cond
6563 ((equal arg '(16))
6564 (setq last-command 'dummy)
6565 (org-set-startup-visibility)
6566 (message "Startup visibility, plus VISIBILITY properties"))
6568 ((equal arg '(64))
6569 (show-all)
6570 (message "Entire buffer visible, including drawers"))
6572 ;; Table: enter it or move to the next field.
6573 ((org-at-table-p 'any)
6574 (if (org-at-table.el-p)
6575 (message "Use C-c ' to edit table.el tables")
6576 (if arg (org-table-edit-field t)
6577 (org-table-justify-field-maybe)
6578 (call-interactively 'org-table-next-field))))
6580 ((run-hook-with-args-until-success
6581 'org-tab-after-check-for-table-hook))
6583 ;; Global cycling: delegate to `org-cycle-internal-global'.
6584 ((eq arg t) (org-cycle-internal-global))
6586 ;; Drawers: delegate to `org-flag-drawer'.
6587 ((and org-drawers org-drawer-regexp
6588 (save-excursion
6589 (beginning-of-line 1)
6590 (looking-at org-drawer-regexp)))
6591 (org-flag-drawer ; toggle block visibility
6592 (not (get-char-property (match-end 0) 'invisible))))
6594 ;; Show-subtree, ARG levels up from here.
6595 ((integerp arg)
6596 (save-excursion
6597 (org-back-to-heading)
6598 (outline-up-heading (if (< arg 0) (- arg)
6599 (- (funcall outline-level) arg)))
6600 (org-show-subtree)))
6602 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6603 ((and (featurep 'org-inlinetask)
6604 (org-inlinetask-at-task-p)
6605 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6606 (org-inlinetask-toggle-visibility))
6608 ((org-try-cdlatex-tab))
6610 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6611 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6612 (save-excursion (beginning-of-line 1)
6613 (looking-at org-outline-regexp)))
6614 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6615 (org-cycle-internal-local))
6617 ;; From there: TAB emulation and template completion.
6618 (buffer-read-only (org-back-to-heading))
6620 ((run-hook-with-args-until-success
6621 'org-tab-after-check-for-cycling-hook))
6623 ((org-try-structure-completion))
6625 ((run-hook-with-args-until-success
6626 'org-tab-before-tab-emulation-hook))
6628 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6629 (or (not (bolp))
6630 (not (looking-at org-outline-regexp))))
6631 (call-interactively (global-key-binding "\t")))
6633 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6634 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6635 (or (and (eq org-cycle-emulate-tab 'white)
6636 (= (match-end 0) (point-at-eol)))
6637 (and (eq org-cycle-emulate-tab 'whitestart)
6638 (>= (match-end 0) pos))))
6640 (eq org-cycle-emulate-tab t))
6641 (call-interactively (global-key-binding "\t")))
6643 (t (save-excursion
6644 (org-back-to-heading)
6645 (org-cycle)))))))
6647 (defun org-cycle-internal-global ()
6648 "Do the global cycling action."
6649 ;; Hack to avoid display of messages for .org attachments in Gnus
6650 (let (message-log-max ; Don't populate the *Messages* buffer
6651 (ga (string-match "\\*fontification" (buffer-name))))
6652 (cond
6653 ((and (eq last-command this-command)
6654 (eq org-cycle-global-status 'overview))
6655 ;; We just created the overview - now do table of contents
6656 ;; This can be slow in very large buffers, so indicate action
6657 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6658 (unless ga (message "CONTENTS..."))
6659 (org-content)
6660 (unless ga (message "CONTENTS...done"))
6661 (setq org-cycle-global-status 'contents)
6662 (run-hook-with-args 'org-cycle-hook 'contents))
6664 ((and (eq last-command this-command)
6665 (eq org-cycle-global-status 'contents))
6666 ;; We just showed the table of contents - now show everything
6667 (run-hook-with-args 'org-pre-cycle-hook 'all)
6668 (show-all)
6669 (unless ga (message "SHOW ALL"))
6670 (setq org-cycle-global-status 'all)
6671 (run-hook-with-args 'org-cycle-hook 'all))
6674 ;; Default action: go to overview
6675 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6676 (org-overview)
6677 (unless ga (message "OVERVIEW"))
6678 (setq org-cycle-global-status 'overview)
6679 (run-hook-with-args 'org-cycle-hook 'overview)))))
6681 (defun org-cycle-internal-local ()
6682 "Do the local cycling action."
6683 (let (message-log-max ; Don't populate the *Messages* buffer
6684 (goal-column 0) eoh eol eos has-children children-skipped struct)
6685 ;; First, determine end of headline (EOH), end of subtree or item
6686 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6687 (save-excursion
6688 (if (org-at-item-p)
6689 (progn
6690 (beginning-of-line)
6691 (setq struct (org-list-struct))
6692 (setq eoh (point-at-eol))
6693 (setq eos (org-list-get-item-end-before-blank (point) struct))
6694 (setq has-children (org-list-has-child-p (point) struct)))
6695 (org-back-to-heading)
6696 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6697 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6698 (setq has-children
6699 (or (save-excursion
6700 (let ((level (funcall outline-level)))
6701 (outline-next-heading)
6702 (and (org-at-heading-p t)
6703 (> (funcall outline-level) level))))
6704 (save-excursion
6705 (org-list-search-forward (org-item-beginning-re) eos t)))))
6706 ;; Determine end invisible part of buffer (EOL)
6707 (beginning-of-line 2)
6708 ;; XEmacs doesn't have `next-single-char-property-change'
6709 (if (featurep 'xemacs)
6710 (while (and (not (eobp)) ;; this is like `next-line'
6711 (get-char-property (1- (point)) 'invisible))
6712 (beginning-of-line 2))
6713 (while (and (not (eobp)) ;; this is like `next-line'
6714 (get-char-property (1- (point)) 'invisible))
6715 (goto-char (next-single-char-property-change (point) 'invisible))
6716 (and (eolp) (beginning-of-line 2))))
6717 (setq eol (point)))
6718 ;; Find out what to do next and set `this-command'
6719 (cond
6720 ((= eos eoh)
6721 ;; Nothing is hidden behind this heading
6722 (unless (org-before-first-heading-p)
6723 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6724 (message "EMPTY ENTRY")
6725 (setq org-cycle-subtree-status nil)
6726 (save-excursion
6727 (goto-char eos)
6728 (outline-next-heading)
6729 (if (outline-invisible-p) (org-flag-heading nil))))
6730 ((and (or (>= eol eos)
6731 (not (string-match "\\S-" (buffer-substring eol eos))))
6732 (or has-children
6733 (not (setq children-skipped
6734 org-cycle-skip-children-state-if-no-children))))
6735 ;; Entire subtree is hidden in one line: children view
6736 (unless (org-before-first-heading-p)
6737 (run-hook-with-args 'org-pre-cycle-hook 'children))
6738 (if (org-at-item-p)
6739 (org-list-set-item-visibility (point-at-bol) struct 'children)
6740 (org-show-entry)
6741 (org-with-limited-levels (show-children))
6742 ;; FIXME: This slows down the func way too much.
6743 ;; How keep drawers hidden in subtree anyway?
6744 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6745 ;; (org-cycle-hide-drawers 'subtree))
6747 ;; Fold every list in subtree to top-level items.
6748 (when (eq org-cycle-include-plain-lists 'integrate)
6749 (save-excursion
6750 (org-back-to-heading)
6751 (while (org-list-search-forward (org-item-beginning-re) eos t)
6752 (beginning-of-line 1)
6753 (let* ((struct (org-list-struct))
6754 (prevs (org-list-prevs-alist struct))
6755 (end (org-list-get-bottom-point struct)))
6756 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6757 (org-list-get-all-items (point) struct prevs))
6758 (goto-char (if (< end eos) end eos)))))))
6759 (message "CHILDREN")
6760 (save-excursion
6761 (goto-char eos)
6762 (outline-next-heading)
6763 (if (outline-invisible-p) (org-flag-heading nil)))
6764 (setq org-cycle-subtree-status 'children)
6765 (unless (org-before-first-heading-p)
6766 (run-hook-with-args 'org-cycle-hook 'children)))
6767 ((or children-skipped
6768 (and (eq last-command this-command)
6769 (eq org-cycle-subtree-status 'children)))
6770 ;; We just showed the children, or no children are there,
6771 ;; now show everything.
6772 (unless (org-before-first-heading-p)
6773 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6774 (outline-flag-region eoh eos nil)
6775 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6776 (setq org-cycle-subtree-status 'subtree)
6777 (unless (org-before-first-heading-p)
6778 (run-hook-with-args 'org-cycle-hook 'subtree)))
6780 ;; Default action: hide the subtree.
6781 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6782 (outline-flag-region eoh eos t)
6783 (message "FOLDED")
6784 (setq org-cycle-subtree-status 'folded)
6785 (unless (org-before-first-heading-p)
6786 (run-hook-with-args 'org-cycle-hook 'folded))))))
6788 ;;;###autoload
6789 (defun org-global-cycle (&optional arg)
6790 "Cycle the global visibility. For details see `org-cycle'.
6791 With \\[universal-argument] prefix arg, switch to startup visibility.
6792 With a numeric prefix, show all headlines up to that level."
6793 (interactive "P")
6794 (let ((org-cycle-include-plain-lists
6795 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6796 (cond
6797 ((integerp arg)
6798 (show-all)
6799 (hide-sublevels arg)
6800 (setq org-cycle-global-status 'contents))
6801 ((equal arg '(4))
6802 (org-set-startup-visibility)
6803 (message "Startup visibility, plus VISIBILITY properties."))
6805 (org-cycle '(4))))))
6807 (defun org-set-startup-visibility ()
6808 "Set the visibility required by startup options and properties."
6809 (cond
6810 ((eq org-startup-folded t)
6811 (org-cycle '(4)))
6812 ((eq org-startup-folded 'content)
6813 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6814 (org-cycle '(4)) (org-cycle '(4)))))
6815 (unless (eq org-startup-folded 'showeverything)
6816 (if org-hide-block-startup (org-hide-block-all))
6817 (org-set-visibility-according-to-property 'no-cleanup)
6818 (org-cycle-hide-archived-subtrees 'all)
6819 (org-cycle-hide-drawers 'all)
6820 (org-cycle-show-empty-lines t)))
6822 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6823 "Switch subtree visibilities according to :VISIBILITY: property."
6824 (interactive)
6825 (let (org-show-entry-below state)
6826 (save-excursion
6827 (goto-char (point-min))
6828 (while (re-search-forward
6829 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6830 nil t)
6831 (setq state (match-string 1))
6832 (save-excursion
6833 (org-back-to-heading t)
6834 (hide-subtree)
6835 (org-reveal)
6836 (cond
6837 ((equal state '("fold" "folded"))
6838 (hide-subtree))
6839 ((equal state "children")
6840 (org-show-hidden-entry)
6841 (show-children))
6842 ((equal state "content")
6843 (save-excursion
6844 (save-restriction
6845 (org-narrow-to-subtree)
6846 (org-content))))
6847 ((member state '("all" "showall"))
6848 (show-subtree)))))
6849 (unless no-cleanup
6850 (org-cycle-hide-archived-subtrees 'all)
6851 (org-cycle-hide-drawers 'all)
6852 (org-cycle-show-empty-lines 'all)))))
6854 ;; This function uses outline-regexp instead of the more fundamental
6855 ;; org-outline-regexp so that org-cycle-global works outside of Org
6856 ;; buffers, where outline-regexp is needed.
6857 (defun org-overview ()
6858 "Switch to overview mode, showing only top-level headlines.
6859 Really, this shows all headlines with level equal or greater than the level
6860 of the first headline in the buffer. This is important, because if the
6861 first headline is not level one, then (hide-sublevels 1) gives confusing
6862 results."
6863 (interactive)
6864 (let ((l (org-current-line))
6865 (level (save-excursion
6866 (goto-char (point-min))
6867 (if (re-search-forward (concat "^" outline-regexp) nil t)
6868 (progn
6869 (goto-char (match-beginning 0))
6870 (funcall outline-level))))))
6871 (and level (hide-sublevels level))
6872 (recenter '(4))
6873 (org-goto-line l)))
6875 (defun org-content (&optional arg)
6876 "Show all headlines in the buffer, like a table of contents.
6877 With numerical argument N, show content up to level N."
6878 (interactive "P")
6879 (save-excursion
6880 ;; Visit all headings and show their offspring
6881 (and (integerp arg) (org-overview))
6882 (goto-char (point-max))
6883 (catch 'exit
6884 (while (and (progn (condition-case nil
6885 (outline-previous-visible-heading 1)
6886 (error (goto-char (point-min))))
6888 (looking-at org-outline-regexp))
6889 (if (integerp arg)
6890 (show-children (1- arg))
6891 (show-branches))
6892 (if (bobp) (throw 'exit nil))))))
6895 (defun org-optimize-window-after-visibility-change (state)
6896 "Adjust the window after a change in outline visibility.
6897 This function is the default value of the hook `org-cycle-hook'."
6898 (when (get-buffer-window (current-buffer))
6899 (cond
6900 ((eq state 'content) nil)
6901 ((eq state 'all) nil)
6902 ((eq state 'folded) nil)
6903 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6904 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6906 (defun org-remove-empty-overlays-at (pos)
6907 "Remove outline overlays that do not contain non-white stuff."
6908 (mapc
6909 (lambda (o)
6910 (and (eq 'outline (overlay-get o 'invisible))
6911 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6912 (overlay-end o))))
6913 (delete-overlay o)))
6914 (overlays-at pos)))
6916 (defun org-clean-visibility-after-subtree-move ()
6917 "Fix visibility issues after moving a subtree."
6918 ;; First, find a reasonable region to look at:
6919 ;; Start two siblings above, end three below
6920 (let* ((beg (save-excursion
6921 (and (org-get-last-sibling)
6922 (org-get-last-sibling))
6923 (point)))
6924 (end (save-excursion
6925 (and (org-get-next-sibling)
6926 (org-get-next-sibling)
6927 (org-get-next-sibling))
6928 (if (org-at-heading-p)
6929 (point-at-eol)
6930 (point))))
6931 (level (looking-at "\\*+"))
6932 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6933 (save-excursion
6934 (save-restriction
6935 (narrow-to-region beg end)
6936 (when re
6937 ;; Properly fold already folded siblings
6938 (goto-char (point-min))
6939 (while (re-search-forward re nil t)
6940 (if (and (not (outline-invisible-p))
6941 (save-excursion
6942 (goto-char (point-at-eol)) (outline-invisible-p)))
6943 (hide-entry))))
6944 (org-cycle-show-empty-lines 'overview)
6945 (org-cycle-hide-drawers 'overview)))))
6947 (defun org-cycle-show-empty-lines (state)
6948 "Show empty lines above all visible headlines.
6949 The region to be covered depends on STATE when called through
6950 `org-cycle-hook'. Lisp program can use t for STATE to get the
6951 entire buffer covered. Note that an empty line is only shown if there
6952 are at least `org-cycle-separator-lines' empty lines before the headline."
6953 (when (not (= org-cycle-separator-lines 0))
6954 (save-excursion
6955 (let* ((n (abs org-cycle-separator-lines))
6956 (re (cond
6957 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6958 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6959 (t (let ((ns (number-to-string (- n 2))))
6960 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6961 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6962 beg end b e)
6963 (cond
6964 ((memq state '(overview contents t))
6965 (setq beg (point-min) end (point-max)))
6966 ((memq state '(children folded))
6967 (setq beg (point) end (progn (org-end-of-subtree t t)
6968 (beginning-of-line 2)
6969 (point)))))
6970 (when beg
6971 (goto-char beg)
6972 (while (re-search-forward re end t)
6973 (unless (get-char-property (match-end 1) 'invisible)
6974 (setq e (match-end 1))
6975 (if (< org-cycle-separator-lines 0)
6976 (setq b (save-excursion
6977 (goto-char (match-beginning 0))
6978 (org-back-over-empty-lines)
6979 (if (save-excursion
6980 (goto-char (max (point-min) (1- (point))))
6981 (org-at-heading-p))
6982 (1- (point))
6983 (point))))
6984 (setq b (match-beginning 1)))
6985 (outline-flag-region b e nil)))))))
6986 ;; Never hide empty lines at the end of the file.
6987 (save-excursion
6988 (goto-char (point-max))
6989 (outline-previous-heading)
6990 (outline-end-of-heading)
6991 (if (and (looking-at "[ \t\n]+")
6992 (= (match-end 0) (point-max)))
6993 (outline-flag-region (point) (match-end 0) nil))))
6995 (defun org-show-empty-lines-in-parent ()
6996 "Move to the parent and re-show empty lines before visible headlines."
6997 (save-excursion
6998 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6999 (org-cycle-show-empty-lines context))))
7001 (defun org-files-list ()
7002 "Return `org-agenda-files' list, plus all open org-mode files.
7003 This is useful for operations that need to scan all of a user's
7004 open and agenda-wise Org files."
7005 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7006 (dolist (buf (buffer-list))
7007 (with-current-buffer buf
7008 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7009 (let ((file (expand-file-name (buffer-file-name))))
7010 (unless (member file files)
7011 (push file files))))))
7012 files))
7014 (defsubst org-entry-beginning-position ()
7015 "Return the beginning position of the current entry."
7016 (save-excursion (outline-back-to-heading t) (point)))
7018 (defsubst org-entry-end-position ()
7019 "Return the end position of the current entry."
7020 (save-excursion (outline-next-heading) (point)))
7022 (defun org-cycle-hide-drawers (state)
7023 "Re-hide all drawers after a visibility state change."
7024 (when (and (derived-mode-p 'org-mode)
7025 (not (memq state '(overview folded contents))))
7026 (save-excursion
7027 (let* ((globalp (memq state '(contents all)))
7028 (beg (if globalp (point-min) (point)))
7029 (end (if globalp (point-max)
7030 (if (eq state 'children)
7031 (save-excursion (outline-next-heading) (point))
7032 (org-end-of-subtree t)))))
7033 (goto-char beg)
7034 (while (re-search-forward org-drawer-regexp end t)
7035 (org-flag-drawer t))))))
7037 (defun org-cycle-hide-inline-tasks (state)
7038 "Re-hide inline task when switching to 'contents visibility state."
7039 (when (and (eq state 'contents)
7040 (boundp 'org-inlinetask-min-level)
7041 org-inlinetask-min-level)
7042 (hide-sublevels (1- org-inlinetask-min-level))))
7044 (defun org-flag-drawer (flag)
7045 "When FLAG is non-nil, hide the drawer we are within.
7046 Otherwise make it visible."
7047 (save-excursion
7048 (beginning-of-line 1)
7049 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7050 (let ((b (match-end 0)))
7051 (if (re-search-forward
7052 "^[ \t]*:END:"
7053 (save-excursion (outline-next-heading) (point)) t)
7054 (outline-flag-region b (point-at-eol) flag)
7055 (user-error ":END: line missing at position %s" b))))))
7057 (defun org-subtree-end-visible-p ()
7058 "Is the end of the current subtree visible?"
7059 (pos-visible-in-window-p
7060 (save-excursion (org-end-of-subtree t) (point))))
7062 (defun org-first-headline-recenter (&optional N)
7063 "Move cursor to the first headline and recenter the headline.
7064 Optional argument N means put the headline into the Nth line of the window."
7065 (goto-char (point-min))
7066 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7067 (beginning-of-line)
7068 (recenter (prefix-numeric-value N))))
7070 ;;; Saving and restoring visibility
7072 (defun org-outline-overlay-data (&optional use-markers)
7073 "Return a list of the locations of all outline overlays.
7074 These are overlays with the `invisible' property value `outline'.
7075 The return value is a list of cons cells, with start and stop
7076 positions for each overlay.
7077 If USE-MARKERS is set, return the positions as markers."
7078 (let (beg end)
7079 (save-excursion
7080 (save-restriction
7081 (widen)
7082 (delq nil
7083 (mapcar (lambda (o)
7084 (when (eq (overlay-get o 'invisible) 'outline)
7085 (setq beg (overlay-start o)
7086 end (overlay-end o))
7087 (and beg end (> end beg)
7088 (if use-markers
7089 (cons (move-marker (make-marker) beg)
7090 (move-marker (make-marker) end))
7091 (cons beg end)))))
7092 (overlays-in (point-min) (point-max))))))))
7094 (defun org-set-outline-overlay-data (data)
7095 "Create visibility overlays for all positions in DATA.
7096 DATA should have been made by `org-outline-overlay-data'."
7097 (let (o)
7098 (save-excursion
7099 (save-restriction
7100 (widen)
7101 (show-all)
7102 (mapc (lambda (c)
7103 (outline-flag-region (car c) (cdr c) t))
7104 data)))))
7106 ;;; Folding of blocks
7108 (defvar org-hide-block-overlays nil
7109 "Overlays hiding blocks.")
7110 (make-variable-buffer-local 'org-hide-block-overlays)
7112 (defun org-block-map (function &optional start end)
7113 "Call FUNCTION at the head of all source blocks in the current buffer.
7114 Optional arguments START and END can be used to limit the range."
7115 (let ((start (or start (point-min)))
7116 (end (or end (point-max))))
7117 (save-excursion
7118 (goto-char start)
7119 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7120 (save-excursion
7121 (save-match-data
7122 (goto-char (match-beginning 0))
7123 (funcall function)))))))
7125 (defun org-hide-block-toggle-all ()
7126 "Toggle the visibility of all blocks in the current buffer."
7127 (org-block-map #'org-hide-block-toggle))
7129 (defun org-hide-block-all ()
7130 "Fold all blocks in the current buffer."
7131 (interactive)
7132 (org-show-block-all)
7133 (org-block-map #'org-hide-block-toggle-maybe))
7135 (defun org-show-block-all ()
7136 "Unfold all blocks in the current buffer."
7137 (interactive)
7138 (mapc 'delete-overlay org-hide-block-overlays)
7139 (setq org-hide-block-overlays nil))
7141 (defun org-hide-block-toggle-maybe ()
7142 "Toggle visibility of block at point."
7143 (interactive)
7144 (let ((case-fold-search t))
7145 (if (save-excursion
7146 (beginning-of-line 1)
7147 (looking-at org-block-regexp))
7148 (progn (org-hide-block-toggle)
7149 t) ;; to signal that we took action
7150 nil))) ;; to signal that we did not
7152 (defun org-hide-block-toggle (&optional force)
7153 "Toggle the visibility of the current block."
7154 (interactive)
7155 (save-excursion
7156 (beginning-of-line)
7157 (if (re-search-forward org-block-regexp nil t)
7158 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7159 (end (match-end 0)) ;; end of entire body
7161 (if (memq t (mapcar (lambda (overlay)
7162 (eq (overlay-get overlay 'invisible)
7163 'org-hide-block))
7164 (overlays-at start)))
7165 (if (or (not force) (eq force 'off))
7166 (mapc (lambda (ov)
7167 (when (member ov org-hide-block-overlays)
7168 (setq org-hide-block-overlays
7169 (delq ov org-hide-block-overlays)))
7170 (when (eq (overlay-get ov 'invisible)
7171 'org-hide-block)
7172 (delete-overlay ov)))
7173 (overlays-at start)))
7174 (setq ov (make-overlay start end))
7175 (overlay-put ov 'invisible 'org-hide-block)
7176 ;; make the block accessible to isearch
7177 (overlay-put
7178 ov 'isearch-open-invisible
7179 (lambda (ov)
7180 (when (member ov org-hide-block-overlays)
7181 (setq org-hide-block-overlays
7182 (delq ov org-hide-block-overlays)))
7183 (when (eq (overlay-get ov 'invisible)
7184 'org-hide-block)
7185 (delete-overlay ov))))
7186 (push ov org-hide-block-overlays)))
7187 (user-error "Not looking at a source block"))))
7189 ;; org-tab-after-check-for-cycling-hook
7190 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7191 ;; Remove overlays when changing major mode
7192 (add-hook 'org-mode-hook
7193 (lambda () (org-add-hook 'change-major-mode-hook
7194 'org-show-block-all 'append 'local)))
7196 ;;; Org-goto
7198 (defvar org-goto-window-configuration nil)
7199 (defvar org-goto-marker nil)
7200 (defvar org-goto-map)
7201 (defun org-goto-map ()
7202 "Set the keymap `org-goto'."
7203 (setq org-goto-map
7204 (let ((map (make-sparse-keymap)))
7205 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7206 mouse-drag-region universal-argument org-occur))
7207 cmd)
7208 (while (setq cmd (pop cmds))
7209 (substitute-key-definition cmd cmd map global-map)))
7210 (suppress-keymap map)
7211 (org-defkey map "\C-m" 'org-goto-ret)
7212 (org-defkey map [(return)] 'org-goto-ret)
7213 (org-defkey map [(left)] 'org-goto-left)
7214 (org-defkey map [(right)] 'org-goto-right)
7215 (org-defkey map [(control ?g)] 'org-goto-quit)
7216 (org-defkey map "\C-i" 'org-cycle)
7217 (org-defkey map [(tab)] 'org-cycle)
7218 (org-defkey map [(down)] 'outline-next-visible-heading)
7219 (org-defkey map [(up)] 'outline-previous-visible-heading)
7220 (if org-goto-auto-isearch
7221 (if (fboundp 'define-key-after)
7222 (define-key-after map [t] 'org-goto-local-auto-isearch)
7223 nil)
7224 (org-defkey map "q" 'org-goto-quit)
7225 (org-defkey map "n" 'outline-next-visible-heading)
7226 (org-defkey map "p" 'outline-previous-visible-heading)
7227 (org-defkey map "f" 'outline-forward-same-level)
7228 (org-defkey map "b" 'outline-backward-same-level)
7229 (org-defkey map "u" 'outline-up-heading))
7230 (org-defkey map "/" 'org-occur)
7231 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7232 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7233 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7234 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7235 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7236 map)))
7238 (defconst org-goto-help
7239 "Browse buffer copy, to find location or copy text.%s
7240 RET=jump to location C-g=quit and return to previous location
7241 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7243 (defvar org-goto-start-pos) ; dynamically scoped parameter
7245 (defun org-goto (&optional alternative-interface)
7246 "Look up a different location in the current file, keeping current visibility.
7248 When you want look-up or go to a different location in a
7249 document, the fastest way is often to fold the entire buffer and
7250 then dive into the tree. This method has the disadvantage, that
7251 the previous location will be folded, which may not be what you
7252 want.
7254 This command works around this by showing a copy of the current
7255 buffer in an indirect buffer, in overview mode. You can dive
7256 into the tree in that copy, use org-occur and incremental search
7257 to find a location. When pressing RET or `Q', the command
7258 returns to the original buffer in which the visibility is still
7259 unchanged. After RET it will also jump to the location selected
7260 in the indirect buffer and expose the headline hierarchy above.
7262 With a prefix argument, use the alternative interface: e.g. if
7263 `org-goto-interface' is 'outline use 'outline-path-completion."
7264 (interactive "P")
7265 (org-goto-map)
7266 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7267 (org-refile-use-outline-path t)
7268 (org-refile-target-verify-function nil)
7269 (interface
7270 (if (not alternative-interface)
7271 org-goto-interface
7272 (if (eq org-goto-interface 'outline)
7273 'outline-path-completion
7274 'outline)))
7275 (org-goto-start-pos (point))
7276 (selected-point
7277 (if (eq interface 'outline)
7278 (car (org-get-location (current-buffer) org-goto-help))
7279 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7280 (org-refile-check-position pa)
7281 (nth 3 pa)))))
7282 (if selected-point
7283 (progn
7284 (org-mark-ring-push org-goto-start-pos)
7285 (goto-char selected-point)
7286 (if (or (outline-invisible-p) (org-invisible-p2))
7287 (org-show-context 'org-goto)))
7288 (message "Quit"))))
7290 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7291 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7292 (defvar org-goto-local-auto-isearch-map) ; defined below
7294 (defun org-get-location (buf help)
7295 "Let the user select a location in the Org-mode buffer BUF.
7296 This function uses a recursive edit. It returns the selected position
7297 or nil."
7298 (org-no-popups
7299 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7300 (isearch-hide-immediately nil)
7301 (isearch-search-fun-function
7302 (lambda () 'org-goto-local-search-headings))
7303 (org-goto-selected-point org-goto-exit-command))
7304 (save-excursion
7305 (save-window-excursion
7306 (delete-other-windows)
7307 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7308 (org-pop-to-buffer-same-window
7309 (condition-case nil
7310 (make-indirect-buffer (current-buffer) "*org-goto*")
7311 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7312 (with-output-to-temp-buffer "*Org Help*"
7313 (princ (format help (if org-goto-auto-isearch
7314 " Just type for auto-isearch."
7315 " n/p/f/b/u to navigate, q to quit."))))
7316 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7317 (setq buffer-read-only nil)
7318 (let ((org-startup-truncated t)
7319 (org-startup-folded nil)
7320 (org-startup-align-all-tables nil))
7321 (org-mode)
7322 (org-overview))
7323 (setq buffer-read-only t)
7324 (if (and (boundp 'org-goto-start-pos)
7325 (integer-or-marker-p org-goto-start-pos))
7326 (let ((org-show-hierarchy-above t)
7327 (org-show-siblings t)
7328 (org-show-following-heading t))
7329 (goto-char org-goto-start-pos)
7330 (and (outline-invisible-p) (org-show-context)))
7331 (goto-char (point-min)))
7332 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7333 (message "Select location and press RET")
7334 (use-local-map org-goto-map)
7335 (recursive-edit)))
7336 (kill-buffer "*org-goto*")
7337 (cons org-goto-selected-point org-goto-exit-command))))
7339 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7340 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7341 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7342 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7344 (defun org-goto-local-search-headings (string bound noerror)
7345 "Search and make sure that any matches are in headlines."
7346 (catch 'return
7347 (while (if isearch-forward
7348 (search-forward string bound noerror)
7349 (search-backward string bound noerror))
7350 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7351 (and (member :headline context)
7352 (not (member :tags context))))
7353 (throw 'return (point))))))
7355 (defun org-goto-local-auto-isearch ()
7356 "Start isearch."
7357 (interactive)
7358 (goto-char (point-min))
7359 (let ((keys (this-command-keys)))
7360 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7361 (isearch-mode t)
7362 (isearch-process-search-char (string-to-char keys)))))
7364 (defun org-goto-ret (&optional arg)
7365 "Finish `org-goto' by going to the new location."
7366 (interactive "P")
7367 (setq org-goto-selected-point (point)
7368 org-goto-exit-command 'return)
7369 (throw 'exit nil))
7371 (defun org-goto-left ()
7372 "Finish `org-goto' by going to the new location."
7373 (interactive)
7374 (if (org-at-heading-p)
7375 (progn
7376 (beginning-of-line 1)
7377 (setq org-goto-selected-point (point)
7378 org-goto-exit-command 'left)
7379 (throw 'exit nil))
7380 (user-error "Not on a heading")))
7382 (defun org-goto-right ()
7383 "Finish `org-goto' by going to the new location."
7384 (interactive)
7385 (if (org-at-heading-p)
7386 (progn
7387 (setq org-goto-selected-point (point)
7388 org-goto-exit-command 'right)
7389 (throw 'exit nil))
7390 (user-error "Not on a heading")))
7392 (defun org-goto-quit ()
7393 "Finish `org-goto' without cursor motion."
7394 (interactive)
7395 (setq org-goto-selected-point nil)
7396 (setq org-goto-exit-command 'quit)
7397 (throw 'exit nil))
7399 ;;; Indirect buffer display of subtrees
7401 (defvar org-indirect-dedicated-frame nil
7402 "This is the frame being used for indirect tree display.")
7403 (defvar org-last-indirect-buffer nil)
7405 (defun org-tree-to-indirect-buffer (&optional arg)
7406 "Create indirect buffer and narrow it to current subtree.
7407 With a numerical prefix ARG, go up to this level and then take that tree.
7408 If ARG is negative, go up that many levels.
7410 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7411 indirect buffer previously made with this command, to avoid proliferation of
7412 indirect buffers. However, when you call the command with a \
7413 \\[universal-argument] prefix, or
7414 when `org-indirect-buffer-display' is `new-frame', the last buffer
7415 is kept so that you can work with several indirect buffers at the same time.
7416 If `org-indirect-buffer-display' is `dedicated-frame', the \
7417 \\[universal-argument] prefix also
7418 requests that a new frame be made for the new buffer, so that the dedicated
7419 frame is not changed."
7420 (interactive "P")
7421 (let ((cbuf (current-buffer))
7422 (cwin (selected-window))
7423 (pos (point))
7424 beg end level heading ibuf)
7425 (save-excursion
7426 (org-back-to-heading t)
7427 (when (numberp arg)
7428 (setq level (org-outline-level))
7429 (if (< arg 0) (setq arg (+ level arg)))
7430 (while (> (setq level (org-outline-level)) arg)
7431 (org-up-heading-safe)))
7432 (setq beg (point)
7433 heading (org-get-heading))
7434 (org-end-of-subtree t t)
7435 (if (org-at-heading-p) (backward-char 1))
7436 (setq end (point)))
7437 (if (and (buffer-live-p org-last-indirect-buffer)
7438 (not (eq org-indirect-buffer-display 'new-frame))
7439 (not arg))
7440 (kill-buffer org-last-indirect-buffer))
7441 (setq ibuf (org-get-indirect-buffer cbuf)
7442 org-last-indirect-buffer ibuf)
7443 (cond
7444 ((or (eq org-indirect-buffer-display 'new-frame)
7445 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7446 (select-frame (make-frame))
7447 (delete-other-windows)
7448 (org-pop-to-buffer-same-window ibuf)
7449 (org-set-frame-title heading))
7450 ((eq org-indirect-buffer-display 'dedicated-frame)
7451 (raise-frame
7452 (select-frame (or (and org-indirect-dedicated-frame
7453 (frame-live-p org-indirect-dedicated-frame)
7454 org-indirect-dedicated-frame)
7455 (setq org-indirect-dedicated-frame (make-frame)))))
7456 (delete-other-windows)
7457 (org-pop-to-buffer-same-window ibuf)
7458 (org-set-frame-title (concat "Indirect: " heading)))
7459 ((eq org-indirect-buffer-display 'current-window)
7460 (org-pop-to-buffer-same-window ibuf))
7461 ((eq org-indirect-buffer-display 'other-window)
7462 (pop-to-buffer ibuf))
7463 (t (error "Invalid value")))
7464 (if (featurep 'xemacs)
7465 (save-excursion (org-mode) (turn-on-font-lock)))
7466 (narrow-to-region beg end)
7467 (show-all)
7468 (goto-char pos)
7469 (run-hook-with-args 'org-cycle-hook 'all)
7470 (and (window-live-p cwin) (select-window cwin))))
7472 (defun org-get-indirect-buffer (&optional buffer)
7473 (setq buffer (or buffer (current-buffer)))
7474 (let ((n 1) (base (buffer-name buffer)) bname)
7475 (while (buffer-live-p
7476 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7477 (setq n (1+ n)))
7478 (condition-case nil
7479 (make-indirect-buffer buffer bname 'clone)
7480 (error (make-indirect-buffer buffer bname)))))
7482 (defun org-set-frame-title (title)
7483 "Set the title of the current frame to the string TITLE."
7484 ;; FIXME: how to name a single frame in XEmacs???
7485 (unless (featurep 'xemacs)
7486 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7488 ;;;; Structure editing
7490 ;;; Inserting headlines
7492 (defun org-previous-line-empty-p (&optional next)
7493 "Is the previous line a blank line?
7494 When NEXT is non-nil, check the next line instead."
7495 (save-excursion
7496 (and (not (bobp))
7497 (or (beginning-of-line (if next 2 0)) t)
7498 (save-match-data
7499 (looking-at "[ \t]*$")))))
7501 (defun org-insert-heading (&optional arg invisible-ok)
7502 "Insert a new heading or item with same depth at point.
7503 If point is in a plain list and ARG is nil, create a new list item.
7504 With one universal prefix argument, insert a heading even in lists.
7505 With two universal prefix arguments, insert the heading at the end
7506 of the parent subtree.
7508 If point is at the beginning of a headline, insert a sibling before
7509 the current headline. If point is not at the beginning, split the line
7510 and create a new headline with the text in the current line after point
7511 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7513 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7514 This is important for non-interactive uses of the command."
7515 (interactive "P")
7516 (if (org-called-interactively-p 'any) (org-reveal))
7517 (let ((itemp (org-in-item-p)))
7518 (cond
7519 ((or (= (buffer-size) 0)
7520 (and (not (save-excursion
7521 (and (ignore-errors (org-back-to-heading invisible-ok))
7522 (org-at-heading-p))))
7523 (or arg (not itemp))))
7524 (insert
7525 (if (org-previous-line-empty-p) "" "\n")
7526 (if (org-in-src-block-p) ",* " "* "))
7527 (run-hooks 'org-insert-heading-hook))
7528 ((or arg
7529 (and (not itemp) org-insert-heading-respect-content)
7530 (not (org-insert-item
7531 (save-excursion
7532 (and itemp
7533 (goto-char itemp)
7534 (looking-at org-list-full-item-re)
7535 (match-string 3))))))
7536 (let (begn endn)
7537 (when (org-buffer-narrowed-p)
7538 (setq begn (point-min) endn (point-max))
7539 (widen))
7540 (let* ((empty-line-p nil)
7541 (eops (equal arg '(16))) ; insert at end of parent subtree
7542 (org-insert-heading-respect-content
7543 (or (not (null arg)) org-insert-heading-respect-content))
7544 (level nil)
7545 (on-heading (org-at-heading-p))
7546 ;; Get a level to fall back on
7547 (fix-level
7548 (save-excursion
7549 (org-back-to-heading t)
7550 (looking-at org-outline-regexp)
7551 (make-string (1- (length (match-string 0))) ?*)))
7552 (on-empty-line
7553 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7554 (head (save-excursion
7555 (condition-case nil
7556 (progn
7557 (org-back-to-heading invisible-ok)
7558 (when (and (not on-heading)
7559 (featurep 'org-inlinetask)
7560 (integerp org-inlinetask-min-level)
7561 (>= (length (match-string 0))
7562 org-inlinetask-min-level))
7563 ;; Find a heading level before the inline task
7564 (while (and (setq level (org-up-heading-safe))
7565 (>= level org-inlinetask-min-level)))
7566 (if (org-at-heading-p)
7567 (org-back-to-heading invisible-ok)
7568 (error "This should not happen")))
7569 (unless (and (save-excursion
7570 (save-match-data
7571 (org-backward-heading-same-level 1 invisible-ok))
7572 (= (point) (match-beginning 0)))
7573 (not (org-previous-line-empty-p t)))
7574 (setq empty-line-p (org-previous-line-empty-p)))
7575 (match-string 0))
7576 (error (or fix-level "* ")))))
7577 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7578 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7579 pos hide-previous previous-pos)
7580 (if ;; At the beginning of a heading, open a new line for insertion
7581 (and (bolp) (org-at-heading-p)
7582 (not eops)
7583 (or (bobp)
7584 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7585 (open-line (if blank 2 1))
7586 (save-excursion
7587 (setq previous-pos (point-at-bol))
7588 (end-of-line)
7589 (setq hide-previous (outline-invisible-p)))
7590 (and org-insert-heading-respect-content
7591 (save-excursion
7592 (while (outline-invisible-p)
7593 (org-show-subtree)
7594 (org-up-heading-safe))))
7595 (let ((split
7596 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7597 (save-excursion
7598 (let ((p (point)))
7599 (goto-char (point-at-bol))
7600 (and (looking-at org-complex-heading-regexp)
7601 (match-beginning 4)
7602 (> p (match-beginning 4)))))))
7603 tags pos)
7604 (cond
7605 ;; Insert a new line, possibly at end of parent subtree
7606 ((and (not arg) (not on-heading) (not on-empty-line)
7607 (not (save-excursion
7608 (beginning-of-line 1)
7609 (or (looking-at org-list-full-item-re)
7610 ;; Don't convert :end: lines to headline
7611 (looking-at "^\\s-*:end:")
7612 (looking-at "^\\s-*#\\+end_?")))))
7613 (beginning-of-line 1))
7614 (org-insert-heading-respect-content
7615 (if (not eops)
7616 (progn
7617 (org-end-of-subtree nil t)
7618 (and (looking-at "^\\*") (backward-char 1))
7619 (while (and (not (bobp))
7620 ;; Don't delete spaces in empty headlines
7621 (not (looking-back org-outline-regexp))
7622 (member (char-before) '(?\ ?\t ?\n)))
7623 (backward-delete-char 1)))
7624 (let ((p (point)))
7625 (org-up-heading-safe)
7626 (if (= p (point))
7627 (goto-char (point-max))
7628 (org-end-of-subtree nil t))))
7629 (when (featurep 'org-inlinetask)
7630 (while (and (not (eobp))
7631 (looking-at "\\(\\*+\\)[ \t]+")
7632 (>= (length (match-string 1))
7633 org-inlinetask-min-level))
7634 (org-end-of-subtree nil t)))
7635 (or (bolp) (newline))
7636 (or (org-previous-line-empty-p)
7637 (and blank (newline)))
7638 (if (or empty-line-p eops) (open-line 1)))
7639 ;; Insert a headling containing text after point
7640 ((org-at-heading-p)
7641 (when hide-previous
7642 (show-children)
7643 (org-show-entry))
7644 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7645 (setq tags (and (match-end 2) (match-string 2)))
7646 (and (match-end 1)
7647 (delete-region (match-beginning 1) (match-end 1)))
7648 (setq pos (point-at-bol))
7649 (or split (end-of-line 1))
7650 (delete-horizontal-space)
7651 (if (string-match "\\`\\*+\\'"
7652 (buffer-substring (point-at-bol) (point)))
7653 (insert " "))
7654 (newline (if blank 2 1))
7655 (when tags
7656 (save-excursion
7657 (goto-char pos)
7658 (end-of-line 1)
7659 (insert " " tags)
7660 (org-set-tags nil 'align))))
7662 (or split (end-of-line 1))
7663 (newline (cond ((and blank (not on-empty-line)) 2)
7664 (blank 1)
7665 (on-empty-line 0) (t 1)))))))
7666 (insert head) (just-one-space)
7667 (setq pos (point))
7668 (end-of-line 1)
7669 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7670 (when (and org-insert-heading-respect-content hide-previous)
7671 (save-excursion
7672 (goto-char previous-pos)
7673 (hide-subtree)))
7674 (when (and begn endn)
7675 (narrow-to-region (min (point) begn) (max (point) endn)))
7676 (run-hooks 'org-insert-heading-hook)))))))
7678 (defun org-get-heading (&optional no-tags no-todo)
7679 "Return the heading of the current entry, without the stars.
7680 When NO-TAGS is non-nil, don't include tags.
7681 When NO-TODO is non-nil, don't include TODO keywords."
7682 (save-excursion
7683 (org-back-to-heading t)
7684 (cond
7685 ((and no-tags no-todo)
7686 (looking-at org-complex-heading-regexp)
7687 (match-string 4))
7688 (no-tags
7689 (looking-at (concat org-outline-regexp
7690 "\\(.*?\\)"
7691 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7692 (match-string 1))
7693 (no-todo
7694 (looking-at org-todo-line-regexp)
7695 (match-string 3))
7696 (t (looking-at org-heading-regexp)
7697 (match-string 2)))))
7699 (defvar orgstruct-mode) ; defined below
7701 (defun org-heading-components ()
7702 "Return the components of the current heading.
7703 This is a list with the following elements:
7704 - the level as an integer
7705 - the reduced level, different if `org-odd-levels-only' is set.
7706 - the TODO keyword, or nil
7707 - the priority character, like ?A, or nil if no priority is given
7708 - the headline text itself, or the tags string if no headline text
7709 - the tags string, or nil."
7710 (save-excursion
7711 (org-back-to-heading t)
7712 (if (let (case-fold-search)
7713 (looking-at
7714 (if orgstruct-mode
7715 org-heading-regexp
7716 org-complex-heading-regexp)))
7717 (if orgstruct-mode
7718 (list (length (match-string 1))
7719 (org-reduced-level (length (match-string 1)))
7722 (match-string 2)
7723 nil)
7724 (list (length (match-string 1))
7725 (org-reduced-level (length (match-string 1)))
7726 (org-match-string-no-properties 2)
7727 (and (match-end 3) (aref (match-string 3) 2))
7728 (org-match-string-no-properties 4)
7729 (org-match-string-no-properties 5))))))
7731 (defun org-get-entry ()
7732 "Get the entry text, after heading, entire subtree."
7733 (save-excursion
7734 (org-back-to-heading t)
7735 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7737 (defun org-insert-heading-after-current ()
7738 "Insert a new heading with same level as current, after current subtree."
7739 (interactive)
7740 (org-back-to-heading)
7741 (org-insert-heading)
7742 (org-move-subtree-down)
7743 (end-of-line 1))
7745 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7746 "Insert heading with `org-insert-heading-respect-content' set to t."
7747 (interactive "P")
7748 (let ((org-insert-heading-respect-content t))
7749 (org-insert-heading arg invisible-ok)))
7751 (defun org-insert-todo-heading-respect-content (&optional force-state)
7752 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7753 (interactive "P")
7754 (let ((org-insert-heading-respect-content t))
7755 (org-insert-todo-heading force-state t)))
7757 (defun org-insert-todo-heading (arg &optional force-heading)
7758 "Insert a new heading with the same level and TODO state as current heading.
7759 If the heading has no TODO state, or if the state is DONE, use the first
7760 state (TODO by default). Also one prefix arg, force first state. With two
7761 prefix args, force inserting at the end of the parent subtree."
7762 (interactive "P")
7763 (when (or force-heading (not (org-insert-item 'checkbox)))
7764 (org-insert-heading (or (and (equal arg '(16)) '(16))
7765 force-heading))
7766 (save-excursion
7767 (org-back-to-heading)
7768 (outline-previous-heading)
7769 (looking-at org-todo-line-regexp))
7770 (let*
7771 ((new-mark-x
7772 (if (or arg
7773 (not (match-beginning 2))
7774 (member (match-string 2) org-done-keywords))
7775 (car org-todo-keywords-1)
7776 (match-string 2)))
7777 (new-mark
7779 (run-hook-with-args-until-success
7780 'org-todo-get-default-hook new-mark-x nil)
7781 new-mark-x)))
7782 (beginning-of-line 1)
7783 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7784 (if org-treat-insert-todo-heading-as-state-change
7785 (org-todo new-mark)
7786 (insert new-mark " "))))
7787 (when org-provide-todo-statistics
7788 (org-update-parent-todo-statistics))))
7790 (defun org-insert-subheading (arg)
7791 "Insert a new subheading and demote it.
7792 Works for outline headings and for plain lists alike."
7793 (interactive "P")
7794 (org-insert-heading arg)
7795 (cond
7796 ((org-at-heading-p) (org-do-demote))
7797 ((org-at-item-p) (org-indent-item))))
7799 (defun org-insert-todo-subheading (arg)
7800 "Insert a new subheading with TODO keyword or checkbox and demote it.
7801 Works for outline headings and for plain lists alike."
7802 (interactive "P")
7803 (org-insert-todo-heading arg)
7804 (cond
7805 ((org-at-heading-p) (org-do-demote))
7806 ((org-at-item-p) (org-indent-item))))
7808 ;;; Promotion and Demotion
7810 (defvar org-after-demote-entry-hook nil
7811 "Hook run after an entry has been demoted.
7812 The cursor will be at the beginning of the entry.
7813 When a subtree is being demoted, the hook will be called for each node.")
7815 (defvar org-after-promote-entry-hook nil
7816 "Hook run after an entry has been promoted.
7817 The cursor will be at the beginning of the entry.
7818 When a subtree is being promoted, the hook will be called for each node.")
7820 (defun org-promote-subtree ()
7821 "Promote the entire subtree.
7822 See also `org-promote'."
7823 (interactive)
7824 (save-excursion
7825 (org-with-limited-levels (org-map-tree 'org-promote)))
7826 (org-fix-position-after-promote))
7828 (defun org-demote-subtree ()
7829 "Demote the entire subtree. See `org-demote'.
7830 See also `org-promote'."
7831 (interactive)
7832 (save-excursion
7833 (org-with-limited-levels (org-map-tree 'org-demote)))
7834 (org-fix-position-after-promote))
7837 (defun org-do-promote ()
7838 "Promote the current heading higher up the tree.
7839 If the region is active in `transient-mark-mode', promote all headings
7840 in the region."
7841 (interactive)
7842 (save-excursion
7843 (if (org-region-active-p)
7844 (org-map-region 'org-promote (region-beginning) (region-end))
7845 (org-promote)))
7846 (org-fix-position-after-promote))
7848 (defun org-do-demote ()
7849 "Demote the current heading lower down the tree.
7850 If the region is active in `transient-mark-mode', demote all headings
7851 in the region."
7852 (interactive)
7853 (save-excursion
7854 (if (org-region-active-p)
7855 (org-map-region 'org-demote (region-beginning) (region-end))
7856 (org-demote)))
7857 (org-fix-position-after-promote))
7859 (defun org-fix-position-after-promote ()
7860 "Make sure that after pro/demotion cursor position is right."
7861 (let ((pos (point)))
7862 (when (save-excursion
7863 (beginning-of-line 1)
7864 (looking-at org-todo-line-regexp)
7865 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7866 (cond ((eobp) (insert " "))
7867 ((eolp) (insert " "))
7868 ((equal (char-after) ?\ ) (forward-char 1))))))
7870 (defun org-current-level ()
7871 "Return the level of the current entry, or nil if before the first headline.
7872 The level is the number of stars at the beginning of the headline."
7873 (save-excursion
7874 (org-with-limited-levels
7875 (if (ignore-errors (org-back-to-heading t))
7876 (funcall outline-level)))))
7878 (defun org-get-previous-line-level ()
7879 "Return the outline depth of the last headline before the current line.
7880 Returns 0 for the first headline in the buffer, and nil if before the
7881 first headline."
7882 (let ((current-level (org-current-level))
7883 (prev-level (when (> (line-number-at-pos) 1)
7884 (save-excursion
7885 (beginning-of-line 0)
7886 (org-current-level)))))
7887 (cond ((null current-level) nil) ; Before first headline
7888 ((null prev-level) 0) ; At first headline
7889 (prev-level))))
7891 (defun org-reduced-level (l)
7892 "Compute the effective level of a heading.
7893 This takes into account the setting of `org-odd-levels-only'."
7894 (cond
7895 ((zerop l) 0)
7896 (org-odd-levels-only (1+ (floor (/ l 2))))
7897 (t l)))
7899 (defun org-level-increment ()
7900 "Return the number of stars that will be added or removed at a
7901 time to headlines when structure editing, based on the value of
7902 `org-odd-levels-only'."
7903 (if org-odd-levels-only 2 1))
7905 (defun org-get-valid-level (level &optional change)
7906 "Rectify a level change under the influence of `org-odd-levels-only'
7907 LEVEL is a current level, CHANGE is by how much the level should be
7908 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7909 even level numbers will become the next higher odd number."
7910 (if org-odd-levels-only
7911 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7912 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7913 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7914 (max 1 (+ level (or change 0)))))
7916 (if (boundp 'define-obsolete-function-alias)
7917 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7918 (define-obsolete-function-alias 'org-get-legal-level
7919 'org-get-valid-level)
7920 (define-obsolete-function-alias 'org-get-legal-level
7921 'org-get-valid-level "23.1")))
7923 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7924 ;; ̀org-with-limited-levels'
7925 (defun org-promote ()
7926 "Promote the current heading higher up the tree.
7927 If the region is active in `transient-mark-mode', promote all headings
7928 in the region."
7929 (org-back-to-heading t)
7930 (let* ((level (save-match-data (funcall outline-level)))
7931 (after-change-functions (remove 'flyspell-after-change-function
7932 after-change-functions))
7933 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7934 (diff (abs (- level (length up-head) -1))))
7935 (cond ((and (= level 1) org-called-with-limited-levels
7936 org-allow-promoting-top-level-subtree)
7937 (replace-match "# " nil t))
7938 ((= level 1)
7939 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7940 (t (replace-match up-head nil t)))
7941 ;; Fixup tag positioning
7942 (unless (= level 1)
7943 (and org-auto-align-tags (org-set-tags nil t))
7944 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7945 (run-hooks 'org-after-promote-entry-hook)))
7947 (defun org-demote ()
7948 "Demote the current heading lower down the tree.
7949 If the region is active in `transient-mark-mode', demote all headings
7950 in the region."
7951 (org-back-to-heading t)
7952 (let* ((level (save-match-data (funcall outline-level)))
7953 (after-change-functions (remove 'flyspell-after-change-function
7954 after-change-functions))
7955 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7956 (diff (abs (- level (length down-head) -1))))
7957 (replace-match down-head nil t)
7958 ;; Fixup tag positioning
7959 (and org-auto-align-tags (org-set-tags nil t))
7960 (if org-adapt-indentation (org-fixup-indentation diff))
7961 (run-hooks 'org-after-demote-entry-hook)))
7963 (defun org-cycle-level ()
7964 "Cycle the level of an empty headline through possible states.
7965 This goes first to child, then to parent, level, then up the hierarchy.
7966 After top level, it switches back to sibling level."
7967 (interactive)
7968 (let ((org-adapt-indentation nil))
7969 (when (org-point-at-end-of-empty-headline)
7970 (setq this-command 'org-cycle-level) ; Only needed for caching
7971 (let ((cur-level (org-current-level))
7972 (prev-level (org-get-previous-line-level)))
7973 (cond
7974 ;; If first headline in file, promote to top-level.
7975 ((= prev-level 0)
7976 (loop repeat (/ (- cur-level 1) (org-level-increment))
7977 do (org-do-promote)))
7978 ;; If same level as prev, demote one.
7979 ((= prev-level cur-level)
7980 (org-do-demote))
7981 ;; If parent is top-level, promote to top level if not already.
7982 ((= prev-level 1)
7983 (loop repeat (/ (- cur-level 1) (org-level-increment))
7984 do (org-do-promote)))
7985 ;; If top-level, return to prev-level.
7986 ((= cur-level 1)
7987 (loop repeat (/ (- prev-level 1) (org-level-increment))
7988 do (org-do-demote)))
7989 ;; If less than prev-level, promote one.
7990 ((< cur-level prev-level)
7991 (org-do-promote))
7992 ;; If deeper than prev-level, promote until higher than
7993 ;; prev-level.
7994 ((> cur-level prev-level)
7995 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7996 do (org-do-promote))))
7997 t))))
7999 (defun org-map-tree (fun)
8000 "Call FUN for every heading underneath the current one."
8001 (org-back-to-heading)
8002 (let ((level (funcall outline-level)))
8003 (save-excursion
8004 (funcall fun)
8005 (while (and (progn
8006 (outline-next-heading)
8007 (> (funcall outline-level) level))
8008 (not (eobp)))
8009 (funcall fun)))))
8011 (defun org-map-region (fun beg end)
8012 "Call FUN for every heading between BEG and END."
8013 (let ((org-ignore-region t))
8014 (save-excursion
8015 (setq end (copy-marker end))
8016 (goto-char beg)
8017 (if (and (re-search-forward org-outline-regexp-bol nil t)
8018 (< (point) end))
8019 (funcall fun))
8020 (while (and (progn
8021 (outline-next-heading)
8022 (< (point) end))
8023 (not (eobp)))
8024 (funcall fun)))))
8026 (defvar org-property-end-re) ; silence byte-compiler
8027 (defun org-fixup-indentation (diff)
8028 "Change the indentation in the current entry by DIFF.
8029 However, if any line in the current entry has no indentation, or if it
8030 would end up with no indentation after the change, nothing at all is done."
8031 (save-excursion
8032 (let ((end (save-excursion (outline-next-heading)
8033 (point-marker)))
8034 (prohibit (if (> diff 0)
8035 "^\\S-"
8036 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8037 col)
8038 (unless (save-excursion (end-of-line 1)
8039 (re-search-forward prohibit end t))
8040 (while (and (< (point) end)
8041 (re-search-forward "^[ \t]+" end t))
8042 (goto-char (match-end 0))
8043 (setq col (current-column))
8044 (if (< diff 0) (replace-match ""))
8045 (org-indent-to-column (+ diff col))))
8046 (move-marker end nil))))
8048 (defun org-convert-to-odd-levels ()
8049 "Convert an org-mode file with all levels allowed to one with odd levels.
8050 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8051 level 5 etc."
8052 (interactive)
8053 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8054 (let ((outline-level 'org-outline-level)
8055 (org-odd-levels-only nil) n)
8056 (save-excursion
8057 (goto-char (point-min))
8058 (while (re-search-forward "^\\*\\*+ " nil t)
8059 (setq n (- (length (match-string 0)) 2))
8060 (while (>= (setq n (1- n)) 0)
8061 (org-demote))
8062 (end-of-line 1))))))
8064 (defun org-convert-to-oddeven-levels ()
8065 "Convert an org-mode file with only odd levels to one with odd/even levels.
8066 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8067 file contains a section with an even level, conversion would
8068 destroy the structure of the file. An error is signaled in this
8069 case."
8070 (interactive)
8071 (goto-char (point-min))
8072 ;; First check if there are no even levels
8073 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8074 (org-show-context t)
8075 (error "Not all levels are odd in this file. Conversion not possible"))
8076 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8077 (let ((outline-regexp org-outline-regexp)
8078 (outline-level 'org-outline-level)
8079 (org-odd-levels-only nil) n)
8080 (save-excursion
8081 (goto-char (point-min))
8082 (while (re-search-forward "^\\*\\*+ " nil t)
8083 (setq n (/ (1- (length (match-string 0))) 2))
8084 (while (>= (setq n (1- n)) 0)
8085 (org-promote))
8086 (end-of-line 1))))))
8088 (defun org-tr-level (n)
8089 "Make N odd if required."
8090 (if org-odd-levels-only (1+ (/ n 2)) n))
8092 ;;; Vertical tree motion, cutting and pasting of subtrees
8094 (defun org-move-subtree-up (&optional arg)
8095 "Move the current subtree up past ARG headlines of the same level."
8096 (interactive "p")
8097 (org-move-subtree-down (- (prefix-numeric-value arg))))
8099 (defun org-move-subtree-down (&optional arg)
8100 "Move the current subtree down past ARG headlines of the same level."
8101 (interactive "p")
8102 (setq arg (prefix-numeric-value arg))
8103 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8104 'org-get-last-sibling))
8105 (ins-point (make-marker))
8106 (cnt (abs arg))
8107 (col (current-column))
8108 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8109 ;; Select the tree
8110 (org-back-to-heading)
8111 (setq beg0 (point))
8112 (save-excursion
8113 (setq ne-beg (org-back-over-empty-lines))
8114 (setq beg (point)))
8115 (save-match-data
8116 (save-excursion (outline-end-of-heading)
8117 (setq folded (outline-invisible-p)))
8118 (outline-end-of-subtree))
8119 (outline-next-heading)
8120 (setq ne-end (org-back-over-empty-lines))
8121 (setq end (point))
8122 (goto-char beg0)
8123 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8124 ;; include less whitespace
8125 (save-excursion
8126 (goto-char beg)
8127 (forward-line (- ne-beg ne-end))
8128 (setq beg (point))))
8129 ;; Find insertion point, with error handling
8130 (while (> cnt 0)
8131 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8132 (progn (goto-char beg0)
8133 (user-error "Cannot move past superior level or buffer limit")))
8134 (setq cnt (1- cnt)))
8135 (if (> arg 0)
8136 ;; Moving forward - still need to move over subtree
8137 (progn (org-end-of-subtree t t)
8138 (save-excursion
8139 (org-back-over-empty-lines)
8140 (or (bolp) (newline)))))
8141 (setq ne-ins (org-back-over-empty-lines))
8142 (move-marker ins-point (point))
8143 (setq txt (buffer-substring beg end))
8144 (org-save-markers-in-region beg end)
8145 (delete-region beg end)
8146 (org-remove-empty-overlays-at beg)
8147 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8148 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8149 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8150 (let ((bbb (point)))
8151 (insert-before-markers txt)
8152 (org-reinstall-markers-in-region bbb)
8153 (move-marker ins-point bbb))
8154 (or (bolp) (insert "\n"))
8155 (setq ins-end (point))
8156 (goto-char ins-point)
8157 (org-skip-whitespace)
8158 (when (and (< arg 0)
8159 (org-first-sibling-p)
8160 (> ne-ins ne-beg))
8161 ;; Move whitespace back to beginning
8162 (save-excursion
8163 (goto-char ins-end)
8164 (let ((kill-whole-line t))
8165 (kill-line (- ne-ins ne-beg)) (point)))
8166 (insert (make-string (- ne-ins ne-beg) ?\n)))
8167 (move-marker ins-point nil)
8168 (if folded
8169 (hide-subtree)
8170 (org-show-entry)
8171 (show-children)
8172 (org-cycle-hide-drawers 'children))
8173 (org-clean-visibility-after-subtree-move)
8174 ;; move back to the initial column we were at
8175 (move-to-column col)))
8177 (defvar org-subtree-clip ""
8178 "Clipboard for cut and paste of subtrees.
8179 This is actually only a copy of the kill, because we use the normal kill
8180 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8182 (defvar org-subtree-clip-folded nil
8183 "Was the last copied subtree folded?
8184 This is used to fold the tree back after pasting.")
8186 (defun org-cut-subtree (&optional n)
8187 "Cut the current subtree into the clipboard.
8188 With prefix arg N, cut this many sequential subtrees.
8189 This is a short-hand for marking the subtree and then cutting it."
8190 (interactive "p")
8191 (org-copy-subtree n 'cut))
8193 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8194 "Cut the current subtree into the clipboard.
8195 With prefix arg N, cut this many sequential subtrees.
8196 This is a short-hand for marking the subtree and then copying it.
8197 If CUT is non-nil, actually cut the subtree.
8198 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8199 of some markers in the region, even if CUT is non-nil. This is
8200 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8201 (interactive "p")
8202 (let (beg end folded (beg0 (point)))
8203 (if (org-called-interactively-p 'any)
8204 (org-back-to-heading nil) ; take what looks like a subtree
8205 (org-back-to-heading t)) ; take what is really there
8206 (setq beg (point))
8207 (skip-chars-forward " \t\r\n")
8208 (save-match-data
8209 (if nosubtrees
8210 (outline-next-heading)
8211 (save-excursion (outline-end-of-heading)
8212 (setq folded (outline-invisible-p)))
8213 (condition-case nil
8214 (org-forward-heading-same-level (1- n) t)
8215 (error nil))
8216 (org-end-of-subtree t t)))
8217 (setq end (point))
8218 (goto-char beg0)
8219 (when (> end beg)
8220 (setq org-subtree-clip-folded folded)
8221 (when (or cut force-store-markers)
8222 (org-save-markers-in-region beg end))
8223 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8224 (setq org-subtree-clip (current-kill 0))
8225 (message "%s: Subtree(s) with %d characters"
8226 (if cut "Cut" "Copied")
8227 (length org-subtree-clip)))))
8229 (defun org-paste-subtree (&optional level tree for-yank)
8230 "Paste the clipboard as a subtree, with modification of headline level.
8231 The entire subtree is promoted or demoted in order to match a new headline
8232 level.
8234 If the cursor is at the beginning of a headline, the same level as
8235 that headline is used to paste the tree.
8237 If not, the new level is derived from the *visible* headings
8238 before and after the insertion point, and taken to be the inferior headline
8239 level of the two. So if the previous visible heading is level 3 and the
8240 next is level 4 (or vice versa), level 4 will be used for insertion.
8241 This makes sure that the subtree remains an independent subtree and does
8242 not swallow low level entries.
8244 You can also force a different level, either by using a numeric prefix
8245 argument, or by inserting the heading marker by hand. For example, if the
8246 cursor is after \"*****\", then the tree will be shifted to level 5.
8248 If optional TREE is given, use this text instead of the kill ring.
8250 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8251 move back over whitespace before inserting, and move point to the end of
8252 the inserted text when done."
8253 (interactive "P")
8254 (setq tree (or tree (and kill-ring (current-kill 0))))
8255 (unless (org-kill-is-subtree-p tree)
8256 (user-error "%s"
8257 (substitute-command-keys
8258 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8259 (org-with-limited-levels
8260 (let* ((visp (not (outline-invisible-p)))
8261 (txt tree)
8262 (^re_ "\\(\\*+\\)[ \t]*")
8263 (old-level (if (string-match org-outline-regexp-bol txt)
8264 (- (match-end 0) (match-beginning 0) 1)
8265 -1))
8266 (force-level (cond (level (prefix-numeric-value level))
8267 ((and (looking-at "[ \t]*$")
8268 (string-match
8269 "^\\*+$" (buffer-substring
8270 (point-at-bol) (point))))
8271 (- (match-end 1) (match-beginning 1)))
8272 ((and (bolp)
8273 (looking-at org-outline-regexp))
8274 (- (match-end 0) (point) 1))))
8275 (previous-level (save-excursion
8276 (condition-case nil
8277 (progn
8278 (outline-previous-visible-heading 1)
8279 (if (looking-at ^re_)
8280 (- (match-end 0) (match-beginning 0) 1)
8282 (error 1))))
8283 (next-level (save-excursion
8284 (condition-case nil
8285 (progn
8286 (or (looking-at org-outline-regexp)
8287 (outline-next-visible-heading 1))
8288 (if (looking-at ^re_)
8289 (- (match-end 0) (match-beginning 0) 1)
8291 (error 1))))
8292 (new-level (or force-level (max previous-level next-level)))
8293 (shift (if (or (= old-level -1)
8294 (= new-level -1)
8295 (= old-level new-level))
8297 (- new-level old-level)))
8298 (delta (if (> shift 0) -1 1))
8299 (func (if (> shift 0) 'org-demote 'org-promote))
8300 (org-odd-levels-only nil)
8301 beg end newend)
8302 ;; Remove the forced level indicator
8303 (if force-level
8304 (delete-region (point-at-bol) (point)))
8305 ;; Paste
8306 (beginning-of-line (if (bolp) 1 2))
8307 (setq beg (point))
8308 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8309 (insert-before-markers txt)
8310 (unless (string-match "\n\\'" txt) (insert "\n"))
8311 (setq newend (point))
8312 (org-reinstall-markers-in-region beg)
8313 (setq end (point))
8314 (goto-char beg)
8315 (skip-chars-forward " \t\n\r")
8316 (setq beg (point))
8317 (if (and (outline-invisible-p) visp)
8318 (save-excursion (outline-show-heading)))
8319 ;; Shift if necessary
8320 (unless (= shift 0)
8321 (save-restriction
8322 (narrow-to-region beg end)
8323 (while (not (= shift 0))
8324 (org-map-region func (point-min) (point-max))
8325 (setq shift (+ delta shift)))
8326 (goto-char (point-min))
8327 (setq newend (point-max))))
8328 (when (or (org-called-interactively-p 'interactive) for-yank)
8329 (message "Clipboard pasted as level %d subtree" new-level))
8330 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8331 kill-ring
8332 (eq org-subtree-clip (current-kill 0))
8333 org-subtree-clip-folded)
8334 ;; The tree was folded before it was killed/copied
8335 (hide-subtree))
8336 (and for-yank (goto-char newend)))))
8338 (defun org-kill-is-subtree-p (&optional txt)
8339 "Check if the current kill is an outline subtree, or a set of trees.
8340 Returns nil if kill does not start with a headline, or if the first
8341 headline level is not the largest headline level in the tree.
8342 So this will actually accept several entries of equal levels as well,
8343 which is OK for `org-paste-subtree'.
8344 If optional TXT is given, check this string instead of the current kill."
8345 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8346 (re (org-get-limited-outline-regexp))
8347 (^re (concat "^" re))
8348 (start-level (and kill
8349 (string-match
8350 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8351 kill)
8352 (- (match-end 2) (match-beginning 2) 1)))
8353 (start (1+ (or (match-beginning 2) -1))))
8354 (if (not start-level)
8355 (progn
8356 nil) ;; does not even start with a heading
8357 (catch 'exit
8358 (while (setq start (string-match ^re kill (1+ start)))
8359 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8360 (throw 'exit nil)))
8361 t))))
8363 (defvar org-markers-to-move nil
8364 "Markers that should be moved with a cut-and-paste operation.
8365 Those markers are stored together with their positions relative to
8366 the start of the region.")
8368 (defun org-save-markers-in-region (beg end)
8369 "Check markers in region.
8370 If these markers are between BEG and END, record their position relative
8371 to BEG, so that after moving the block of text, we can put the markers back
8372 into place.
8373 This function gets called just before an entry or tree gets cut from the
8374 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8375 called immediately, to move the markers with the entries."
8376 (setq org-markers-to-move nil)
8377 (when (featurep 'org-clock)
8378 (org-clock-save-markers-for-cut-and-paste beg end))
8379 (when (featurep 'org-agenda)
8380 (org-agenda-save-markers-for-cut-and-paste beg end)))
8382 (defun org-check-and-save-marker (marker beg end)
8383 "Check if MARKER is between BEG and END.
8384 If yes, remember the marker and the distance to BEG."
8385 (when (and (marker-buffer marker)
8386 (equal (marker-buffer marker) (current-buffer)))
8387 (if (and (>= marker beg) (< marker end))
8388 (push (cons marker (- marker beg)) org-markers-to-move))))
8390 (defun org-reinstall-markers-in-region (beg)
8391 "Move all remembered markers to their position relative to BEG."
8392 (mapc (lambda (x)
8393 (move-marker (car x) (+ beg (cdr x))))
8394 org-markers-to-move)
8395 (setq org-markers-to-move nil))
8397 (defun org-narrow-to-subtree ()
8398 "Narrow buffer to the current subtree."
8399 (interactive)
8400 (save-excursion
8401 (save-match-data
8402 (org-with-limited-levels
8403 (narrow-to-region
8404 (progn (org-back-to-heading t) (point))
8405 (progn (org-end-of-subtree t t)
8406 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8407 (point)))))))
8409 (defun org-narrow-to-block ()
8410 "Narrow buffer to the current block."
8411 (interactive)
8412 (let* ((case-fold-search t)
8413 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8414 "^[ \t]*#\\+end_.*")))
8415 (if blockp
8416 (narrow-to-region (car blockp) (cdr blockp))
8417 (user-error "Not in a block"))))
8419 (eval-when-compile
8420 (defvar org-property-drawer-re))
8422 (defvar org-property-start-re) ;; defined below
8423 (defun org-clone-subtree-with-time-shift (n &optional shift)
8424 "Clone the task (subtree) at point N times.
8425 The clones will be inserted as siblings.
8427 In interactive use, the user will be prompted for the number of
8428 clones to be produced. If the entry has a timestamp, the user
8429 will also be prompted for a time shift, which may be a repeater
8430 as used in time stamps, for example `+3d'. To disable this,
8431 you can call the function with a universal prefix argument.
8433 When a valid repeater is given and the entry contains any time
8434 stamps, the clones will become a sequence in time, with time
8435 stamps in the subtree shifted for each clone produced. If SHIFT
8436 is nil or the empty string, time stamps will be left alone. The
8437 ID property of the original subtree is removed.
8439 If the original subtree did contain time stamps with a repeater,
8440 the following will happen:
8441 - the repeater will be removed in each clone
8442 - an additional clone will be produced, with the current, unshifted
8443 date(s) in the entry.
8444 - the original entry will be placed *after* all the clones, with
8445 repeater intact.
8446 - the start days in the repeater in the original entry will be shifted
8447 to past the last clone.
8448 In this way you can spell out a number of instances of a repeating task,
8449 and still retain the repeater to cover future instances of the task."
8450 (interactive "nNumber of clones to produce: ")
8451 (let ((shift
8452 (or shift
8453 (if (and (not (equal current-prefix-arg '(4)))
8454 (save-excursion
8455 (re-search-forward org-ts-regexp-both
8456 (save-excursion
8457 (org-end-of-subtree t)
8458 (point)) t)))
8459 (read-from-minibuffer
8460 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8461 ""))) ;; No time shift
8462 (n-no-remove -1)
8463 (drawer-re org-drawer-regexp)
8464 beg end template task idprop
8465 shift-n shift-what doshift nmin nmax)
8466 (if (not (and (integerp n) (> n 0)))
8467 (error "Invalid number of replications %s" n))
8468 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8469 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8470 shift)))
8471 (error "Invalid shift specification %s" shift))
8472 (when doshift
8473 (setq shift-n (string-to-number (match-string 1 shift))
8474 shift-what (cdr (assoc (match-string 2 shift)
8475 '(("d" . day) ("w" . week)
8476 ("m" . month) ("y" . year))))))
8477 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8478 (setq nmin 1 nmax n)
8479 (org-back-to-heading t)
8480 (setq beg (point))
8481 (setq idprop (org-entry-get nil "ID"))
8482 (org-end-of-subtree t t)
8483 (or (bolp) (insert "\n"))
8484 (setq end (point))
8485 (setq template (buffer-substring beg end))
8486 (when (and doshift
8487 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8488 (delete-region beg end)
8489 (setq end beg)
8490 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8491 (goto-char end)
8492 (loop for n from nmin to nmax do
8493 ;; prepare clone
8494 (with-temp-buffer
8495 (insert template)
8496 (org-mode)
8497 (goto-char (point-min))
8498 (org-show-subtree)
8499 (and idprop (if org-clone-delete-id
8500 (org-entry-delete nil "ID")
8501 (org-id-get-create t)))
8502 (unless (= n 0)
8503 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8504 (kill-whole-line))
8505 (goto-char (point-min))
8506 (while (re-search-forward drawer-re nil t)
8507 (mapc (lambda (d)
8508 (org-remove-empty-drawer-at d (point))) org-drawers)))
8509 (goto-char (point-min))
8510 (when doshift
8511 (while (re-search-forward org-ts-regexp-both nil t)
8512 (org-timestamp-change (* n shift-n) shift-what))
8513 (unless (= n n-no-remove)
8514 (goto-char (point-min))
8515 (while (re-search-forward org-ts-regexp nil t)
8516 (save-excursion
8517 (goto-char (match-beginning 0))
8518 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8519 (delete-region (match-beginning 1) (match-end 1)))))))
8520 (setq task (buffer-string)))
8521 (insert task))
8522 (goto-char beg)))
8524 ;;; Outline Sorting
8526 (defun org-sort (with-case)
8527 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8528 Optional argument WITH-CASE means sort case-sensitively."
8529 (interactive "P")
8530 (cond
8531 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8532 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8534 (org-call-with-arg 'org-sort-entries with-case))))
8536 (defun org-sort-remove-invisible (s)
8537 "Remove invisible links from string S."
8538 (remove-text-properties 0 (length s) org-rm-props s)
8539 (while (string-match org-bracket-link-regexp s)
8540 (setq s (replace-match (if (match-end 2)
8541 (match-string 3 s)
8542 (match-string 1 s)) t t s)))
8543 (let ((st (format " %s " s)))
8544 (while (string-match org-emph-re st)
8545 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8546 (setq s (substring st 1 -1)))
8549 (defvar org-priority-regexp) ; defined later in the file
8551 (defvar org-after-sorting-entries-or-items-hook nil
8552 "Hook that is run after a bunch of entries or items have been sorted.
8553 When children are sorted, the cursor is in the parent line when this
8554 hook gets called. When a region or a plain list is sorted, the cursor
8555 will be in the first entry of the sorted region/list.")
8557 (defun org-sort-entries
8558 (&optional with-case sorting-type getkey-func compare-func property)
8559 "Sort entries on a certain level of an outline tree.
8560 If there is an active region, the entries in the region are sorted.
8561 Else, if the cursor is before the first entry, sort the top-level items.
8562 Else, the children of the entry at point are sorted.
8564 Sorting can be alphabetically, numerically, by date/time as given by
8565 a time stamp, by a property, by priority order, or by a custom function.
8567 The command prompts for the sorting type unless it has been given to the
8568 function through the SORTING-TYPE argument, which needs to be a character,
8569 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8570 precise meaning of each character:
8572 n Numerically, by converting the beginning of the entry/item to a number.
8573 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8574 o By order of TODO keywords.
8575 t By date/time, either the first active time stamp in the entry, or, if
8576 none exist, by the first inactive one.
8577 s By the scheduled date/time.
8578 d By deadline date/time.
8579 c By creation time, which is assumed to be the first inactive time stamp
8580 at the beginning of a line.
8581 p By priority according to the cookie.
8582 r By the value of a property.
8584 Capital letters will reverse the sort order.
8586 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8587 called with point at the beginning of the record. It must return either
8588 a string or a number that should serve as the sorting key for that record.
8590 Comparing entries ignores case by default. However, with an optional argument
8591 WITH-CASE, the sorting considers case as well.
8593 Sorting is done against the visible part of the headlines, it ignores hidden
8594 links."
8595 (interactive "P")
8596 (let ((case-func (if with-case 'identity 'downcase))
8597 (cmstr
8598 ;; The clock marker is lost when using `sort-subr', let's
8599 ;; store the clocking string.
8600 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8601 (save-excursion
8602 (goto-char org-clock-marker)
8603 (looking-back "^.*") (match-string-no-properties 0))))
8604 start beg end stars re re2
8605 txt what tmp)
8606 ;; Find beginning and end of region to sort
8607 (cond
8608 ((org-region-active-p)
8609 ;; we will sort the region
8610 (setq end (region-end)
8611 what "region")
8612 (goto-char (region-beginning))
8613 (if (not (org-at-heading-p)) (outline-next-heading))
8614 (setq start (point)))
8615 ((or (org-at-heading-p)
8616 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8617 ;; we will sort the children of the current headline
8618 (org-back-to-heading)
8619 (setq start (point)
8620 end (progn (org-end-of-subtree t t)
8621 (or (bolp) (insert "\n"))
8622 (org-back-over-empty-lines)
8623 (point))
8624 what "children")
8625 (goto-char start)
8626 (show-subtree)
8627 (outline-next-heading))
8629 ;; we will sort the top-level entries in this file
8630 (goto-char (point-min))
8631 (or (org-at-heading-p) (outline-next-heading))
8632 (setq start (point))
8633 (goto-char (point-max))
8634 (beginning-of-line 1)
8635 (when (looking-at ".*?\\S-")
8636 ;; File ends in a non-white line
8637 (end-of-line 1)
8638 (insert "\n"))
8639 (setq end (point-max))
8640 (setq what "top-level")
8641 (goto-char start)
8642 (show-all)))
8644 (setq beg (point))
8645 (if (>= beg end) (user-error "Nothing to sort"))
8647 (looking-at "\\(\\*+\\)")
8648 (setq stars (match-string 1)
8649 re (concat "^" (regexp-quote stars) " +")
8650 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8651 txt (buffer-substring beg end))
8652 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8653 (if (and (not (equal stars "*")) (string-match re2 txt))
8654 (user-error "Region to sort contains a level above the first entry"))
8656 (unless sorting-type
8657 (message
8658 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8659 [t]ime [s]cheduled [d]eadline [c]reated
8660 A/N/P/R/O/F/T/S/D/C means reversed:"
8661 what)
8662 (setq sorting-type (read-char-exclusive))
8664 (unless getkey-func
8665 (and (= (downcase sorting-type) ?f)
8666 (setq getkey-func
8667 (org-icompleting-read "Sort using function: "
8668 obarray 'fboundp t nil nil))
8669 (setq getkey-func (intern getkey-func))))
8671 (and (= (downcase sorting-type) ?r)
8672 (not property)
8673 (setq property
8674 (org-icompleting-read "Property: "
8675 (mapcar 'list (org-buffer-property-keys t))
8676 nil t))))
8678 (message "Sorting entries...")
8680 (save-restriction
8681 (narrow-to-region start end)
8682 (let ((dcst (downcase sorting-type))
8683 (case-fold-search nil)
8684 (now (current-time)))
8685 (sort-subr
8686 (/= dcst sorting-type)
8687 ;; This function moves to the beginning character of the "record" to
8688 ;; be sorted.
8689 (lambda nil
8690 (if (re-search-forward re nil t)
8691 (goto-char (match-beginning 0))
8692 (goto-char (point-max))))
8693 ;; This function moves to the last character of the "record" being
8694 ;; sorted.
8695 (lambda nil
8696 (save-match-data
8697 (condition-case nil
8698 (outline-forward-same-level 1)
8699 (error
8700 (goto-char (point-max))))))
8701 ;; This function returns the value that gets sorted against.
8702 (lambda nil
8703 (cond
8704 ((= dcst ?n)
8705 (if (looking-at org-complex-heading-regexp)
8706 (string-to-number (org-sort-remove-invisible (match-string 4)))
8707 nil))
8708 ((= dcst ?a)
8709 (if (looking-at org-complex-heading-regexp)
8710 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8711 nil))
8712 ((= dcst ?t)
8713 (let ((end (save-excursion (outline-next-heading) (point))))
8714 (if (or (re-search-forward org-ts-regexp end t)
8715 (re-search-forward org-ts-regexp-both end t))
8716 (org-time-string-to-seconds (match-string 0))
8717 (org-float-time now))))
8718 ((= dcst ?c)
8719 (let ((end (save-excursion (outline-next-heading) (point))))
8720 (if (re-search-forward
8721 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8722 end t)
8723 (org-time-string-to-seconds (match-string 0))
8724 (org-float-time now))))
8725 ((= dcst ?s)
8726 (let ((end (save-excursion (outline-next-heading) (point))))
8727 (if (re-search-forward org-scheduled-time-regexp end t)
8728 (org-time-string-to-seconds (match-string 1))
8729 (org-float-time now))))
8730 ((= dcst ?d)
8731 (let ((end (save-excursion (outline-next-heading) (point))))
8732 (if (re-search-forward org-deadline-time-regexp end t)
8733 (org-time-string-to-seconds (match-string 1))
8734 (org-float-time now))))
8735 ((= dcst ?p)
8736 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8737 (string-to-char (match-string 2))
8738 org-default-priority))
8739 ((= dcst ?r)
8740 (or (org-entry-get nil property) ""))
8741 ((= dcst ?o)
8742 (if (looking-at org-complex-heading-regexp)
8743 (- 9999 (length (member (match-string 2)
8744 org-todo-keywords-1)))))
8745 ((= dcst ?f)
8746 (if getkey-func
8747 (progn
8748 (setq tmp (funcall getkey-func))
8749 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8750 tmp)
8751 (error "Invalid key function `%s'" getkey-func)))
8752 (t (error "Invalid sorting type `%c'" sorting-type))))
8754 (cond
8755 ((= dcst ?a) 'string<)
8756 ((= dcst ?f) compare-func)
8757 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8758 (run-hooks 'org-after-sorting-entries-or-items-hook)
8759 ;; Reset the clock marker if needed
8760 (when cmstr
8761 (save-excursion
8762 (goto-char start)
8763 (search-forward cmstr nil t)
8764 (move-marker org-clock-marker (point))))
8765 (message "Sorting entries...done")))
8767 (defun org-do-sort (table what &optional with-case sorting-type)
8768 "Sort TABLE of WHAT according to SORTING-TYPE.
8769 The user will be prompted for the SORTING-TYPE if the call to this
8770 function does not specify it. WHAT is only for the prompt, to indicate
8771 what is being sorted. The sorting key will be extracted from
8772 the car of the elements of the table.
8773 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8774 (unless sorting-type
8775 (message
8776 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8777 what)
8778 (setq sorting-type (read-char-exclusive)))
8779 (let ((dcst (downcase sorting-type))
8780 extractfun comparefun)
8781 ;; Define the appropriate functions
8782 (cond
8783 ((= dcst ?n)
8784 (setq extractfun 'string-to-number
8785 comparefun (if (= dcst sorting-type) '< '>)))
8786 ((= dcst ?a)
8787 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8788 (lambda(x) (downcase (org-sort-remove-invisible x))))
8789 comparefun (if (= dcst sorting-type)
8790 'string<
8791 (lambda (a b) (and (not (string< a b))
8792 (not (string= a b)))))))
8793 ((= dcst ?t)
8794 (setq extractfun
8795 (lambda (x)
8796 (if (or (string-match org-ts-regexp x)
8797 (string-match org-ts-regexp-both x))
8798 (org-float-time
8799 (org-time-string-to-time (match-string 0 x)))
8801 comparefun (if (= dcst sorting-type) '< '>)))
8802 (t (error "Invalid sorting type `%c'" sorting-type)))
8804 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8805 table)
8806 (lambda (a b) (funcall comparefun (car a) (car b))))))
8809 ;;; The orgstruct minor mode
8811 ;; Define a minor mode which can be used in other modes in order to
8812 ;; integrate the org-mode structure editing commands.
8814 ;; This is really a hack, because the org-mode structure commands use
8815 ;; keys which normally belong to the major mode. Here is how it
8816 ;; works: The minor mode defines all the keys necessary to operate the
8817 ;; structure commands, but wraps the commands into a function which
8818 ;; tests if the cursor is currently at a headline or a plain list
8819 ;; item. If that is the case, the structure command is used,
8820 ;; temporarily setting many Org-mode variables like regular
8821 ;; expressions for filling etc. However, when any of those keys is
8822 ;; used at a different location, function uses `key-binding' to look
8823 ;; up if the key has an associated command in another currently active
8824 ;; keymap (minor modes, major mode, global), and executes that
8825 ;; command. There might be problems if any of the keys is otherwise
8826 ;; used as a prefix key.
8828 (defcustom orgstruct-heading-prefix-regexp nil
8829 "Regexp that matches the custom prefix of Org headlines in
8830 orgstruct(++)-mode."
8831 :group 'org
8832 :version "24.4"
8833 :package-version '(Org . "8.0")
8834 :type 'string)
8835 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8837 (defcustom orgstruct-setup-hook nil
8838 "Hook run after orgstruct-mode-map is filled."
8839 :group 'org
8840 :version "24.4"
8841 :package-version '(Org . "8.0")
8842 :type 'hook)
8844 (defvar orgstruct-initialized nil)
8846 (defvar org-local-vars nil
8847 "List of local variables, for use by `orgstruct-mode'.")
8849 ;;;###autoload
8850 (define-minor-mode orgstruct-mode
8851 "Toggle the minor mode `orgstruct-mode'.
8852 This mode is for using Org-mode structure commands in other
8853 modes. The following keys behave as if Org-mode were active, if
8854 the cursor is on a headline, or on a plain list item (both as
8855 defined by Org-mode)."
8856 nil " OrgStruct" (make-sparse-keymap)
8857 (funcall (if orgstruct-mode
8858 'add-to-invisibility-spec
8859 'remove-from-invisibility-spec)
8860 '(outline . t))
8861 (when orgstruct-mode
8862 (org-load-modules-maybe)
8863 (unless orgstruct-initialized
8864 (orgstruct-setup)
8865 (setq orgstruct-initialized t))))
8867 ;;;###autoload
8868 (defun turn-on-orgstruct ()
8869 "Unconditionally turn on `orgstruct-mode'."
8870 (orgstruct-mode 1))
8872 (defvar org-fb-vars nil)
8873 (make-variable-buffer-local 'org-fb-vars)
8874 (defun orgstruct++-mode (&optional arg)
8875 "Toggle `orgstruct-mode', the enhanced version of it.
8876 In addition to setting orgstruct-mode, this also exports all
8877 indentation and autofilling variables from org-mode into the
8878 buffer. It will also recognize item context in multiline items."
8879 (interactive "P")
8880 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8881 (if (< arg 1)
8882 (progn (orgstruct-mode -1)
8883 (mapc (lambda(v)
8884 (org-set-local (car v)
8885 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8886 org-fb-vars))
8887 (orgstruct-mode 1)
8888 (setq org-fb-vars nil)
8889 (unless org-local-vars
8890 (setq org-local-vars (org-get-local-variables)))
8891 (let (var val)
8892 (mapc
8893 (lambda (x)
8894 (when (string-match
8895 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8896 (symbol-name (car x)))
8897 (setq var (car x) val (nth 1 x))
8898 (push (list var `(quote ,(eval var))) org-fb-vars)
8899 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8900 org-local-vars)
8901 (org-set-local 'orgstruct-is-++ t))))
8903 (defvar orgstruct-is-++ nil
8904 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8905 (make-variable-buffer-local 'orgstruct-is-++)
8907 ;;;###autoload
8908 (defun turn-on-orgstruct++ ()
8909 "Unconditionally turn on `orgstruct++-mode'."
8910 (orgstruct++-mode 1))
8912 (defun orgstruct-error ()
8913 "Error when there is no default binding for a structure key."
8914 (interactive)
8915 (funcall (if (fboundp 'user-error)
8916 'user-error
8917 'error)
8918 "This key has no function outside structure elements"))
8920 (defun orgstruct-setup ()
8921 "Setup orgstruct keymap."
8922 (dolist (cell '((org-demote . t)
8923 (org-metaleft . t)
8924 (org-metaright . t)
8925 (org-promote . t)
8926 (org-shiftmetaleft . t)
8927 (org-shiftmetaright . t)
8928 org-backward-element
8929 org-backward-heading-same-level
8930 org-ctrl-c-ret
8931 org-ctrl-c-minus
8932 org-ctrl-c-star
8933 org-cycle
8934 org-forward-heading-same-level
8935 org-insert-heading
8936 org-insert-heading-respect-content
8937 org-kill-note-or-show-branches
8938 org-mark-subtree
8939 org-meta-return
8940 org-metadown
8941 org-metaup
8942 org-narrow-to-subtree
8943 org-promote-subtree
8944 org-reveal
8945 org-shiftdown
8946 org-shiftleft
8947 org-shiftmetadown
8948 org-shiftmetaup
8949 org-shiftright
8950 org-shifttab
8951 org-shifttab
8952 org-shiftup
8953 org-show-subtree
8954 org-sort
8955 org-up-element
8956 outline-demote
8957 outline-next-visible-heading
8958 outline-previous-visible-heading
8959 outline-promote
8960 outline-up-heading
8961 show-children))
8962 (let ((f (or (car-safe cell) cell))
8963 (disable-when-heading-prefix (cdr-safe cell)))
8964 (when (fboundp f)
8965 (let ((new-bindings))
8966 (dolist (binding (nconc (where-is-internal f org-mode-map)
8967 (where-is-internal f outline-mode-map)))
8968 (push binding new-bindings)
8969 ;; TODO use local-function-key-map
8970 (dolist (rep '(("<tab>" . "TAB")
8971 ("<return>" . "RET")
8972 ("<escape>" . "ESC")
8973 ("<delete>" . "DEL")))
8974 (setq binding (read-kbd-macro
8975 (let ((case-fold-search))
8976 (replace-regexp-in-string
8977 (regexp-quote (cdr rep))
8978 (car rep)
8979 (key-description binding)))))
8980 (pushnew binding new-bindings :test 'equal)))
8981 (dolist (binding new-bindings)
8982 (let ((key (lookup-key orgstruct-mode-map binding)))
8983 (when (or (not key) (numberp key))
8984 (condition-case nil
8985 (org-defkey orgstruct-mode-map
8986 binding
8987 (orgstruct-make-binding f binding disable-when-heading-prefix))
8988 (error nil)))))))))
8989 (run-hooks 'orgstruct-setup-hook))
8991 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8992 "Create a function for binding in the structure minor mode.
8993 FUN is the command to call inside a table. KEY is the key that
8994 should be checked in for a command to execute outside of tables.
8995 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8996 if `orgstruct-heading-prefix-regexp' is non-nil."
8997 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8998 (let ((nname name)
8999 (i 0))
9000 (while (fboundp (intern nname))
9001 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9002 (setq name (intern nname)))
9003 (eval
9004 (let ((bindings '((org-heading-regexp
9005 (concat "^"
9006 orgstruct-heading-prefix-regexp
9007 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9008 (org-outline-regexp
9009 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9010 (org-outline-regexp-bol
9011 (concat "^" org-outline-regexp))
9012 (outline-regexp org-outline-regexp)
9013 (outline-heading-end-regexp "\n")
9014 (outline-level 'org-outline-level)
9015 (outline-heading-alist))))
9016 `(defun ,name (arg)
9017 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9018 "Outside of structure, run the binding of `"
9019 (key-description key) "'."
9020 (when disable-when-heading-prefix
9021 (concat
9022 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9023 "back to the default binding due to limitations of Org's implementation of\n"
9024 "`" (symbol-name fun) "'.")))
9025 (interactive "p")
9026 (let* ((disable
9027 ,(when disable-when-heading-prefix
9028 '(and orgstruct-heading-prefix-regexp
9029 (not (string= orgstruct-heading-prefix-regexp "")))))
9030 (fallback
9031 (or disable
9032 (not
9033 (let* ,bindings
9034 (org-context-p 'headline 'item
9035 ,(when (memq fun
9036 '(org-insert-heading
9037 org-insert-heading-respect-content
9038 org-meta-return))
9039 '(when orgstruct-is-++
9040 'item-body))))))))
9041 (if fallback
9042 (let* ((orgstruct-mode)
9043 (binding
9044 (loop with key = ,key
9045 for rep in
9046 '(nil
9047 ("<\\([^>]*\\)tab>" . "\\1TAB")
9048 ("<\\([^>]*\\)return>" . "\\1RET")
9049 ("<\\([^>]*\\)escape>" . "\\1ESC")
9050 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9052 (when rep
9053 (setq key (read-kbd-macro
9054 (let ((case-fold-search))
9055 (replace-regexp-in-string
9056 (car rep)
9057 (cdr rep)
9058 (key-description key))))))
9059 thereis (key-binding key))))
9060 (if (keymapp binding)
9061 (set-temporary-overlay-map binding)
9062 (let ((func (or binding
9063 (unless disable
9064 'orgstruct-error))))
9065 (when func
9066 (call-interactively func)))))
9067 (org-run-like-in-org-mode
9068 (lambda ()
9069 (interactive)
9070 (let* ,bindings
9071 (call-interactively ',fun)))))))))
9072 name))
9074 (defun org-contextualize-keys (alist contexts)
9075 "Return valid elements in ALIST depending on CONTEXTS.
9077 `org-agenda-custom-commands' or `org-capture-templates' are the
9078 values used for ALIST, and `org-agenda-custom-commands-contexts'
9079 or `org-capture-templates-contexts' are the associated contexts
9080 definitions."
9081 (let ((contexts
9082 ;; normalize contexts
9083 (mapcar
9084 (lambda(c) (cond ((listp (cadr c))
9085 (list (car c) (car c) (cadr c)))
9086 ((string= "" (cadr c))
9087 (list (car c) (car c) (caddr c)))
9088 (t c))) contexts))
9089 (a alist) c r s)
9090 ;; loop over all commands or templates
9091 (while (setq c (pop a))
9092 (let (vrules repl)
9093 (cond
9094 ((not (assoc (car c) contexts))
9095 (push c r))
9096 ((and (assoc (car c) contexts)
9097 (setq vrules (org-contextualize-validate-key
9098 (car c) contexts)))
9099 (mapc (lambda (vr)
9100 (when (not (equal (car vr) (cadr vr)))
9101 (setq repl vr))) vrules)
9102 (if (not repl) (push c r)
9103 (push (cadr repl) s)
9104 (push
9105 (cons (car c)
9106 (cdr (or (assoc (cadr repl) alist)
9107 (error "Undefined key `%s' as contextual replacement for `%s'"
9108 (cadr repl) (car c)))))
9109 r))))))
9110 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9111 (delq
9113 (delete-dups
9114 (mapcar (lambda (x)
9115 (let ((tpl (car x)))
9116 (when (not (delq
9118 (mapcar (lambda(y)
9119 (equal y tpl)) s))) x)))
9120 (reverse r))))))
9122 (defun org-contextualize-validate-key (key contexts)
9123 "Check CONTEXTS for agenda or capture KEY."
9124 (let (r rr res)
9125 (while (setq r (pop contexts))
9126 (mapc
9127 (lambda (rr)
9128 (when
9129 (and (equal key (car r))
9130 (if (functionp rr) (funcall rr)
9131 (or (and (eq (car rr) 'in-file)
9132 (buffer-file-name)
9133 (string-match (cdr rr) (buffer-file-name)))
9134 (and (eq (car rr) 'in-mode)
9135 (string-match (cdr rr) (symbol-name major-mode)))
9136 (and (eq (car rr) 'in-buffer)
9137 (string-match (cdr rr) (buffer-name)))
9138 (when (and (eq (car rr) 'not-in-file)
9139 (buffer-file-name))
9140 (not (string-match (cdr rr) (buffer-file-name))))
9141 (when (eq (car rr) 'not-in-mode)
9142 (not (string-match (cdr rr) (symbol-name major-mode))))
9143 (when (eq (car rr) 'not-in-buffer)
9144 (not (string-match (cdr rr) (buffer-name)))))))
9145 (push r res)))
9146 (car (last r))))
9147 (delete-dups (delq nil res))))
9149 (defun org-context-p (&rest contexts)
9150 "Check if local context is any of CONTEXTS.
9151 Possible values in the list of contexts are `table', `headline', and `item'."
9152 (let ((pos (point)))
9153 (goto-char (point-at-bol))
9154 (prog1 (or (and (memq 'table contexts)
9155 (looking-at "[ \t]*|"))
9156 (and (memq 'headline contexts)
9157 (looking-at org-outline-regexp))
9158 (and (memq 'item contexts)
9159 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9160 (and (memq 'item-body contexts)
9161 (org-in-item-p)))
9162 (goto-char pos))))
9164 (defun org-get-local-variables ()
9165 "Return a list of all local variables in an Org mode buffer."
9166 (let (varlist)
9167 (with-current-buffer (get-buffer-create "*Org tmp*")
9168 (erase-buffer)
9169 (org-mode)
9170 (setq varlist (buffer-local-variables)))
9171 (kill-buffer "*Org tmp*")
9172 (delq nil
9173 (mapcar
9174 (lambda (x)
9175 (setq x
9176 (if (symbolp x)
9177 (list x)
9178 (list (car x) (cdr x))))
9179 (if (and (not (get (car x) 'org-state))
9180 (string-match
9181 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9182 (symbol-name (car x))))
9183 x nil))
9184 varlist))))
9186 (defun org-clone-local-variables (from-buffer &optional regexp)
9187 "Clone local variables from FROM-BUFFER.
9188 Optional argument REGEXP selects variables to clone."
9189 (mapc
9190 (lambda (pair)
9191 (and (symbolp (car pair))
9192 (or (null regexp)
9193 (string-match regexp (symbol-name (car pair))))
9194 (set (make-local-variable (car pair))
9195 (cdr pair))))
9196 (buffer-local-variables from-buffer)))
9198 ;;;###autoload
9199 (defun org-run-like-in-org-mode (cmd)
9200 "Run a command, pretending that the current buffer is in Org-mode.
9201 This will temporarily bind local variables that are typically bound in
9202 Org-mode to the values they have in Org-mode, and then interactively
9203 call CMD."
9204 (org-load-modules-maybe)
9205 (unless org-local-vars
9206 (setq org-local-vars (org-get-local-variables)))
9207 (let (binds)
9208 (dolist (var org-local-vars)
9209 (when (or (not (boundp (car var)))
9210 (eq (symbol-value (car var))
9211 (default-value (car var))))
9212 (push (list (car var) `(quote ,(cadr var))) binds)))
9213 (eval `(let ,binds
9214 (call-interactively (quote ,cmd))))))
9216 ;;;; Archiving
9218 (defun org-get-category (&optional pos force-refresh)
9219 "Get the category applying to position POS."
9220 (save-match-data
9221 (if force-refresh (org-refresh-category-properties))
9222 (let ((pos (or pos (point))))
9223 (or (get-text-property pos 'org-category)
9224 (progn (org-refresh-category-properties)
9225 (get-text-property pos 'org-category))))))
9227 (defun org-refresh-category-properties ()
9228 "Refresh category text properties in the buffer."
9229 (let ((case-fold-search t)
9230 (inhibit-read-only t)
9231 (def-cat (cond
9232 ((null org-category)
9233 (if buffer-file-name
9234 (file-name-sans-extension
9235 (file-name-nondirectory buffer-file-name))
9236 "???"))
9237 ((symbolp org-category) (symbol-name org-category))
9238 (t org-category)))
9239 beg end cat pos optionp)
9240 (org-with-silent-modifications
9241 (save-excursion
9242 (save-restriction
9243 (widen)
9244 (goto-char (point-min))
9245 (put-text-property (point) (point-max) 'org-category def-cat)
9246 (while (re-search-forward
9247 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9248 (setq pos (match-end 0)
9249 optionp (equal (char-after (match-beginning 0)) ?#)
9250 cat (org-trim (match-string 2)))
9251 (if optionp
9252 (setq beg (point-at-bol) end (point-max))
9253 (org-back-to-heading t)
9254 (setq beg (point) end (org-end-of-subtree t t)))
9255 (put-text-property beg end 'org-category cat)
9256 (put-text-property beg end 'org-category-position beg)
9257 (goto-char pos)))))))
9259 (defun org-refresh-properties (dprop tprop)
9260 "Refresh buffer text properties.
9261 DPROP is the drawer property and TPROP is the corresponding text
9262 property to set."
9263 (let ((case-fold-search t)
9264 (inhibit-read-only t) p)
9265 (org-with-silent-modifications
9266 (save-excursion
9267 (save-restriction
9268 (widen)
9269 (goto-char (point-min))
9270 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9271 (setq p (org-match-string-no-properties 1))
9272 (save-excursion
9273 (org-back-to-heading t)
9274 (put-text-property
9275 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9278 ;;;; Link Stuff
9280 ;;; Link abbreviations
9282 (defun org-link-expand-abbrev (link)
9283 "Apply replacements as defined in `org-link-abbrev-alist'."
9284 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9285 (let* ((key (match-string 1 link))
9286 (as (or (assoc key org-link-abbrev-alist-local)
9287 (assoc key org-link-abbrev-alist)))
9288 (tag (and (match-end 2) (match-string 3 link)))
9289 rpl)
9290 (if (not as)
9291 link
9292 (setq rpl (cdr as))
9293 (cond
9294 ((symbolp rpl) (funcall rpl tag))
9295 ((string-match "%(\\([^)]+\\))" rpl)
9296 (replace-match
9297 (save-match-data
9298 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9299 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9300 ((string-match "%h" rpl)
9301 (replace-match (url-hexify-string (or tag "")) t t rpl))
9302 (t (concat rpl tag)))))
9303 link))
9305 ;;; Storing and inserting links
9307 (defvar org-insert-link-history nil
9308 "Minibuffer history for links inserted with `org-insert-link'.")
9310 (defvar org-stored-links nil
9311 "Contains the links stored with `org-store-link'.")
9313 (defvar org-store-link-plist nil
9314 "Plist with info about the most recently link created with `org-store-link'.")
9316 (defvar org-link-protocols nil
9317 "Link protocols added to Org-mode using `org-add-link-type'.")
9319 (defvar org-store-link-functions nil
9320 "List of functions that are called to create and store a link.
9321 Each function will be called in turn until one returns a non-nil
9322 value. Each function should check if it is responsible for creating
9323 this link (for example by looking at the major mode).
9324 If not, it must exit and return nil.
9325 If yes, it should return a non-nil value after a calling
9326 `org-store-link-props' with a list of properties and values.
9327 Special properties are:
9329 :type The link prefix, like \"http\". This must be given.
9330 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9331 This is obligatory as well.
9332 :description Optional default description for the second pair
9333 of brackets in an Org-mode link. The user can still change
9334 this when inserting this link into an Org-mode buffer.
9336 In addition to these, any additional properties can be specified
9337 and then used in capture templates.")
9339 (defun org-add-link-type (type &optional follow export)
9340 "Add TYPE to the list of `org-link-types'.
9341 Re-compute all regular expressions depending on `org-link-types'
9343 FOLLOW and EXPORT are two functions.
9345 FOLLOW should take the link path as the single argument and do whatever
9346 is necessary to follow the link, for example find a file or display
9347 a mail message.
9349 EXPORT should format the link path for export to one of the export formats.
9350 It should be a function accepting three arguments:
9352 path the path of the link, the text after the prefix (like \"http:\")
9353 desc the description of the link, if any, or a description added by
9354 org-export-normalize-links if there is none
9355 format the export format, a symbol like `html' or `latex' or `ascii'..
9357 The function may use the FORMAT information to return different values
9358 depending on the format. The return value will be put literally into
9359 the exported file. If the return value is nil, this means Org should
9360 do what it normally does with links which do not have EXPORT defined.
9362 Org-mode has a built-in default for exporting links. If you are happy with
9363 this default, there is no need to define an export function for the link
9364 type. For a simple example of an export function, see `org-bbdb.el'."
9365 (add-to-list 'org-link-types type t)
9366 (org-make-link-regexps)
9367 (if (assoc type org-link-protocols)
9368 (setcdr (assoc type org-link-protocols) (list follow export))
9369 (push (list type follow export) org-link-protocols)))
9371 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9372 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9374 ;;;###autoload
9375 (defun org-store-link (arg)
9376 "\\<org-mode-map>Store an org-link to the current location.
9377 This link is added to `org-stored-links' and can later be inserted
9378 into an org-buffer with \\[org-insert-link].
9380 For some link types, a prefix arg is interpreted.
9381 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9382 For file links, arg negates `org-context-in-file-links'.
9384 A double prefix arg force skipping storing functions that are not
9385 part of Org's core.
9387 A triple prefix arg force storing a link for each line in the
9388 active region."
9389 (interactive "P")
9390 (org-load-modules-maybe)
9391 (if (and (equal arg '(64)) (org-region-active-p))
9392 (save-excursion
9393 (let ((end (region-end)))
9394 (goto-char (region-beginning))
9395 (set-mark (point))
9396 (while (< (point-at-eol) end)
9397 (move-end-of-line 1) (activate-mark)
9398 (let (current-prefix-arg)
9399 (call-interactively 'org-store-link))
9400 (move-beginning-of-line 2)
9401 (set-mark (point)))))
9402 (org-with-limited-levels
9403 (setq org-store-link-plist nil)
9404 (let (link cpltxt desc description search
9405 txt custom-id agenda-link sfuns sfunsn)
9406 (cond
9408 ;; Store a link using an external link type
9409 ((and (not (equal arg '(16)))
9410 (setq sfuns
9411 (delq
9412 nil (mapcar (lambda (f)
9413 (let (fs) (if (funcall f) (push f fs))))
9414 org-store-link-functions))
9415 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9416 (or (and (cdr sfuns)
9417 (funcall (intern
9418 (completing-read
9419 "Which function for creating the link? "
9420 sfunsn t (car sfunsn)))))
9421 (funcall (caar sfuns)))
9422 (setq link (plist-get org-store-link-plist :link)
9423 desc (or (plist-get org-store-link-plist
9424 :description) link))))
9426 ;; Store a link from a source code buffer
9427 ((org-src-edit-buffer-p)
9428 (let (label gc)
9429 (while (or (not label)
9430 (save-excursion
9431 (save-restriction
9432 (widen)
9433 (goto-char (point-min))
9434 (re-search-forward
9435 (regexp-quote (format org-coderef-label-format label))
9436 nil t))))
9437 (when label (message "Label exists already") (sit-for 2))
9438 (setq label (read-string "Code line label: " label)))
9439 (end-of-line 1)
9440 (setq link (format org-coderef-label-format label))
9441 (setq gc (- 79 (length link)))
9442 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9443 (insert link)
9444 (setq link (concat "(" label ")") desc nil)))
9446 ;; We are in the agenda, link to referenced location
9447 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9448 (let ((m (or (get-text-property (point) 'org-hd-marker)
9449 (get-text-property (point) 'org-marker))))
9450 (when m
9451 (org-with-point-at m
9452 (setq agenda-link
9453 (if (org-called-interactively-p 'any)
9454 (call-interactively 'org-store-link)
9455 (org-store-link nil)))))))
9457 ((eq major-mode 'calendar-mode)
9458 (let ((cd (calendar-cursor-to-date)))
9459 (setq link
9460 (format-time-string
9461 (car org-time-stamp-formats)
9462 (apply 'encode-time
9463 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9464 nil nil nil))))
9465 (org-store-link-props :type "calendar" :date cd)))
9467 ((eq major-mode 'help-mode)
9468 (setq link (concat "help:" (save-excursion
9469 (goto-char (point-min))
9470 (looking-at "^[^ ]+")
9471 (match-string 0))))
9472 (org-store-link-props :type "help"))
9474 ((eq major-mode 'w3-mode)
9475 (setq cpltxt (if (and (buffer-name)
9476 (not (string-match "Untitled" (buffer-name))))
9477 (buffer-name)
9478 (url-view-url t))
9479 link (url-view-url t))
9480 (org-store-link-props :type "w3" :url (url-view-url t)))
9482 ((eq major-mode 'image-mode)
9483 (setq cpltxt (concat "file:"
9484 (abbreviate-file-name buffer-file-name))
9485 link cpltxt)
9486 (org-store-link-props :type "image" :file buffer-file-name))
9488 ;; In dired, store a link to the file of the current line
9489 ((eq major-mode 'dired-mode)
9490 (let ((file (dired-get-filename nil t)))
9491 (setq file (if file
9492 (abbreviate-file-name
9493 (expand-file-name (dired-get-filename nil t)))
9494 ;; otherwise, no file so use current directory.
9495 default-directory))
9496 (setq cpltxt (concat "file:" file)
9497 link cpltxt)))
9499 ((setq search (run-hook-with-args-until-success
9500 'org-create-file-search-functions))
9501 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9502 "::" search))
9503 (setq cpltxt (or description link)))
9505 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9506 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9507 (cond
9508 ;; Store a link using the target at point
9509 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9510 (setq cpltxt
9511 (concat "file:"
9512 (abbreviate-file-name
9513 (buffer-file-name (buffer-base-buffer)))
9514 "::" (match-string 1))
9515 link cpltxt))
9516 ((and (featurep 'org-id)
9517 (or (eq org-id-link-to-org-use-id t)
9518 (and (org-called-interactively-p 'any)
9519 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9520 (and (eq org-id-link-to-org-use-id
9521 'create-if-interactive-and-no-custom-id)
9522 (not custom-id))))
9523 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9524 ;; Store a link using the ID at point
9525 (setq link (condition-case nil
9526 (prog1 (org-id-store-link)
9527 (setq desc (plist-get org-store-link-plist
9528 :description)))
9529 (error
9530 ;; Probably before first headline, link only to file
9531 (concat "file:"
9532 (abbreviate-file-name
9533 (buffer-file-name (buffer-base-buffer))))))))
9535 ;; Just link to current headline
9536 (setq cpltxt (concat "file:"
9537 (abbreviate-file-name
9538 (buffer-file-name (buffer-base-buffer)))))
9539 ;; Add a context search string
9540 (when (org-xor org-context-in-file-links arg)
9541 (let* ((ee (org-element-at-point))
9542 (et (org-element-type ee))
9543 (ev (plist-get (cadr ee) :value))
9544 (ek (plist-get (cadr ee) :key))
9545 (eok (and (stringp ek) (string-match "name" ek))))
9546 (setq txt (cond
9547 ((org-at-heading-p) nil)
9548 ((and (eq et 'keyword) eok) ev)
9549 ((org-region-active-p)
9550 (buffer-substring (region-beginning) (region-end)))))
9551 (when (or (null txt) (string-match "\\S-" txt))
9552 (setq cpltxt
9553 (concat cpltxt "::"
9554 (condition-case nil
9555 (org-make-org-heading-search-string txt)
9556 (error "")))
9557 desc (or (and (eq et 'keyword) eok ev)
9558 (nth 4 (ignore-errors (org-heading-components)))
9559 "NONE")))))
9560 (if (string-match "::\\'" cpltxt)
9561 (setq cpltxt (substring cpltxt 0 -2)))
9562 (setq link cpltxt))))
9564 ((buffer-file-name (buffer-base-buffer))
9565 ;; Just link to this file here.
9566 (setq cpltxt (concat "file:"
9567 (abbreviate-file-name
9568 (buffer-file-name (buffer-base-buffer)))))
9569 ;; Add a context string.
9570 (when (org-xor org-context-in-file-links arg)
9571 (setq txt (if (org-region-active-p)
9572 (buffer-substring (region-beginning) (region-end))
9573 (buffer-substring (point-at-bol) (point-at-eol))))
9574 ;; Only use search option if there is some text.
9575 (when (string-match "\\S-" txt)
9576 (setq cpltxt
9577 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9578 desc "NONE")))
9579 (setq link cpltxt))
9581 ((org-called-interactively-p 'interactive)
9582 (user-error "No method for storing a link from this buffer"))
9584 (t (setq link nil)))
9586 ;; We're done setting link and desc, clean up
9587 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9588 (setq link (or link cpltxt)
9589 desc (or desc cpltxt))
9590 (cond ((equal desc "NONE") (setq desc nil))
9591 ((string-match org-bracket-link-analytic-regexp desc)
9592 (let ((d0 (match-string 3 desc))
9593 (p0 (match-string 5 desc)))
9594 (setq desc
9595 (replace-regexp-in-string
9596 org-bracket-link-regexp
9597 (concat (or p0 d0)
9598 (if (equal (length (match-string 0 desc))
9599 (length desc)) "*" "")) desc)))))
9601 ;; Return the link
9602 (if (not (and (or (org-called-interactively-p 'any)
9603 executing-kbd-macro) link))
9604 (or agenda-link (and link (org-make-link-string link desc)))
9605 (push (list link desc) org-stored-links)
9606 (message "Stored: %s" (or desc link))
9607 (when custom-id
9608 (setq link (concat "file:" (abbreviate-file-name
9609 (buffer-file-name)) "::#" custom-id))
9610 (push (list link desc) org-stored-links)))))))
9612 (defun org-store-link-props (&rest plist)
9613 "Store link properties, extract names and addresses."
9614 (let (x adr)
9615 (when (setq x (plist-get plist :from))
9616 (setq adr (mail-extract-address-components x))
9617 (setq plist (plist-put plist :fromname (car adr)))
9618 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9619 (when (setq x (plist-get plist :to))
9620 (setq adr (mail-extract-address-components x))
9621 (setq plist (plist-put plist :toname (car adr)))
9622 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9623 (let ((from (plist-get plist :from))
9624 (to (plist-get plist :to)))
9625 (when (and from to org-from-is-user-regexp)
9626 (setq plist
9627 (plist-put plist :fromto
9628 (if (string-match org-from-is-user-regexp from)
9629 (concat "to %t")
9630 (concat "from %f"))))))
9631 (setq org-store-link-plist plist))
9633 (defun org-add-link-props (&rest plist)
9634 "Add these properties to the link property list."
9635 (let (key value)
9636 (while plist
9637 (setq key (pop plist) value (pop plist))
9638 (setq org-store-link-plist
9639 (plist-put org-store-link-plist key value)))))
9641 (defun org-email-link-description (&optional fmt)
9642 "Return the description part of an email link.
9643 This takes information from `org-store-link-plist' and formats it
9644 according to FMT (default from `org-email-link-description-format')."
9645 (setq fmt (or fmt org-email-link-description-format))
9646 (let* ((p org-store-link-plist)
9647 (to (plist-get p :toaddress))
9648 (from (plist-get p :fromaddress))
9649 (table
9650 (list
9651 (cons "%c" (plist-get p :fromto))
9652 (cons "%F" (plist-get p :from))
9653 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9654 (cons "%T" (plist-get p :to))
9655 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9656 (cons "%s" (plist-get p :subject))
9657 (cons "%d" (plist-get p :date))
9658 (cons "%m" (plist-get p :message-id)))))
9659 (when (string-match "%c" fmt)
9660 ;; Check if the user wrote this message
9661 (if (and org-from-is-user-regexp from to
9662 (save-match-data (string-match org-from-is-user-regexp from)))
9663 (setq fmt (replace-match "to %t" t t fmt))
9664 (setq fmt (replace-match "from %f" t t fmt))))
9665 (org-replace-escapes fmt table)))
9667 (defun org-make-org-heading-search-string (&optional string)
9668 "Make search string for the current headline or STRING."
9669 (let ((s (or string
9670 (and (derived-mode-p 'org-mode)
9671 (save-excursion
9672 (org-back-to-heading t)
9673 (org-element-property :raw-value (org-element-at-point))))))
9674 (lines org-context-in-file-links))
9675 (or string (setq s (concat "*" s))) ; Add * for headlines
9676 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9677 (when (and string (integerp lines) (> lines 0))
9678 (let ((slines (org-split-string s "\n")))
9679 (when (< lines (length slines))
9680 (setq s (mapconcat
9681 'identity
9682 (reverse (nthcdr (- (length slines) lines)
9683 (reverse slines))) "\n")))))
9684 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9686 (defun org-make-link-string (link &optional description)
9687 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9688 (unless (string-match "\\S-" link)
9689 (error "Empty link"))
9690 (when (and description
9691 (stringp description)
9692 (not (string-match "\\S-" description)))
9693 (setq description nil))
9694 (when (stringp description)
9695 ;; Remove brackets from the description, they are fatal.
9696 (while (string-match "\\[" description)
9697 (setq description (replace-match "{" t t description)))
9698 (while (string-match "\\]" description)
9699 (setq description (replace-match "}" t t description))))
9700 (when (equal link description)
9701 ;; No description needed, it is identical
9702 (setq description nil))
9703 (when (and (not description)
9704 (not (string-match (org-image-file-name-regexp) link))
9705 (not (equal link (org-link-escape link))))
9706 (setq description (org-extract-attributes link)))
9707 (setq link
9708 (cond ((string-match (org-image-file-name-regexp) link) link)
9709 ((string-match org-link-types-re link)
9710 (concat (match-string 1 link)
9711 (org-link-escape (substring link (match-end 1)))))
9712 (t (org-link-escape link))))
9713 (concat "[[" link "]"
9714 (if description (concat "[" description "]") "")
9715 "]"))
9717 (defconst org-link-escape-chars
9718 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9719 "List of characters that should be escaped in link.
9720 This is the list that is used for internal purposes.")
9722 (defconst org-link-escape-chars-browser
9723 '(?\ ?\")
9724 "List of escapes for characters that are problematic in links.
9725 This is the list that is used before handing over to the browser.")
9727 (defun org-link-escape (text &optional table merge)
9728 "Return percent escaped representation of TEXT.
9729 TEXT is a string with the text to escape.
9730 Optional argument TABLE is a list with characters that should be
9731 escaped. When nil, `org-link-escape-chars' is used.
9732 If optional argument MERGE is set, merge TABLE into
9733 `org-link-escape-chars'."
9734 (cond
9735 ((and table merge)
9736 (mapc (lambda (defchr)
9737 (unless (member defchr table)
9738 (setq table (cons defchr table)))) org-link-escape-chars))
9739 ((null table)
9740 (setq table org-link-escape-chars)))
9741 (mapconcat
9742 (lambda (char)
9743 (if (or (member char table)
9744 (and (or (< char 32) (= char 37) (> char 126))
9745 org-url-hexify-p))
9746 (mapconcat (lambda (sequence-element)
9747 (format "%%%.2X" sequence-element))
9748 (or (encode-coding-char char 'utf-8)
9749 (error "Unable to percent escape character: %s"
9750 (char-to-string char))) "")
9751 (char-to-string char))) text ""))
9753 (defun org-link-unescape (str)
9754 "Unhex hexified Unicode strings as returned from the JavaScript function
9755 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9756 (unless (and (null str) (string= "" str))
9757 (let ((pos 0) (case-fold-search t) unhexed)
9758 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9759 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9760 (setq str (replace-match unhexed t t str))
9761 (setq pos (+ pos (length unhexed))))))
9762 str)
9764 (defun org-link-unescape-compound (hex)
9765 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9766 Note: this function also decodes single byte encodings like
9767 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9768 (save-match-data
9769 (let* ((bytes (cdr (split-string hex "%")))
9770 (ret "")
9771 (eat 0)
9772 (sum 0))
9773 (while bytes
9774 (let* ((val (string-to-number (pop bytes) 16))
9775 (shift-xor
9776 (if (= 0 eat)
9777 (cond
9778 ((>= val 252) (cons 6 252))
9779 ((>= val 248) (cons 5 248))
9780 ((>= val 240) (cons 4 240))
9781 ((>= val 224) (cons 3 224))
9782 ((>= val 192) (cons 2 192))
9783 (t (cons 0 0)))
9784 (cons 6 128))))
9785 (if (>= val 192) (setq eat (car shift-xor)))
9786 (setq val (logxor val (cdr shift-xor)))
9787 (setq sum (+ (lsh sum (car shift-xor)) val))
9788 (if (> eat 0) (setq eat (- eat 1)))
9789 (cond
9790 ((= 0 eat) ;multi byte
9791 (setq ret (concat ret (org-char-to-string sum)))
9792 (setq sum 0))
9793 ((not bytes) ; single byte(s)
9794 (setq ret (org-link-unescape-single-byte-sequence hex))))
9795 )) ;; end (while bytes
9796 ret )))
9798 (defun org-link-unescape-single-byte-sequence (hex)
9799 "Unhexify hex-encoded single byte character sequences."
9800 (mapconcat (lambda (byte)
9801 (char-to-string (string-to-number byte 16)))
9802 (cdr (split-string hex "%")) ""))
9804 (defun org-xor (a b)
9805 "Exclusive or."
9806 (if a (not b) b))
9808 (defun org-fixup-message-id-for-http (s)
9809 "Replace special characters in a message id, so it can be used in an http query."
9810 (when (string-match "%" s)
9811 (setq s (mapconcat (lambda (c)
9812 (if (eq c ?%)
9813 "%25"
9814 (char-to-string c)))
9815 s "")))
9816 (while (string-match "<" s)
9817 (setq s (replace-match "%3C" t t s)))
9818 (while (string-match ">" s)
9819 (setq s (replace-match "%3E" t t s)))
9820 (while (string-match "@" s)
9821 (setq s (replace-match "%40" t t s)))
9824 (defun org-link-prettify (link)
9825 "Return a human-readable representation of LINK.
9826 The car of LINK must be a raw link the cdr of LINK must be either
9827 a link description or nil."
9828 (let ((desc (or (cadr link) "<no description>")))
9829 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9830 "<" (car link) ">")))
9832 ;;;###autoload
9833 (defun org-insert-link-global ()
9834 "Insert a link like Org-mode does.
9835 This command can be called in any mode to insert a link in Org-mode syntax."
9836 (interactive)
9837 (org-load-modules-maybe)
9838 (org-run-like-in-org-mode 'org-insert-link))
9840 (defun org-insert-all-links (&optional keep)
9841 "Insert all links in `org-stored-links'."
9842 (interactive "P")
9843 (let ((links (copy-sequence org-stored-links)) l)
9844 (while (setq l (if keep (pop links) (pop org-stored-links)))
9845 (insert "- ")
9846 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9847 (insert "\n"))))
9849 (defun org-link-fontify-links-to-this-file ()
9850 "Fontify links to the current file in `org-stored-links'."
9851 (let ((f (buffer-file-name)) a b)
9852 (setq a (mapcar (lambda(l)
9853 (let ((ll (car l)))
9854 (when (and (string-match "^file:\\(.+\\)::" ll)
9855 (equal f (expand-file-name (match-string 1 ll))))
9856 ll)))
9857 org-stored-links))
9858 (when (featurep 'org-id)
9859 (setq b (mapcar (lambda(l)
9860 (let ((ll (car l)))
9861 (when (and (string-match "^id:\\(.+\\)$" ll)
9862 (equal f (expand-file-name
9863 (or (org-id-find-id-file
9864 (match-string 1 ll)) ""))))
9865 ll)))
9866 org-stored-links)))
9867 (mapcar (lambda(l)
9868 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9869 (delq nil (append a b)))))
9871 (defvar org-link-links-in-this-file nil)
9872 (defun org-insert-link (&optional complete-file link-location default-description)
9873 "Insert a link. At the prompt, enter the link.
9875 Completion can be used to insert any of the link protocol prefixes like
9876 http or ftp in use.
9878 The history can be used to select a link previously stored with
9879 `org-store-link'. When the empty string is entered (i.e. if you just
9880 press RET at the prompt), the link defaults to the most recently
9881 stored link. As SPC triggers completion in the minibuffer, you need to
9882 use M-SPC or C-q SPC to force the insertion of a space character.
9884 You will also be prompted for a description, and if one is given, it will
9885 be displayed in the buffer instead of the link.
9887 If there is already a link at point, this command will allow you to edit link
9888 and description parts.
9890 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9891 be selected using completion. The path to the file will be relative to the
9892 current directory if the file is in the current directory or a subdirectory.
9893 Otherwise, the link will be the absolute path as completed in the minibuffer
9894 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9895 option `org-link-file-path-type'.
9897 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9898 the current directory or below.
9900 With three \\[universal-argument] prefixes, negate the meaning of
9901 `org-keep-stored-link-after-insertion'.
9903 If `org-make-link-description-function' is non-nil, this function will be
9904 called with the link target, and the result will be the default
9905 link description.
9907 If the LINK-LOCATION parameter is non-nil, this value will be
9908 used as the link location instead of reading one interactively.
9910 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9911 be used as the default description."
9912 (interactive "P")
9913 (let* ((wcf (current-window-configuration))
9914 (origbuf (current-buffer))
9915 (region (if (org-region-active-p)
9916 (buffer-substring (region-beginning) (region-end))))
9917 (remove (and region (list (region-beginning) (region-end))))
9918 (desc region)
9919 tmphist ; byte-compile incorrectly complains about this
9920 (link link-location)
9921 (abbrevs org-link-abbrev-alist-local)
9922 entry file all-prefixes auto-desc)
9923 (cond
9924 (link-location) ; specified by arg, just use it.
9925 ((org-in-regexp org-bracket-link-regexp 1)
9926 ;; We do have a link at point, and we are going to edit it.
9927 (setq remove (list (match-beginning 0) (match-end 0)))
9928 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9929 (setq link (read-string "Link: "
9930 (org-link-unescape
9931 (org-match-string-no-properties 1)))))
9932 ((or (org-in-regexp org-angle-link-re)
9933 (org-in-regexp org-plain-link-re))
9934 ;; Convert to bracket link
9935 (setq remove (list (match-beginning 0) (match-end 0))
9936 link (read-string "Link: "
9937 (org-remove-angle-brackets (match-string 0)))))
9938 ((member complete-file '((4) (16)))
9939 ;; Completing read for file names.
9940 (setq link (org-file-complete-link complete-file)))
9942 ;; Read link, with completion for stored links.
9943 (org-link-fontify-links-to-this-file)
9944 (org-switch-to-buffer-other-window "*Org Links*")
9945 (with-current-buffer "*Org Links*"
9946 (erase-buffer)
9947 (insert "Insert a link.
9948 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9949 (when org-stored-links
9950 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9951 (insert (mapconcat 'org-link-prettify
9952 (reverse org-stored-links) "\n")))
9953 (goto-char (point-min)))
9954 (let ((cw (selected-window)))
9955 (select-window (get-buffer-window "*Org Links*" 'visible))
9956 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9957 (unless (pos-visible-in-window-p (point-max))
9958 (org-fit-window-to-buffer))
9959 (and (window-live-p cw) (select-window cw)))
9960 ;; Fake a link history, containing the stored links.
9961 (setq tmphist (append (mapcar 'car org-stored-links)
9962 org-insert-link-history))
9963 (setq all-prefixes (append (mapcar 'car abbrevs)
9964 (mapcar 'car org-link-abbrev-alist)
9965 org-link-types))
9966 (unwind-protect
9967 (progn
9968 (setq link
9969 (org-completing-read
9970 "Link: "
9971 (append
9972 (mapcar (lambda (x) (concat x ":"))
9973 all-prefixes)
9974 (mapcar 'car org-stored-links))
9975 nil nil nil
9976 'tmphist
9977 (caar org-stored-links)))
9978 (if (not (string-match "\\S-" link))
9979 (user-error "No link selected"))
9980 (mapc (lambda(l)
9981 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9982 org-stored-links)
9983 (if (or (member link all-prefixes)
9984 (and (equal ":" (substring link -1))
9985 (member (substring link 0 -1) all-prefixes)
9986 (setq link (substring link 0 -1))))
9987 (setq link (with-current-buffer origbuf
9988 (org-link-try-special-completion link)))))
9989 (set-window-configuration wcf)
9990 (kill-buffer "*Org Links*"))
9991 (setq entry (assoc link org-stored-links))
9992 (or entry (push link org-insert-link-history))
9993 (setq desc (or desc (nth 1 entry)))))
9995 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9996 (not org-keep-stored-link-after-insertion))
9997 (setq org-stored-links (delq (assoc link org-stored-links)
9998 org-stored-links)))
10000 (if (string-match org-plain-link-re link)
10001 ;; URL-like link, normalize the use of angular brackets.
10002 (setq link (org-remove-angle-brackets link)))
10004 ;; Check if we are linking to the current file with a search
10005 ;; option If yes, simplify the link by using only the search
10006 ;; option.
10007 (when (and buffer-file-name
10008 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10009 (let* ((path (match-string 1 link))
10010 (case-fold-search nil)
10011 (search (match-string 2 link)))
10012 (save-match-data
10013 (if (equal (file-truename buffer-file-name) (file-truename path))
10014 ;; We are linking to this same file, with a search option
10015 (setq link search)))))
10017 ;; Check if we can/should use a relative path. If yes, simplify the link
10018 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10019 (let* ((type (match-string 1 link))
10020 (path (match-string 2 link))
10021 (origpath path)
10022 (case-fold-search nil))
10023 (cond
10024 ((or (eq org-link-file-path-type 'absolute)
10025 (equal complete-file '(16)))
10026 (setq path (abbreviate-file-name (expand-file-name path))))
10027 ((eq org-link-file-path-type 'noabbrev)
10028 (setq path (expand-file-name path)))
10029 ((eq org-link-file-path-type 'relative)
10030 (setq path (file-relative-name path)))
10032 (save-match-data
10033 (if (string-match (concat "^" (regexp-quote
10034 (expand-file-name
10035 (file-name-as-directory
10036 default-directory))))
10037 (expand-file-name path))
10038 ;; We are linking a file with relative path name.
10039 (setq path (substring (expand-file-name path)
10040 (match-end 0)))
10041 (setq path (abbreviate-file-name (expand-file-name path)))))))
10042 (setq link (concat type path))
10043 (if (equal desc origpath)
10044 (setq desc path))))
10046 (if org-make-link-description-function
10047 (setq desc
10048 (or (condition-case nil
10049 (funcall org-make-link-description-function link desc)
10050 (error (progn (message "Can't get link description from `%s'"
10051 (symbol-name org-make-link-description-function))
10052 (sit-for 2) nil)))
10053 (read-string "Description: " default-description)))
10054 (if default-description (setq desc default-description)
10055 (setq desc (or (and auto-desc desc)
10056 (read-string "Description: " desc)))))
10058 (unless (string-match "\\S-" desc) (setq desc nil))
10059 (if remove (apply 'delete-region remove))
10060 (insert (org-make-link-string link desc))))
10062 (defun org-link-try-special-completion (type)
10063 "If there is completion support for link type TYPE, offer it."
10064 (let ((fun (intern (concat "org-" type "-complete-link"))))
10065 (if (functionp fun)
10066 (funcall fun)
10067 (read-string "Link (no completion support): " (concat type ":")))))
10069 (defun org-file-complete-link (&optional arg)
10070 "Create a file link using completion."
10071 (let (file link)
10072 (setq file (org-iread-file-name "File: "))
10073 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10074 (pwd1 (file-name-as-directory (abbreviate-file-name
10075 (expand-file-name ".")))))
10076 (cond
10077 ((equal arg '(16))
10078 (setq link (concat
10079 "file:"
10080 (abbreviate-file-name (expand-file-name file)))))
10081 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10082 (setq link (concat "file:" (match-string 1 file))))
10083 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10084 (expand-file-name file))
10085 (setq link (concat
10086 "file:" (match-string 1 (expand-file-name file)))))
10087 (t (setq link (concat "file:" file)))))
10088 link))
10090 (defun org-iread-file-name (&rest args)
10091 "Read-file-name using `ido-mode' speedup if available.
10092 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10093 See `read-file-name' for a description of parameters."
10094 (org-without-partial-completion
10095 (if (and org-completion-use-ido
10096 (fboundp 'ido-read-file-name)
10097 (boundp 'ido-mode) ido-mode
10098 (listp (second args)))
10099 (let ((ido-enter-matching-directory nil))
10100 (apply 'ido-read-file-name args))
10101 (apply 'read-file-name args))))
10103 (defun org-completing-read (&rest args)
10104 "Completing-read with SPACE being a normal character."
10105 (let ((enable-recursive-minibuffers t)
10106 (minibuffer-local-completion-map
10107 (copy-keymap minibuffer-local-completion-map)))
10108 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10109 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10110 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10111 (apply 'org-icompleting-read args)))
10113 (defun org-completing-read-no-i (&rest args)
10114 (let (org-completion-use-ido org-completion-use-iswitchb)
10115 (apply 'org-completing-read args)))
10117 (defun org-iswitchb-completing-read (prompt choices &rest args)
10118 "Use iswitch as a completing-read replacement to choose from choices.
10119 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10120 from."
10121 (let* ((iswitchb-use-virtual-buffers nil)
10122 (iswitchb-make-buflist-hook
10123 (lambda ()
10124 (setq iswitchb-temp-buflist choices))))
10125 (iswitchb-read-buffer prompt)))
10127 (defun org-icompleting-read (&rest args)
10128 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10129 (org-without-partial-completion
10130 (if (and org-completion-use-ido
10131 (fboundp 'ido-completing-read)
10132 (boundp 'ido-mode) ido-mode
10133 (listp (second args)))
10134 (let ((ido-enter-matching-directory nil))
10135 (apply 'ido-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 (if (and org-completion-use-iswitchb
10141 (boundp 'iswitchb-mode) iswitchb-mode
10142 (listp (second args)))
10143 (apply 'org-iswitchb-completing-read (concat (car args))
10144 (if (consp (car (nth 1 args)))
10145 (mapcar 'car (nth 1 args))
10146 (nth 1 args))
10147 (cddr args))
10148 (apply 'completing-read args)))))
10150 (defun org-extract-attributes (s)
10151 "Extract the attributes cookie from a string and set as text property."
10152 (let (a attr (start 0) key value)
10153 (save-match-data
10154 (when (string-match "{{\\([^}]+\\)}}$" s)
10155 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10156 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10157 (setq key (match-string 1 a) value (match-string 2 a)
10158 start (match-end 0)
10159 attr (plist-put attr (intern key) value))))
10160 (org-add-props s nil 'org-attr attr))
10163 ;;; Opening/following a link
10165 (defvar org-link-search-failed nil)
10167 (defvar org-open-link-functions nil
10168 "Hook for functions finding a plain text link.
10169 These functions must take a single argument, the link content.
10170 They will be called for links that look like [[link text][description]]
10171 when LINK TEXT does not have a protocol like \"http:\" and does not look
10172 like a filename (e.g. \"./blue.png\").
10174 These functions will be called *before* Org attempts to resolve the
10175 link by doing text searches in the current buffer - so if you want a
10176 link \"[[target]]\" to still find \"<<target>>\", your function should
10177 handle this as a special case.
10179 When the function does handle the link, it must return a non-nil value.
10180 If it decides that it is not responsible for this link, it must return
10181 nil to indicate that that Org-mode can continue with other options
10182 like exact and fuzzy text search.")
10184 (defun org-next-link (&optional search-backward)
10185 "Move forward to the next link.
10186 If the link is in hidden text, expose it."
10187 (interactive "P")
10188 (when (and org-link-search-failed (eq this-command last-command))
10189 (goto-char (point-min))
10190 (message "Link search wrapped back to beginning of buffer"))
10191 (setq org-link-search-failed nil)
10192 (let* ((pos (point))
10193 (ct (org-context))
10194 (a (assoc :link ct))
10195 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10196 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10197 ((looking-at org-any-link-re)
10198 ;; Don't stay stuck at link without an org-link face
10199 (forward-char (if search-backward -1 1))))
10200 (if (funcall srch-fun org-any-link-re nil t)
10201 (progn
10202 (goto-char (match-beginning 0))
10203 (if (outline-invisible-p) (org-show-context)))
10204 (goto-char pos)
10205 (setq org-link-search-failed t)
10206 (message "No further link found"))))
10208 (defun org-previous-link ()
10209 "Move backward to the previous link.
10210 If the link is in hidden text, expose it."
10211 (interactive)
10212 (funcall 'org-next-link t))
10214 (defun org-translate-link (s)
10215 "Translate a link string if a translation function has been defined."
10216 (if (and org-link-translation-function
10217 (fboundp org-link-translation-function)
10218 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10219 (progn
10220 (setq s (funcall org-link-translation-function
10221 (match-string 1 s) (match-string 2 s)))
10222 (concat (car s) ":" (cdr s)))
10225 (defun org-translate-link-from-planner (type path)
10226 "Translate a link from Emacs Planner syntax so that Org can follow it.
10227 This is still an experimental function, your mileage may vary."
10228 (cond
10229 ((member type '("http" "https" "news" "ftp"))
10230 ;; standard Internet links are the same.
10231 nil)
10232 ((and (equal type "irc") (string-match "^//" path))
10233 ;; Planner has two / at the beginning of an irc link, we have 1.
10234 ;; We should have zero, actually....
10235 (setq path (substring path 1)))
10236 ((and (equal type "lisp") (string-match "^/" path))
10237 ;; Planner has a slash, we do not.
10238 (setq type "elisp" path (substring path 1)))
10239 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10240 ;; A typical message link. Planner has the id after the final slash,
10241 ;; we separate it with a hash mark
10242 (setq path (concat (match-string 1 path) "#"
10243 (org-remove-angle-brackets (match-string 2 path))))))
10244 (cons type path))
10246 (defun org-find-file-at-mouse (ev)
10247 "Open file link or URL at mouse."
10248 (interactive "e")
10249 (mouse-set-point ev)
10250 (org-open-at-point 'in-emacs))
10252 (defun org-open-at-mouse (ev)
10253 "Open file link or URL at mouse.
10254 See the docstring of `org-open-file' for details."
10255 (interactive "e")
10256 (mouse-set-point ev)
10257 (if (eq major-mode 'org-agenda-mode)
10258 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10259 (org-open-at-point))
10261 (defvar org-window-config-before-follow-link nil
10262 "The window configuration before following a link.
10263 This is saved in case the need arises to restore it.")
10265 (defvar org-open-link-marker (make-marker)
10266 "Marker pointing to the location where `org-open-at-point; was called.")
10268 ;;;###autoload
10269 (defun org-open-at-point-global ()
10270 "Follow a link like Org-mode does.
10271 This command can be called in any mode to follow a link that has
10272 Org-mode syntax."
10273 (interactive)
10274 (org-run-like-in-org-mode 'org-open-at-point))
10276 ;;;###autoload
10277 (defun org-open-link-from-string (s &optional arg reference-buffer)
10278 "Open a link in the string S, as if it was in Org-mode."
10279 (interactive "sLink: \nP")
10280 (let ((reference-buffer (or reference-buffer (current-buffer))))
10281 (with-temp-buffer
10282 (let ((org-inhibit-startup (not reference-buffer)))
10283 (org-mode)
10284 (insert s)
10285 (goto-char (point-min))
10286 (when reference-buffer
10287 (setq org-link-abbrev-alist-local
10288 (with-current-buffer reference-buffer
10289 org-link-abbrev-alist-local)))
10290 (org-open-at-point arg reference-buffer)))))
10292 (defvar org-open-at-point-functions nil
10293 "Hook that is run when following a link at point.
10295 Functions in this hook must return t if they identify and follow
10296 a link at point. If they don't find anything interesting at point,
10297 they must return nil.")
10299 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10300 (defun org-open-at-point (&optional arg reference-buffer)
10301 "Open link at or after point.
10302 If there is no link at point, this function will search forward up to
10303 the end of the current line.
10304 Normally, files will be opened by an appropriate application. If the
10305 optional prefix argument ARG is non-nil, Emacs will visit the file.
10306 With a double prefix argument, try to open outside of Emacs, in the
10307 application the system uses for this file type."
10308 (interactive "P")
10309 ;; if in a code block, then open the block's results
10310 (unless (call-interactively #'org-babel-open-src-block-result)
10311 (org-load-modules-maybe)
10312 (move-marker org-open-link-marker (point))
10313 (setq org-window-config-before-follow-link (current-window-configuration))
10314 (org-remove-occur-highlights nil nil t)
10315 (cond
10316 ((and (org-at-heading-p)
10317 (not (org-at-timestamp-p t))
10318 (not (org-in-regexp
10319 (concat org-plain-link-re "\\|"
10320 org-bracket-link-regexp "\\|"
10321 org-angle-link-re "\\|"
10322 "[ \t]:[^ \t\n]+:[ \t]*$")))
10323 (not (get-text-property (point) 'org-linked-text)))
10324 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10325 (lk0 (car lkall))
10326 (lk (if (stringp lk0) (list lk0) lk0))
10327 (lkend (cdr lkall)))
10328 (mapcar (lambda(l)
10329 (search-forward l nil lkend)
10330 (goto-char (match-beginning 0))
10331 (org-open-at-point))
10332 lk))
10333 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10334 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10335 ((and (org-at-timestamp-p t)
10336 (not (org-in-regexp org-bracket-link-regexp)))
10337 (org-follow-timestamp-link))
10338 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10339 (not (org-in-regexp org-any-link-re)))
10340 (org-footnote-action))
10342 (let (type path link line search (pos (point)))
10343 (catch 'match
10344 (save-excursion
10345 (skip-chars-forward "^]\n\r")
10346 (when (org-in-regexp org-bracket-link-regexp 1)
10347 (setq link (org-extract-attributes
10348 (org-link-unescape (org-match-string-no-properties 1))))
10349 (while (string-match " *\n *" link)
10350 (setq link (replace-match " " t t link)))
10351 (setq link (org-link-expand-abbrev link))
10352 (cond
10353 ((or (file-name-absolute-p link)
10354 (string-match "^\\.\\.?/" link))
10355 (setq type "file" path link))
10356 ((string-match org-link-re-with-space3 link)
10357 (setq type (match-string 1 link) path (match-string 2 link)))
10358 ((string-match "^help:+\\(.+\\)" link)
10359 (setq type "help" path (match-string 1 link)))
10360 (t (setq type "thisfile" path link)))
10361 (throw 'match t)))
10363 (when (get-text-property (point) 'org-linked-text)
10364 (setq type "thisfile"
10365 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10366 (1+ (point)) (point))
10367 path (buffer-substring
10368 (or (previous-single-property-change pos 'org-linked-text)
10369 (point-min))
10370 (or (next-single-property-change pos 'org-linked-text)
10371 (point-max)))
10372 ;; Ensure we will search for a <<<radio>>> link, not
10373 ;; a simple reference like <<ref>>
10374 path (concat "<" path))
10375 (throw 'match t))
10377 (save-excursion
10378 (when (or (org-in-regexp org-angle-link-re)
10379 (let ((match (org-in-regexp org-plain-link-re)))
10380 ;; Check a plain link is not within a bracket link
10381 (and match
10382 (save-excursion
10383 (progn
10384 (goto-char (car match))
10385 (not (org-in-regexp org-bracket-link-regexp))))))
10386 (let ((line_ending (save-excursion (end-of-line) (point))))
10387 ;; We are in a line before a plain or bracket link
10388 (or (re-search-forward org-plain-link-re line_ending t)
10389 (re-search-forward org-bracket-link-regexp line_ending t))))
10390 (setq type (match-string 1)
10391 path (org-link-unescape (match-string 2)))
10392 (throw 'match t)))
10393 (save-excursion
10394 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10395 (setq type "tags"
10396 path (match-string 1))
10397 (while (string-match ":" path)
10398 (setq path (replace-match "+" t t path)))
10399 (throw 'match t)))
10400 (when (org-in-regexp "<\\([^><\n]+\\)>")
10401 (setq type "tree-match"
10402 path (match-string 1))
10403 (throw 'match t)))
10404 (unless path
10405 (user-error "No link found"))
10407 ;; switch back to reference buffer
10408 ;; needed when if called in a temporary buffer through
10409 ;; org-open-link-from-string
10410 (with-current-buffer (or reference-buffer (current-buffer))
10412 ;; Remove any trailing spaces in path
10413 (if (string-match " +\\'" path)
10414 (setq path (replace-match "" t t path)))
10415 (if (and org-link-translation-function
10416 (fboundp org-link-translation-function))
10417 ;; Check if we need to translate the link
10418 (let ((tmp (funcall org-link-translation-function type path)))
10419 (setq type (car tmp) path (cdr tmp))))
10421 (cond
10423 ((assoc type org-link-protocols)
10424 (funcall (nth 1 (assoc type org-link-protocols)) path))
10426 ((equal type "help")
10427 (let ((f-or-v (intern path)))
10428 (cond ((fboundp f-or-v)
10429 (describe-function f-or-v))
10430 ((boundp f-or-v)
10431 (describe-variable f-or-v))
10432 (t (error "Not a known function or variable")))))
10434 ((equal type "mailto")
10435 (let ((cmd (car org-link-mailto-program))
10436 (args (cdr org-link-mailto-program)) args1
10437 (address path) (subject "") a)
10438 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10439 (setq address (match-string 1 path)
10440 subject (org-link-escape (match-string 2 path))))
10441 (while args
10442 (cond
10443 ((not (stringp (car args))) (push (pop args) args1))
10444 (t (setq a (pop args))
10445 (if (string-match "%a" a)
10446 (setq a (replace-match address t t a)))
10447 (if (string-match "%s" a)
10448 (setq a (replace-match subject t t a)))
10449 (push a args1))))
10450 (apply cmd (nreverse args1))))
10452 ((member type '("http" "https" "ftp" "news"))
10453 (browse-url
10454 (concat type ":"
10455 (if (org-string-match-p
10456 (concat "[[:nonascii:]"
10457 org-link-escape-chars-browser "]")
10458 path)
10459 (org-link-escape path org-link-escape-chars-browser)
10460 path))))
10462 ((string= type "doi")
10463 (browse-url
10464 (concat org-doi-server-url
10465 (if (org-string-match-p
10466 (concat "[[:nonascii:]"
10467 org-link-escape-chars-browser "]")
10468 path)
10469 (org-link-escape path org-link-escape-chars-browser)
10470 path))))
10472 ((member type '("message"))
10473 (browse-url (concat type ":" path)))
10475 ((string= type "tags")
10476 (org-tags-view arg path))
10478 ((string= type "tree-match")
10479 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10481 ((string= type "file")
10482 (if (string-match "::\\([0-9]+\\)\\'" path)
10483 (setq line (string-to-number (match-string 1 path))
10484 path (substring path 0 (match-beginning 0)))
10485 (if (string-match "::\\(.+\\)\\'" path)
10486 (setq search (match-string 1 path)
10487 path (substring path 0 (match-beginning 0)))))
10488 (if (string-match "[*?{]" (file-name-nondirectory path))
10489 (dired path)
10490 (org-open-file path arg line search)))
10492 ((string= type "shell")
10493 (let ((buf (generate-new-buffer "*Org Shell Output"))
10494 (cmd path))
10495 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10496 (string-match org-confirm-shell-link-not-regexp cmd))
10497 (not org-confirm-shell-link-function)
10498 (funcall org-confirm-shell-link-function
10499 (format "Execute \"%s\" in shell? "
10500 (org-add-props cmd nil
10501 'face 'org-warning))))
10502 (progn
10503 (message "Executing %s" cmd)
10504 (shell-command cmd buf)
10505 (if (featurep 'midnight)
10506 (setq clean-buffer-list-kill-buffer-names
10507 (cons buf clean-buffer-list-kill-buffer-names))))
10508 (error "Abort"))))
10510 ((string= type "elisp")
10511 (let ((cmd path))
10512 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10513 (string-match org-confirm-elisp-link-not-regexp cmd))
10514 (not org-confirm-elisp-link-function)
10515 (funcall org-confirm-elisp-link-function
10516 (format "Execute \"%s\" as elisp? "
10517 (org-add-props cmd nil
10518 'face 'org-warning))))
10519 (message "%s => %s" cmd
10520 (if (equal (string-to-char cmd) ?\()
10521 (eval (read cmd))
10522 (call-interactively (read cmd))))
10523 (error "Abort"))))
10525 ((and (string= type "thisfile")
10526 (run-hook-with-args-until-success
10527 'org-open-link-functions path)))
10529 ((string= type "thisfile")
10530 (if arg
10531 (switch-to-buffer-other-window
10532 (org-get-buffer-for-internal-link (current-buffer)))
10533 (org-mark-ring-push))
10534 (let ((cmd `(org-link-search
10535 ,path
10536 ,(cond ((equal arg '(4)) ''occur)
10537 ((equal arg '(16)) ''org-occur))
10538 ,pos)))
10539 (condition-case nil (let ((org-link-search-inhibit-query t))
10540 (eval cmd))
10541 (error (progn (widen) (eval cmd))))))
10543 (t (browse-url-at-point)))))))
10544 (move-marker org-open-link-marker nil)
10545 (run-hook-with-args 'org-follow-link-hook)))
10547 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10548 "Offer links in the current entry and return the selected link.
10549 If there is only one link, return it.
10550 If NTH is an integer, return the NTH link found.
10551 If ZERO is a string, check also this string for a link, and if
10552 there is one, return it."
10553 (with-current-buffer buffer
10554 (save-excursion
10555 (save-restriction
10556 (widen)
10557 (goto-char marker)
10558 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10559 "\\(" org-angle-link-re "\\)\\|"
10560 "\\(" org-plain-link-re "\\)"))
10561 (cnt ?0)
10562 (in-emacs (if (integerp nth) nil nth))
10563 have-zero end links link c)
10564 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10565 (push (match-string 0 zero) links)
10566 (setq cnt (1- cnt) have-zero t))
10567 (save-excursion
10568 (org-back-to-heading t)
10569 (setq end (save-excursion (outline-next-heading) (point)))
10570 (while (re-search-forward re end t)
10571 (push (match-string 0) links))
10572 (setq links (org-uniquify (reverse links))))
10573 (cond
10574 ((null links)
10575 (message "No links"))
10576 ((equal (length links) 1)
10577 (setq link (car links)))
10578 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10579 (setq link (nth (if have-zero nth (1- nth)) links)))
10580 (t ; we have to select a link
10581 (save-excursion
10582 (save-window-excursion
10583 (delete-other-windows)
10584 (with-output-to-temp-buffer "*Select Link*"
10585 (mapc (lambda (l)
10586 (if (not (string-match org-bracket-link-regexp l))
10587 (princ (format "[%c] %s\n" (incf cnt)
10588 (org-remove-angle-brackets l)))
10589 (if (match-end 3)
10590 (princ (format "[%c] %s (%s)\n" (incf cnt)
10591 (match-string 3 l) (match-string 1 l)))
10592 (princ (format "[%c] %s\n" (incf cnt)
10593 (match-string 1 l))))))
10594 links))
10595 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10596 (message "Select link to open, RET to open all:")
10597 (setq c (read-char-exclusive))
10598 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10599 (when (equal c ?q) (error "Abort"))
10600 (if (equal c ?\C-m)
10601 (setq link links)
10602 (setq nth (- c ?0))
10603 (if have-zero (setq nth (1+ nth)))
10604 (unless (and (integerp nth) (>= (length links) nth))
10605 (user-error "Invalid link selection"))
10606 (setq link (nth (1- nth) links)))))
10607 (cons link end))))))
10609 ;; Add special file links that specify the way of opening
10611 (org-add-link-type "file+sys" 'org-open-file-with-system)
10612 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10613 (defun org-open-file-with-system (path)
10614 "Open file at PATH using the system way of opening it."
10615 (org-open-file path 'system))
10616 (defun org-open-file-with-emacs (path)
10617 "Open file at PATH in Emacs."
10618 (org-open-file path 'emacs))
10621 ;;; File search
10623 (defvar org-create-file-search-functions nil
10624 "List of functions to construct the right search string for a file link.
10625 These functions are called in turn with point at the location to
10626 which the link should point.
10628 A function in the hook should first test if it would like to
10629 handle this file type, for example by checking the `major-mode'
10630 or the file extension. If it decides not to handle this file, it
10631 should just return nil to give other functions a chance. If it
10632 does handle the file, it must return the search string to be used
10633 when following the link. The search string will be part of the
10634 file link, given after a double colon, and `org-open-at-point'
10635 will automatically search for it. If special measures must be
10636 taken to make the search successful, another function should be
10637 added to the companion hook `org-execute-file-search-functions',
10638 which see.
10640 A function in this hook may also use `setq' to set the variable
10641 `description' to provide a suggestion for the descriptive text to
10642 be used for this link when it gets inserted into an Org-mode
10643 buffer with \\[org-insert-link].")
10645 (defvar org-execute-file-search-functions nil
10646 "List of functions to execute a file search triggered by a link.
10648 Functions added to this hook must accept a single argument, the
10649 search string that was part of the file link, the part after the
10650 double colon. The function must first check if it would like to
10651 handle this search, for example by checking the `major-mode' or
10652 the file extension. If it decides not to handle this search, it
10653 should just return nil to give other functions a chance. If it
10654 does handle the search, it must return a non-nil value to keep
10655 other functions from trying.
10657 Each function can access the current prefix argument through the
10658 variable `current-prefix-arg'. Note that a single prefix is used
10659 to force opening a link in Emacs, so it may be good to only use a
10660 numeric or double prefix to guide the search function.
10662 In case this is needed, a function in this hook can also restore
10663 the window configuration before `org-open-at-point' was called using:
10665 (set-window-configuration org-window-config-before-follow-link)")
10667 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10668 (defun org-link-search (s &optional type avoid-pos stealth)
10669 "Search for a link search option.
10670 If S is surrounded by forward slashes, it is interpreted as a
10671 regular expression. In org-mode files, this will create an `org-occur'
10672 sparse tree. In ordinary files, `occur' will be used to list matches.
10673 If the current buffer is in `dired-mode', grep will be used to search
10674 in all files. If AVOID-POS is given, ignore matches near that position.
10676 When optional argument STEALTH is non-nil, do not modify
10677 visibility around point, thus ignoring
10678 `org-show-hierarchy-above', `org-show-following-heading' and
10679 `org-show-siblings' variables."
10680 (let ((case-fold-search t)
10681 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10682 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10683 (append '(("") (" ") ("\t") ("\n"))
10684 org-emphasis-alist)
10685 "\\|") "\\)"))
10686 (pos (point))
10687 (pre nil) (post nil)
10688 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10689 (cond
10690 ;; First check if there are any special search functions
10691 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10692 ;; Now try the builtin stuff
10693 ((and (equal (string-to-char s0) ?#)
10694 (> (length s0) 1)
10695 (save-excursion
10696 (goto-char (point-min))
10697 (and
10698 (re-search-forward
10699 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10700 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10701 (setq type 'dedicated
10702 pos (match-beginning 0))))
10703 ;; There is an exact target for this
10704 (goto-char pos)
10705 (org-back-to-heading t)))
10706 ((save-excursion
10707 (goto-char (point-min))
10708 (and
10709 (re-search-forward
10710 (concat "<<" (regexp-quote s0) ">>") nil t)
10711 (setq type 'dedicated
10712 pos (match-beginning 0))))
10713 ;; There is an exact target for this
10714 (goto-char pos))
10715 ((save-excursion
10716 (goto-char (point-min))
10717 (and
10718 (re-search-forward
10719 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10720 (setq type 'dedicated pos (match-beginning 0))))
10721 ;; Found an element with a matching #+name affiliated keyword.
10722 (goto-char pos))
10723 ((and (string-match "^(\\(.*\\))$" s0)
10724 (save-excursion
10725 (goto-char (point-min))
10726 (and
10727 (re-search-forward
10728 (concat "[^[]" (regexp-quote
10729 (format org-coderef-label-format
10730 (match-string 1 s0))))
10731 nil t)
10732 (setq type 'dedicated
10733 pos (1+ (match-beginning 0))))))
10734 ;; There is a coderef target for this
10735 (goto-char pos))
10736 ((string-match "^/\\(.*\\)/$" s)
10737 ;; A regular expression
10738 (cond
10739 ((derived-mode-p 'org-mode)
10740 (org-occur (match-string 1 s)))
10741 (t (org-do-occur (match-string 1 s)))))
10742 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10743 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10744 (goto-char (point-min))
10745 (cond
10746 ((let (case-fold-search)
10747 (re-search-forward (format org-complex-heading-regexp-format
10748 (regexp-quote s))
10749 nil t))
10750 ;; OK, found a match
10751 (setq type 'dedicated)
10752 (goto-char (match-beginning 0)))
10753 ((and (not org-link-search-inhibit-query)
10754 (eq org-link-search-must-match-exact-headline 'query-to-create)
10755 (y-or-n-p "No match - create this as a new heading? "))
10756 (goto-char (point-max))
10757 (or (bolp) (newline))
10758 (insert "* " s "\n")
10759 (beginning-of-line 0))
10761 (goto-char pos)
10762 (error "No match"))))
10764 ;; A normal search string
10765 (when (equal (string-to-char s) ?*)
10766 ;; Anchor on headlines, post may include tags.
10767 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10768 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10769 s (substring s 1)))
10770 (remove-text-properties
10771 0 (length s)
10772 '(face nil mouse-face nil keymap nil fontified nil) s)
10773 ;; Make a series of regular expressions to find a match
10774 (setq words (org-split-string s "[ \n\r\t]+")
10776 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10777 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10778 "\\)" markers)
10779 re2a_ (concat "\\(" (mapconcat 'downcase words
10780 "[ \t\r\n]+") "\\)[ \t\r\n]")
10781 re2a (concat "[ \t\r\n]" re2a_)
10782 re4_ (concat "\\(" (mapconcat 'downcase words
10783 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10784 re4 (concat "[^a-zA-Z_]" re4_)
10786 re1 (concat pre re2 post)
10787 re3 (concat pre (if pre re4_ re4) post)
10788 re5 (concat pre ".*" re4)
10789 re2 (concat pre re2)
10790 re2a (concat pre (if pre re2a_ re2a))
10791 re4 (concat pre (if pre re4_ re4))
10792 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10793 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10794 re5 "\\)"))
10795 (cond
10796 ((eq type 'org-occur) (org-occur reall))
10797 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10798 (t (goto-char (point-min))
10799 (setq type 'fuzzy)
10800 (if (or (and (org-search-not-self 1 re0 nil t)
10801 (setq type 'dedicated))
10802 (org-search-not-self 1 re1 nil t)
10803 (org-search-not-self 1 re2 nil t)
10804 (org-search-not-self 1 re2a nil t)
10805 (org-search-not-self 1 re3 nil t)
10806 (org-search-not-self 1 re4 nil t)
10807 (org-search-not-self 1 re5 nil t))
10808 (goto-char (match-beginning 1))
10809 (goto-char pos)
10810 (error "No match"))))))
10811 (and (derived-mode-p 'org-mode)
10812 (not stealth)
10813 (org-show-context 'link-search))
10814 type))
10816 (defun org-search-not-self (group &rest args)
10817 "Execute `re-search-forward', but only accept matches that do not
10818 enclose the position of `org-open-link-marker'."
10819 (let ((m org-open-link-marker))
10820 (catch 'exit
10821 (while (apply 're-search-forward args)
10822 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10823 (goto-char (match-end group))
10824 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10825 (> (match-beginning 0) (marker-position m))
10826 (< (match-end 0) (marker-position m)))
10827 (save-match-data
10828 (or (not (org-in-regexp
10829 org-bracket-link-analytic-regexp 1))
10830 (not (match-end 4)) ; no description
10831 (and (<= (match-beginning 4) (point))
10832 (>= (match-end 4) (point))))))
10833 (throw 'exit (point))))))))
10835 (defun org-get-buffer-for-internal-link (buffer)
10836 "Return a buffer to be used for displaying the link target of internal links."
10837 (cond
10838 ((not org-display-internal-link-with-indirect-buffer)
10839 buffer)
10840 ((string-match "(Clone)$" (buffer-name buffer))
10841 (message "Buffer is already a clone, not making another one")
10842 ;; we also do not modify visibility in this case
10843 buffer)
10844 (t ; make a new indirect buffer for displaying the link
10845 (let* ((bn (buffer-name buffer))
10846 (ibn (concat bn "(Clone)"))
10847 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10848 (with-current-buffer ib (org-overview))
10849 ib))))
10851 (defun org-do-occur (regexp &optional cleanup)
10852 "Call the Emacs command `occur'.
10853 If CLEANUP is non-nil, remove the printout of the regular expression
10854 in the *Occur* buffer. This is useful if the regex is long and not useful
10855 to read."
10856 (occur regexp)
10857 (when cleanup
10858 (let ((cwin (selected-window)) win beg end)
10859 (when (setq win (get-buffer-window "*Occur*"))
10860 (select-window win))
10861 (goto-char (point-min))
10862 (when (re-search-forward "match[a-z]+" nil t)
10863 (setq beg (match-end 0))
10864 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10865 (setq end (1- (match-beginning 0)))))
10866 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10867 (goto-char (point-min))
10868 (select-window cwin))))
10870 ;;; The mark ring for links jumps
10872 (defvar org-mark-ring nil
10873 "Mark ring for positions before jumps in Org-mode.")
10874 (defvar org-mark-ring-last-goto nil
10875 "Last position in the mark ring used to go back.")
10876 ;; Fill and close the ring
10877 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10878 (loop for i from 1 to org-mark-ring-length do
10879 (push (make-marker) org-mark-ring))
10880 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10881 org-mark-ring)
10883 (defun org-mark-ring-push (&optional pos buffer)
10884 "Put the current position or POS into the mark ring and rotate it."
10885 (interactive)
10886 (setq pos (or pos (point)))
10887 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10888 (move-marker (car org-mark-ring)
10889 (or pos (point))
10890 (or buffer (current-buffer)))
10891 (message "%s"
10892 (substitute-command-keys
10893 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10895 (defun org-mark-ring-goto (&optional n)
10896 "Jump to the previous position in the mark ring.
10897 With prefix arg N, jump back that many stored positions. When
10898 called several times in succession, walk through the entire ring.
10899 Org-mode commands jumping to a different position in the current file,
10900 or to another Org-mode file, automatically push the old position
10901 onto the ring."
10902 (interactive "p")
10903 (let (p m)
10904 (if (eq last-command this-command)
10905 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10906 (setq p org-mark-ring))
10907 (setq org-mark-ring-last-goto p)
10908 (setq m (car p))
10909 (org-pop-to-buffer-same-window (marker-buffer m))
10910 (goto-char m)
10911 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10913 (defun org-remove-angle-brackets (s)
10914 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10915 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10917 (defun org-add-angle-brackets (s)
10918 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10919 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10921 (defun org-remove-double-quotes (s)
10922 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10923 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10926 ;;; Following specific links
10928 (defun org-follow-timestamp-link ()
10929 "Open an agenda view for the time-stamp date/range at point."
10930 (cond
10931 ((org-at-date-range-p t)
10932 (let ((org-agenda-start-on-weekday)
10933 (t1 (match-string 1))
10934 (t2 (match-string 2)) tt1 tt2)
10935 (setq tt1 (time-to-days (org-time-string-to-time t1))
10936 tt2 (time-to-days (org-time-string-to-time t2)))
10937 (let ((org-agenda-buffer-tmp-name
10938 (format "*Org Agenda(a:%s)"
10939 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10940 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10941 ((org-at-timestamp-p t)
10942 (let ((org-agenda-buffer-tmp-name
10943 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10944 (org-agenda-list nil (time-to-days (org-time-string-to-time
10945 (substring (match-string 1) 0 10)))
10946 1)))
10947 (t (error "This should not happen"))))
10950 ;;; Following file links
10951 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10952 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10953 (declare-function mailcap-mime-info
10954 "mailcap" (string &optional request no-decode))
10955 (defvar org-wait nil)
10956 (defun org-open-file (path &optional in-emacs line search)
10957 "Open the file at PATH.
10958 First, this expands any special file name abbreviations. Then the
10959 configuration variable `org-file-apps' is checked if it contains an
10960 entry for this file type, and if yes, the corresponding command is launched.
10962 If no application is found, Emacs simply visits the file.
10964 With optional prefix argument IN-EMACS, Emacs will visit the file.
10965 With a double \\[universal-argument] \\[universal-argument] \
10966 prefix arg, Org tries to avoid opening in Emacs
10967 and to use an external application to visit the file.
10969 Optional LINE specifies a line to go to, optional SEARCH a string
10970 to search for. If LINE or SEARCH is given, the file will be
10971 opened in Emacs, unless an entry from org-file-apps that makes
10972 use of groups in a regexp matches.
10974 If you want to change the way frames are used when following a
10975 link, please customize `org-link-frame-setup'.
10977 If the file does not exist, an error is thrown."
10978 (let* ((file (if (equal path "")
10979 buffer-file-name
10980 (substitute-in-file-name (expand-file-name path))))
10981 (file-apps (append org-file-apps (org-default-apps)))
10982 (apps (org-remove-if
10983 'org-file-apps-entry-match-against-dlink-p file-apps))
10984 (apps-dlink (org-remove-if-not
10985 'org-file-apps-entry-match-against-dlink-p file-apps))
10986 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10987 (dirp (if remp nil (file-directory-p file)))
10988 (file (if (and dirp org-open-directory-means-index-dot-org)
10989 (concat (file-name-as-directory file) "index.org")
10990 file))
10991 (a-m-a-p (assq 'auto-mode apps))
10992 (dfile (downcase file))
10993 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10994 (link (cond ((and (eq line nil)
10995 (eq search nil))
10996 file)
10997 (line
10998 (concat file "::" (number-to-string line)))
10999 (search
11000 (concat file "::" search))))
11001 (dlink (downcase link))
11002 (old-buffer (current-buffer))
11003 (old-pos (point))
11004 (old-mode major-mode)
11005 ext cmd link-match-data)
11006 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11007 (setq ext (match-string 1 dfile))
11008 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11009 (setq ext (match-string 1 dfile))))
11010 (cond
11011 ((member in-emacs '((16) system))
11012 (setq cmd (cdr (assoc 'system apps))))
11013 (in-emacs (setq cmd 'emacs))
11015 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11016 (and dirp (cdr (assoc 'directory apps)))
11017 ; first, try matching against apps-dlink
11018 ; if we get a match here, store the match data for later
11019 (let ((match (assoc-default dlink apps-dlink
11020 'string-match)))
11021 (if match
11022 (progn (setq link-match-data (match-data))
11023 match)
11024 (progn (setq in-emacs (or in-emacs line search))
11025 nil))) ; if we have no match in apps-dlink,
11026 ; always open the file in emacs if line or search
11027 ; is given (for backwards compatibility)
11028 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11029 'string-match)
11030 (cdr (assoc ext apps))
11031 (cdr (assoc t apps))))))
11032 (when (eq cmd 'system)
11033 (setq cmd (cdr (assoc 'system apps))))
11034 (when (eq cmd 'default)
11035 (setq cmd (cdr (assoc t apps))))
11036 (when (eq cmd 'mailcap)
11037 (require 'mailcap)
11038 (mailcap-parse-mailcaps)
11039 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11040 (command (mailcap-mime-info mime-type)))
11041 (if (stringp command)
11042 (setq cmd command)
11043 (setq cmd 'emacs))))
11044 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11045 (not (file-exists-p file))
11046 (not org-open-non-existing-files))
11047 (user-error "No such file: %s" file))
11048 (cond
11049 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11050 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11051 (while (string-match "['\"]%s['\"]" cmd)
11052 (setq cmd (replace-match "%s" t t cmd)))
11053 (while (string-match "%s" cmd)
11054 (setq cmd (replace-match
11055 (save-match-data
11056 (shell-quote-argument
11057 (convert-standard-filename file)))
11058 t t cmd)))
11060 ;; Replace "%1", "%2" etc. in command with group matches from regex
11061 (save-match-data
11062 (let ((match-index 1)
11063 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11064 (set-match-data link-match-data)
11065 (while (<= match-index number-of-groups)
11066 (let ((regex (concat "%" (number-to-string match-index)))
11067 (replace-with (match-string match-index dlink)))
11068 (while (string-match regex cmd)
11069 (setq cmd (replace-match replace-with t t cmd))))
11070 (setq match-index (+ match-index 1)))))
11072 (save-window-excursion
11073 (message "Running %s...done" cmd)
11074 (start-process-shell-command cmd nil cmd)
11075 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11076 ((or (stringp cmd)
11077 (eq cmd 'emacs))
11078 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11079 (widen)
11080 (if line (org-goto-line line)
11081 (if search (org-link-search search))))
11082 ((consp cmd)
11083 (let ((file (convert-standard-filename file)))
11084 (save-match-data
11085 (set-match-data link-match-data)
11086 (eval cmd))))
11087 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11088 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11089 (or (not (equal old-buffer (current-buffer)))
11090 (not (equal old-pos (point))))
11091 (org-mark-ring-push old-pos old-buffer))))
11093 (defun org-file-apps-entry-match-against-dlink-p (entry)
11094 "This function returns non-nil if `entry' uses a regular
11095 expression which should be matched against the whole link by
11096 org-open-file.
11098 It assumes that is the case when the entry uses a regular
11099 expression which has at least one grouping construct and the
11100 action is either a lisp form or a command string containing
11101 '%1', i.e. using at least one subexpression match as a
11102 parameter."
11103 (let ((selector (car entry))
11104 (action (cdr entry)))
11105 (if (stringp selector)
11106 (and (> (regexp-opt-depth selector) 0)
11107 (or (and (stringp action)
11108 (string-match "%[0-9]" action))
11109 (consp action)))
11110 nil)))
11112 (defun org-default-apps ()
11113 "Return the default applications for this operating system."
11114 (cond
11115 ((eq system-type 'darwin)
11116 org-file-apps-defaults-macosx)
11117 ((eq system-type 'windows-nt)
11118 org-file-apps-defaults-windowsnt)
11119 (t org-file-apps-defaults-gnu)))
11121 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11122 "Convert extensions to regular expressions in the cars of LIST.
11123 Also, weed out any non-string entries, because the return value is used
11124 only for regexp matching.
11125 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11126 point to the symbol `emacs', indicating that the file should
11127 be opened in Emacs."
11128 (append
11129 (delq nil
11130 (mapcar (lambda (x)
11131 (if (not (stringp (car x)))
11133 (if (string-match "\\W" (car x))
11135 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11136 list))
11137 (if add-auto-mode
11138 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11140 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11141 (defun org-file-remote-p (file)
11142 "Test whether FILE specifies a location on a remote system.
11143 Return non-nil if the location is indeed remote.
11145 For example, the filename \"/user@host:/foo\" specifies a location
11146 on the system \"/user@host:\"."
11147 (cond ((fboundp 'file-remote-p)
11148 (file-remote-p file))
11149 ((fboundp 'tramp-handle-file-remote-p)
11150 (tramp-handle-file-remote-p file))
11151 ((and (boundp 'ange-ftp-name-format)
11152 (string-match (car ange-ftp-name-format) file))
11153 t)))
11156 ;;;; Refiling
11158 (defun org-get-org-file ()
11159 "Read a filename, with default directory `org-directory'."
11160 (let ((default (or org-default-notes-file remember-data-file)))
11161 (read-file-name (format "File name [%s]: " default)
11162 (file-name-as-directory org-directory)
11163 default)))
11165 (defun org-notes-order-reversed-p ()
11166 "Check if the current file should receive notes in reversed order."
11167 (cond
11168 ((not org-reverse-note-order) nil)
11169 ((eq t org-reverse-note-order) t)
11170 ((not (listp org-reverse-note-order)) nil)
11171 (t (catch 'exit
11172 (let ((all org-reverse-note-order)
11173 entry)
11174 (while (setq entry (pop all))
11175 (if (string-match (car entry) buffer-file-name)
11176 (throw 'exit (cdr entry))))
11177 nil)))))
11179 (defvar org-refile-target-table nil
11180 "The list of refile targets, created by `org-refile'.")
11182 (defvar org-agenda-new-buffers nil
11183 "Buffers created to visit agenda files.")
11185 (defvar org-refile-cache nil
11186 "Cache for refile targets.")
11188 (defvar org-refile-markers nil
11189 "All the markers used for caching refile locations.")
11191 (defun org-refile-marker (pos)
11192 "Get a new refile marker, but only if caching is in use."
11193 (if (not org-refile-use-cache)
11195 (let ((m (make-marker)))
11196 (move-marker m pos)
11197 (push m org-refile-markers)
11198 m)))
11200 (defun org-refile-cache-clear ()
11201 "Clear the refile cache and disable all the markers."
11202 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11203 (setq org-refile-markers nil)
11204 (setq org-refile-cache nil)
11205 (message "Refile cache has been cleared"))
11207 (defun org-refile-cache-check-set (set)
11208 "Check if all the markers in the cache still have live buffers."
11209 (let (marker)
11210 (catch 'exit
11211 (while (and set (setq marker (nth 3 (pop set))))
11212 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11213 (when (and marker (null (marker-buffer marker)))
11214 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11215 (sit-for 3)
11216 (throw 'exit nil)))
11217 t)))
11219 (defun org-refile-cache-put (set &rest identifiers)
11220 "Push the refile targets SET into the cache, under IDENTIFIERS."
11221 (let* ((key (sha1 (prin1-to-string identifiers)))
11222 (entry (assoc key org-refile-cache)))
11223 (if entry
11224 (setcdr entry set)
11225 (push (cons key set) org-refile-cache))))
11227 (defun org-refile-cache-get (&rest identifiers)
11228 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11229 (cond
11230 ((not org-refile-cache) nil)
11231 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11233 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11234 org-refile-cache))))
11235 (and set (org-refile-cache-check-set set) set)))))
11237 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11238 "Produce a table with refile targets."
11239 (let ((case-fold-search nil)
11240 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11241 (entries (or org-refile-targets '((nil . (:level . 1)))))
11242 targets tgs txt re files f desc descre fast-path-p level pos0)
11243 (message "Getting targets...")
11244 (with-current-buffer (or default-buffer (current-buffer))
11245 (while (setq entry (pop entries))
11246 (setq files (car entry) desc (cdr entry))
11247 (setq fast-path-p nil)
11248 (cond
11249 ((null files) (setq files (list (current-buffer))))
11250 ((eq files 'org-agenda-files)
11251 (setq files (org-agenda-files 'unrestricted)))
11252 ((and (symbolp files) (fboundp files))
11253 (setq files (funcall files)))
11254 ((and (symbolp files) (boundp files))
11255 (setq files (symbol-value files))))
11256 (if (stringp files) (setq files (list files)))
11257 (cond
11258 ((eq (car desc) :tag)
11259 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11260 ((eq (car desc) :todo)
11261 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11262 ((eq (car desc) :regexp)
11263 (setq descre (cdr desc)))
11264 ((eq (car desc) :level)
11265 (setq descre (concat "^\\*\\{" (number-to-string
11266 (if org-odd-levels-only
11267 (1- (* 2 (cdr desc)))
11268 (cdr desc)))
11269 "\\}[ \t]")))
11270 ((eq (car desc) :maxlevel)
11271 (setq fast-path-p t)
11272 (setq descre (concat "^\\*\\{1," (number-to-string
11273 (if org-odd-levels-only
11274 (1- (* 2 (cdr desc)))
11275 (cdr desc)))
11276 "\\}[ \t]")))
11277 (t (error "Bad refiling target description %s" desc)))
11278 (while (setq f (pop files))
11279 (with-current-buffer
11280 (if (bufferp f) f (org-get-agenda-file-buffer f))
11282 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11283 (progn
11284 (if (bufferp f) (setq f (buffer-file-name
11285 (buffer-base-buffer f))))
11286 (setq f (and f (expand-file-name f)))
11287 (if (eq org-refile-use-outline-path 'file)
11288 (push (list (file-name-nondirectory f) f nil nil) tgs))
11289 (save-excursion
11290 (save-restriction
11291 (widen)
11292 (goto-char (point-min))
11293 (while (re-search-forward descre nil t)
11294 (goto-char (setq pos0 (point-at-bol)))
11295 (catch 'next
11296 (when org-refile-target-verify-function
11297 (save-match-data
11298 (or (funcall org-refile-target-verify-function)
11299 (throw 'next t))))
11300 (when (and (looking-at org-complex-heading-regexp)
11301 (not (member (match-string 4) excluded-entries))
11302 (match-string 4))
11303 (setq level (org-reduced-level
11304 (- (match-end 1) (match-beginning 1)))
11305 txt (org-link-display-format (match-string 4))
11306 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11307 re (format org-complex-heading-regexp-format
11308 (regexp-quote (match-string 4))))
11309 (when org-refile-use-outline-path
11310 (setq txt (mapconcat
11311 'org-protect-slash
11312 (append
11313 (if (eq org-refile-use-outline-path
11314 'file)
11315 (list (file-name-nondirectory
11316 (buffer-file-name
11317 (buffer-base-buffer))))
11318 (if (eq org-refile-use-outline-path
11319 'full-file-path)
11320 (list (buffer-file-name
11321 (buffer-base-buffer)))))
11322 (org-get-outline-path fast-path-p
11323 level txt)
11324 (list txt))
11325 "/")))
11326 (push (list txt f re (org-refile-marker (point)))
11327 tgs)))
11328 (when (= (point) pos0)
11329 ;; verification function has not moved point
11330 (goto-char (point-at-eol))))))))
11331 (when org-refile-use-cache
11332 (org-refile-cache-put tgs (buffer-file-name) descre))
11333 (setq targets (append tgs targets))))))
11334 (message "Getting targets...done")
11335 (nreverse targets)))
11337 (defun org-protect-slash (s)
11338 (while (string-match "/" s)
11339 (setq s (replace-match "\\" t t s)))
11342 (defvar org-olpa (make-vector 20 nil))
11344 (defun org-get-outline-path (&optional fastp level heading)
11345 "Return the outline path to the current entry, as a list.
11347 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11348 routine which makes outline path derivations for an entire file,
11349 avoiding backtracing. Refile target collection makes use of that."
11350 (if fastp
11351 (progn
11352 (if (> level 19)
11353 (error "Outline path failure, more than 19 levels"))
11354 (loop for i from level upto 19 do
11355 (aset org-olpa i nil))
11356 (prog1
11357 (delq nil (append org-olpa nil))
11358 (aset org-olpa level heading)))
11359 (let (rtn case-fold-search)
11360 (save-excursion
11361 (save-restriction
11362 (widen)
11363 (while (org-up-heading-safe)
11364 (when (looking-at org-complex-heading-regexp)
11365 (push (org-trim
11366 (replace-regexp-in-string
11367 ;; Remove statistical/checkboxes cookies
11368 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11369 (org-match-string-no-properties 4)))
11370 rtn)))
11371 rtn)))))
11373 (defun org-format-outline-path (path &optional width prefix separator)
11374 "Format the outline path PATH for display.
11375 WIDTH is the maximum number of characters that is available.
11376 PREFIX is a prefix to be included in the returned string,
11377 such as the file name.
11378 SEPARATOR is inserted between the different parts of the path,
11379 the default is \"/\"."
11380 (setq width (or width 79))
11381 (if prefix (setq width (- width (length prefix))))
11382 (if (not path)
11383 (or prefix "")
11384 (let* ((nsteps (length path))
11385 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11386 (maxwidth (if (<= total-width width)
11387 10000 ;; everything fits
11388 ;; we need to shorten the level headings
11389 (/ (- width nsteps) nsteps)))
11390 (org-odd-levels-only nil)
11391 (n 0)
11392 (total (1+ (length prefix))))
11393 (setq maxwidth (max maxwidth 10))
11394 (concat prefix
11395 (if prefix (or separator "/"))
11396 (mapconcat
11397 (lambda (h)
11398 (setq n (1+ n))
11399 (if (and (= n nsteps) (< maxwidth 10000))
11400 (setq maxwidth (- total-width total)))
11401 (if (< (length h) maxwidth)
11402 (progn (setq total (+ total (length h) 1)) h)
11403 (setq h (substring h 0 (- maxwidth 2))
11404 total (+ total maxwidth 1))
11405 (if (string-match "[ \t]+\\'" h)
11406 (setq h (substring h 0 (match-beginning 0))))
11407 (setq h (concat h "..")))
11408 (org-add-props h nil 'face
11409 (nth (% (1- n) org-n-level-faces)
11410 org-level-faces))
11412 path (or separator "/"))))))
11414 (defun org-display-outline-path (&optional file current separator just-return-string)
11415 "Display the current outline path in the echo area.
11417 If FILE is non-nil, prepend the output with the file name.
11418 If CURRENT is non-nil, append the current heading to the output.
11419 SEPARATOR is passed through to `org-format-outline-path'. It separates
11420 the different parts of the path and defaults to \"/\".
11421 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11422 (interactive "P")
11423 (let* (case-fold-search
11424 message-log-max ; Don't populate the *Messages* buffer
11425 (bfn (buffer-file-name (buffer-base-buffer)))
11426 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11427 res)
11428 (if current (setq path (append path
11429 (save-excursion
11430 (org-back-to-heading t)
11431 (if (looking-at org-complex-heading-regexp)
11432 (list (match-string 4)))))))
11433 (setq res
11434 (org-format-outline-path
11435 path
11436 (1- (frame-width))
11437 (and file bfn (concat (file-name-nondirectory bfn) separator))
11438 separator))
11439 (if just-return-string
11440 (org-no-properties res)
11441 (message "%s" res))))
11443 (defvar org-refile-history nil
11444 "History for refiling operations.")
11446 (defvar org-after-refile-insert-hook nil
11447 "Hook run after `org-refile' has inserted its stuff at the new location.
11448 Note that this is still *before* the stuff will be removed from
11449 the *old* location.")
11451 (defvar org-capture-last-stored-marker)
11452 (defvar org-refile-keep nil
11453 "Non-nil means `org-refile' will copy instead of refile.")
11455 (defun org-copy ()
11456 "Like `org-refile', but copy."
11457 (interactive)
11458 (let ((org-refile-keep t))
11459 (funcall 'org-refile nil nil nil "Copy")))
11461 (defun org-refile (&optional goto default-buffer rfloc msg)
11462 "Move the entry or entries at point to another heading.
11463 The list of target headings is compiled using the information in
11464 `org-refile-targets', which see.
11466 At the target location, the entry is filed as a subitem of the target
11467 heading. Depending on `org-reverse-note-order', the new subitem will
11468 either be the first or the last subitem.
11470 If there is an active region, all entries in that region will be moved.
11471 However, the region must fulfill the requirement that the first heading
11472 is the first one sets the top-level of the moved text - at most siblings
11473 below it are allowed.
11475 With prefix arg GOTO, the command will only visit the target location
11476 and not actually move anything.
11478 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11479 go to the location where the last refiling operation has put the subtree.
11480 With a prefix argument of `2', refile to the running clock.
11482 RFLOC can be a refile location obtained in a different way.
11484 MSG is a string to replace \"Refile\" in the default prompt with
11485 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11487 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11489 If you are using target caching (see `org-refile-use-cache'),
11490 you have to clear the target cache in order to find new targets.
11491 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11492 prefix argument (`C-u C-u C-u C-c C-w')."
11494 (interactive "P")
11495 (if (member goto '(0 (64)))
11496 (org-refile-cache-clear)
11497 (let* ((actionmsg (or msg "Refile"))
11498 (cbuf (current-buffer))
11499 (regionp (org-region-active-p))
11500 (region-start (and regionp (region-beginning)))
11501 (region-end (and regionp (region-end)))
11502 (region-length (and regionp (- region-end region-start)))
11503 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11504 pos it nbuf file re level reversed)
11505 (setq last-command nil)
11506 (when regionp
11507 (goto-char region-start)
11508 (or (bolp) (goto-char (point-at-bol)))
11509 (setq region-start (point))
11510 (unless (or (org-kill-is-subtree-p
11511 (buffer-substring region-start region-end))
11512 (prog1 org-refile-active-region-within-subtree
11513 (org-toggle-heading)))
11514 (user-error "The region is not a (sequence of) subtree(s)")))
11515 (if (equal goto '(16))
11516 (org-refile-goto-last-stored)
11517 (when (or
11518 (and (equal goto 2)
11519 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11520 (prog1
11521 (setq it (list (or org-clock-heading "running clock")
11522 (buffer-file-name
11523 (marker-buffer org-clock-hd-marker))
11525 (marker-position org-clock-hd-marker)))
11526 (setq goto nil)))
11527 (setq it (or rfloc
11528 (let (heading-text)
11529 (save-excursion
11530 (unless goto
11531 (org-back-to-heading t)
11532 (setq heading-text
11533 (nth 4 (org-heading-components))))
11535 (org-refile-get-location
11536 (cond (goto "Goto")
11537 (regionp (concat actionmsg " region to"))
11538 (t (concat actionmsg " subtree \""
11539 heading-text "\" to")))
11540 default-buffer
11541 (and (not (equal '(4) goto))
11542 org-refile-allow-creating-parent-nodes)
11543 goto))))))
11544 (setq file (nth 1 it)
11545 re (nth 2 it)
11546 pos (nth 3 it))
11547 (if (and (not goto)
11549 (equal (buffer-file-name) file)
11550 (if regionp
11551 (and (>= pos region-start)
11552 (<= pos region-end))
11553 (and (>= pos (point))
11554 (< pos (save-excursion
11555 (org-end-of-subtree t t))))))
11556 (error "Cannot refile to position inside the tree or region"))
11558 (setq nbuf (or (find-buffer-visiting file)
11559 (find-file-noselect file)))
11560 (if goto
11561 (progn
11562 (org-pop-to-buffer-same-window nbuf)
11563 (goto-char pos)
11564 (org-show-context 'org-goto))
11565 (if regionp
11566 (progn
11567 (org-kill-new (buffer-substring region-start region-end))
11568 (org-save-markers-in-region region-start region-end))
11569 (org-copy-subtree 1 nil t))
11570 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11571 (find-file-noselect file)))
11572 (setq reversed (org-notes-order-reversed-p))
11573 (save-excursion
11574 (save-restriction
11575 (widen)
11576 (if pos
11577 (progn
11578 (goto-char pos)
11579 (looking-at org-outline-regexp)
11580 (setq level (org-get-valid-level (funcall outline-level) 1))
11581 (goto-char
11582 (if reversed
11583 (or (outline-next-heading) (point-max))
11584 (or (save-excursion (org-get-next-sibling))
11585 (org-end-of-subtree t t)
11586 (point-max)))))
11587 (setq level 1)
11588 (if (not reversed)
11589 (goto-char (point-max))
11590 (goto-char (point-min))
11591 (or (outline-next-heading) (goto-char (point-max)))))
11592 (if (not (bolp)) (newline))
11593 (org-paste-subtree level)
11594 (when org-log-refile
11595 (org-add-log-setup 'refile nil nil 'findpos
11596 org-log-refile)
11597 (unless (eq org-log-refile 'note)
11598 (save-excursion (org-add-log-note))))
11599 (and org-auto-align-tags
11600 (let ((org-loop-over-headlines-in-active-region nil))
11601 (org-set-tags nil t)))
11602 (with-demoted-errors
11603 (bookmark-set "org-refile-last-stored"))
11604 ;; If we are refiling for capture, make sure that the
11605 ;; last-capture pointers point here
11606 (when (org-bound-and-true-p org-refile-for-capture)
11607 (with-demoted-errors
11608 (bookmark-set "org-capture-last-stored-marker"))
11609 (move-marker org-capture-last-stored-marker (point)))
11610 (if (fboundp 'deactivate-mark) (deactivate-mark))
11611 (run-hooks 'org-after-refile-insert-hook))))
11612 (unless org-refile-keep
11613 (if regionp
11614 (delete-region (point) (+ (point) region-length))
11615 (org-cut-subtree)))
11616 (when (featurep 'org-inlinetask)
11617 (org-inlinetask-remove-END-maybe))
11618 (setq org-markers-to-move nil)
11619 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11621 (defun org-refile-goto-last-stored ()
11622 "Go to the location where the last refile was stored."
11623 (interactive)
11624 (bookmark-jump "org-refile-last-stored")
11625 (message "This is the location of the last refile"))
11627 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11628 no-exclude)
11629 "Prompt the user for a refile location, using PROMPT.
11630 PROMPT should not be suffixed with a colon and a space, because
11631 this function appends the default value from
11632 `org-refile-history' automatically, if that is not empty.
11633 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11634 this is used for the GOTO interface."
11635 (let ((org-refile-targets org-refile-targets)
11636 (org-refile-use-outline-path org-refile-use-outline-path)
11637 excluded-entries)
11638 (when (and (derived-mode-p 'org-mode)
11639 (not org-refile-use-cache)
11640 (not no-exclude))
11641 (org-map-tree
11642 (lambda()
11643 (setq excluded-entries
11644 (append excluded-entries (list (org-get-heading t t)))))))
11645 (setq org-refile-target-table
11646 (org-refile-get-targets default-buffer excluded-entries)))
11647 (unless org-refile-target-table
11648 (user-error "No refile targets"))
11649 (let* ((cbuf (current-buffer))
11650 (partial-completion-mode nil)
11651 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11652 (cfunc (if (and org-refile-use-outline-path
11653 org-outline-path-complete-in-steps)
11654 'org-olpath-completing-read
11655 'org-icompleting-read))
11656 (extra (if org-refile-use-outline-path "/" ""))
11657 (cbnex (concat (buffer-name) extra))
11658 (filename (and cfn (expand-file-name cfn)))
11659 (tbl (mapcar
11660 (lambda (x)
11661 (if (and (not (member org-refile-use-outline-path
11662 '(file full-file-path)))
11663 (not (equal filename (nth 1 x))))
11664 (cons (concat (car x) extra " ("
11665 (file-name-nondirectory (nth 1 x)) ")")
11666 (cdr x))
11667 (cons (concat (car x) extra) (cdr x))))
11668 org-refile-target-table))
11669 (completion-ignore-case t)
11670 cdef
11671 (prompt (concat prompt
11672 (or (and (car org-refile-history)
11673 (concat " (default " (car org-refile-history) ")"))
11674 (and (assoc cbnex tbl) (setq cdef cbnex)
11675 (concat " (default " cbnex ")"))) ": "))
11676 pa answ parent-target child parent old-hist)
11677 (setq old-hist org-refile-history)
11678 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11679 nil 'org-refile-history (or cdef (car org-refile-history))))
11680 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11681 (org-refile-check-position pa)
11682 (if pa
11683 (progn
11684 (when (or (not org-refile-history)
11685 (not (eq old-hist org-refile-history))
11686 (not (equal (car pa) (car org-refile-history))))
11687 (setq org-refile-history
11688 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11689 org-refile-history
11690 (cdr org-refile-history))))
11691 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11692 (pop org-refile-history)))
11694 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11695 (progn
11696 (setq parent (match-string 1 answ)
11697 child (match-string 2 answ))
11698 (setq parent-target (or (assoc parent tbl)
11699 (assoc (concat parent "/") tbl)))
11700 (when (and parent-target
11701 (or (eq new-nodes t)
11702 (and (eq new-nodes 'confirm)
11703 (y-or-n-p (format "Create new node \"%s\"? "
11704 child)))))
11705 (org-refile-new-child parent-target child)))
11706 (user-error "Invalid target location")))))
11708 (declare-function org-string-nw-p "org-macs" (s))
11709 (defun org-refile-check-position (refile-pointer)
11710 "Check if the refile pointer matches the headline to which it points."
11711 (let* ((file (nth 1 refile-pointer))
11712 (re (nth 2 refile-pointer))
11713 (pos (nth 3 refile-pointer))
11714 buffer)
11715 (if (and (not (markerp pos)) (not file))
11716 (user-error "Please save the buffer to a file before refiling")
11717 (when (org-string-nw-p re)
11718 (setq buffer (if (markerp pos)
11719 (marker-buffer pos)
11720 (or (find-buffer-visiting file)
11721 (find-file-noselect file))))
11722 (with-current-buffer buffer
11723 (save-excursion
11724 (save-restriction
11725 (widen)
11726 (goto-char pos)
11727 (beginning-of-line 1)
11728 (unless (org-looking-at-p re)
11729 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11731 (defun org-refile-new-child (parent-target child)
11732 "Use refile target PARENT-TARGET to add new CHILD below it."
11733 (unless parent-target
11734 (error "Cannot find parent for new node"))
11735 (let ((file (nth 1 parent-target))
11736 (pos (nth 3 parent-target))
11737 level)
11738 (with-current-buffer (or (find-buffer-visiting file)
11739 (find-file-noselect file))
11740 (save-excursion
11741 (save-restriction
11742 (widen)
11743 (if pos
11744 (goto-char pos)
11745 (goto-char (point-max))
11746 (if (not (bolp)) (newline)))
11747 (when (looking-at org-outline-regexp)
11748 (setq level (funcall outline-level))
11749 (org-end-of-subtree t t))
11750 (org-back-over-empty-lines)
11751 (insert "\n" (make-string
11752 (if pos (org-get-valid-level level 1) 1) ?*)
11753 " " child "\n")
11754 (beginning-of-line 0)
11755 (list (concat (car parent-target) "/" child) file "" (point)))))))
11757 (defun org-olpath-completing-read (prompt collection &rest args)
11758 "Read an outline path like a file name."
11759 (let ((thetable collection)
11760 (org-completion-use-ido nil) ; does not work with ido.
11761 (org-completion-use-iswitchb nil)) ; or iswitchb
11762 (apply
11763 'org-icompleting-read prompt
11764 (lambda (string predicate &optional flag)
11765 (let (rtn r f (l (length string)))
11766 (cond
11767 ((eq flag nil)
11768 ;; try completion
11769 (try-completion string thetable))
11770 ((eq flag t)
11771 ;; all-completions
11772 (setq rtn (all-completions string thetable predicate))
11773 (mapcar
11774 (lambda (x)
11775 (setq r (substring x l))
11776 (if (string-match " ([^)]*)$" x)
11777 (setq f (match-string 0 x))
11778 (setq f ""))
11779 (if (string-match "/" r)
11780 (concat string (substring r 0 (match-end 0)) f)
11782 rtn))
11783 ((eq flag 'lambda)
11784 ;; exact match?
11785 (assoc string thetable)))))
11786 args)))
11788 ;;;; Dynamic blocks
11790 (defun org-find-dblock (name)
11791 "Find the first dynamic block with name NAME in the buffer.
11792 If not found, stay at current position and return nil."
11793 (let ((case-fold-search t) pos)
11794 (save-excursion
11795 (goto-char (point-min))
11796 (setq pos (and (re-search-forward
11797 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11798 (match-beginning 0))))
11799 (if pos (goto-char pos))
11800 pos))
11802 (defconst org-dblock-start-re
11803 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11804 "Matches the start line of a dynamic block, with parameters.")
11806 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11807 "Matches the end of a dynamic block.")
11809 (defun org-create-dblock (plist)
11810 "Create a dynamic block section, with parameters taken from PLIST.
11811 PLIST must contain a :name entry which is used as name of the block."
11812 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11813 (end-of-line 1)
11814 (newline))
11815 (let ((col (current-column))
11816 (name (plist-get plist :name)))
11817 (insert "#+BEGIN: " name)
11818 (while plist
11819 (if (eq (car plist) :name)
11820 (setq plist (cddr plist))
11821 (insert " " (prin1-to-string (pop plist)))))
11822 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11823 (beginning-of-line -2)))
11825 (defun org-prepare-dblock ()
11826 "Prepare dynamic block for refresh.
11827 This empties the block, puts the cursor at the insert position and returns
11828 the property list including an extra property :name with the block name."
11829 (unless (looking-at org-dblock-start-re)
11830 (user-error "Not at a dynamic block"))
11831 (let* ((begdel (1+ (match-end 0)))
11832 (name (org-no-properties (match-string 1)))
11833 (params (append (list :name name)
11834 (read (concat "(" (match-string 3) ")")))))
11835 (save-excursion
11836 (beginning-of-line 1)
11837 (skip-chars-forward " \t")
11838 (setq params (plist-put params :indentation-column (current-column))))
11839 (unless (re-search-forward org-dblock-end-re nil t)
11840 (error "Dynamic block not terminated"))
11841 (setq params
11842 (append params
11843 (list :content (buffer-substring
11844 begdel (match-beginning 0)))))
11845 (delete-region begdel (match-beginning 0))
11846 (goto-char begdel)
11847 (open-line 1)
11848 params))
11850 (defun org-map-dblocks (&optional command)
11851 "Apply COMMAND to all dynamic blocks in the current buffer.
11852 If COMMAND is not given, use `org-update-dblock'."
11853 (let ((cmd (or command 'org-update-dblock)))
11854 (save-excursion
11855 (goto-char (point-min))
11856 (while (re-search-forward org-dblock-start-re nil t)
11857 (goto-char (match-beginning 0))
11858 (save-excursion
11859 (condition-case nil
11860 (funcall cmd)
11861 (error (message "Error during update of dynamic block"))))
11862 (unless (re-search-forward org-dblock-end-re nil t)
11863 (error "Dynamic block not terminated"))))))
11865 (defun org-dblock-update (&optional arg)
11866 "User command for updating dynamic blocks.
11867 Update the dynamic block at point. With prefix ARG, update all dynamic
11868 blocks in the buffer."
11869 (interactive "P")
11870 (if arg
11871 (org-update-all-dblocks)
11872 (or (looking-at org-dblock-start-re)
11873 (org-beginning-of-dblock))
11874 (org-update-dblock)))
11876 (defun org-update-dblock ()
11877 "Update the dynamic block at point.
11878 This means to empty the block, parse for parameters and then call
11879 the correct writing function."
11880 (interactive)
11881 (save-window-excursion
11882 (let* ((pos (point))
11883 (line (org-current-line))
11884 (params (org-prepare-dblock))
11885 (name (plist-get params :name))
11886 (indent (plist-get params :indentation-column))
11887 (cmd (intern (concat "org-dblock-write:" name))))
11888 (message "Updating dynamic block `%s' at line %d..." name line)
11889 (funcall cmd params)
11890 (message "Updating dynamic block `%s' at line %d...done" name line)
11891 (goto-char pos)
11892 (when (and indent (> indent 0))
11893 (setq indent (make-string indent ?\ ))
11894 (save-excursion
11895 (org-beginning-of-dblock)
11896 (forward-line 1)
11897 (while (not (looking-at org-dblock-end-re))
11898 (insert indent)
11899 (beginning-of-line 2))
11900 (when (looking-at org-dblock-end-re)
11901 (and (looking-at "[ \t]+")
11902 (replace-match ""))
11903 (insert indent)))))))
11905 (defun org-beginning-of-dblock ()
11906 "Find the beginning of the dynamic block at point.
11907 Error if there is no such block at point."
11908 (let ((pos (point))
11909 beg)
11910 (end-of-line 1)
11911 (if (and (re-search-backward org-dblock-start-re nil t)
11912 (setq beg (match-beginning 0))
11913 (re-search-forward org-dblock-end-re nil t)
11914 (> (match-end 0) pos))
11915 (goto-char beg)
11916 (goto-char pos)
11917 (error "Not in a dynamic block"))))
11919 (defun org-update-all-dblocks ()
11920 "Update all dynamic blocks in the buffer.
11921 This function can be used in a hook."
11922 (interactive)
11923 (when (derived-mode-p 'org-mode)
11924 (org-map-dblocks 'org-update-dblock)))
11927 ;;;; Completion
11929 (defun org-get-export-keywords ()
11930 "Return a list of all currently understood export keywords.
11931 Export keywords include options, block names, attributes and
11932 keywords relative to each registered export back-end."
11933 (delq nil
11934 (let (keywords)
11935 (mapc
11936 (lambda (back-end)
11937 (let ((props (cdr back-end)))
11938 ;; Back-end name (for keywords, like #+LATEX:)
11939 (push (upcase (symbol-name (car back-end))) keywords)
11940 ;; Back-end options.
11941 (mapc (lambda (option) (push (cadr option) keywords))
11942 (plist-get (cdr back-end) :options-alist))))
11943 (org-bound-and-true-p org-export-registered-backends))
11944 keywords)))
11946 (defconst org-options-keywords
11947 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11948 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11949 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11950 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11951 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11953 (defcustom org-structure-template-alist
11954 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11955 "<src lang=\"?\">\n\n</src>")
11956 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11957 "<example>\n?\n</example>")
11958 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11959 "<quote>\n?\n</quote>")
11960 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11961 "<verse>\n?\n</verse>")
11962 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11963 "<verbatim>\n?\n</verbatim>")
11964 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11965 "<center>\n?\n</center>")
11966 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11967 "<literal style=\"latex\">\n?\n</literal>")
11968 ("L" "#+LaTeX: "
11969 "<literal style=\"latex\">?</literal>")
11970 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11971 "<literal style=\"html\">\n?\n</literal>")
11972 ("H" "#+HTML: "
11973 "<literal style=\"html\">?</literal>")
11974 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11975 ("A" "#+ASCII: ")
11976 ("i" "#+INDEX: ?"
11977 "#+INDEX: ?")
11978 ("I" "#+INCLUDE: %file ?"
11979 "<include file=%file markup=\"?\">"))
11980 "Structure completion elements.
11981 This is a list of abbreviation keys and values. The value gets inserted
11982 if you type `<' followed by the key and then press the completion key,
11983 usually `M-TAB'. %file will be replaced by a file name after prompting
11984 for the file using completion. The cursor will be placed at the position
11985 of the `?` in the template.
11986 There are two templates for each key, the first uses the original Org syntax,
11987 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11988 the default when the /org-mtags.el/ module has been loaded. See also the
11989 variable `org-mtags-prefer-muse-templates'."
11990 :group 'org-completion
11991 :type '(repeat
11992 (string :tag "Key")
11993 (string :tag "Template")
11994 (string :tag "Muse Template")))
11996 (defun org-try-structure-completion ()
11997 "Try to complete a structure template before point.
11998 This looks for strings like \"<e\" on an otherwise empty line and
11999 expands them."
12000 (let ((l (buffer-substring (point-at-bol) (point)))
12002 (when (and (looking-at "[ \t]*$")
12003 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12004 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12005 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12006 (match-beginning 1)) a)
12007 t)))
12009 (defun org-complete-expand-structure-template (start cell)
12010 "Expand a structure template."
12011 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12012 (rpl (nth (if musep 2 1) cell))
12013 (ind ""))
12014 (delete-region start (point))
12015 (when (string-match "\\`#\\+" rpl)
12016 (cond
12017 ((bolp))
12018 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12019 (setq ind (buffer-substring (point-at-bol) (point))))
12020 (t (newline))))
12021 (setq start (point))
12022 (if (string-match "%file" rpl)
12023 (setq rpl (replace-match
12024 (concat
12025 "\""
12026 (save-match-data
12027 (abbreviate-file-name (read-file-name "Include file: ")))
12028 "\"")
12029 t t rpl)))
12030 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12031 (concat "\n" ind)))
12032 (insert rpl)
12033 (if (re-search-backward "\\?" start t) (delete-char 1))))
12035 ;;;; TODO, DEADLINE, Comments
12037 (defun org-toggle-comment ()
12038 "Change the COMMENT state of an entry."
12039 (interactive)
12040 (save-excursion
12041 (org-back-to-heading)
12042 (let (case-fold-search)
12043 (cond
12044 ((looking-at (format org-heading-keyword-regexp-format
12045 org-comment-string))
12046 (goto-char (match-end 1))
12047 (looking-at (concat " +" org-comment-string))
12048 (replace-match "" t t)
12049 (when (eolp) (insert " ")))
12050 ((looking-at org-outline-regexp)
12051 (goto-char (match-end 0))
12052 (insert org-comment-string " "))))))
12054 (defvar org-last-todo-state-is-todo nil
12055 "This is non-nil when the last TODO state change led to a TODO state.
12056 If the last change removed the TODO tag or switched to DONE, then
12057 this is nil.")
12059 (defvar org-setting-tags nil) ; dynamically skipped
12061 (defvar org-todo-setup-filter-hook nil
12062 "Hook for functions that pre-filter todo specs.
12063 Each function takes a todo spec and returns either nil or the spec
12064 transformed into canonical form." )
12066 (defvar org-todo-get-default-hook nil
12067 "Hook for functions that get a default item for todo.
12068 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12069 nil or a string to be used for the todo mark." )
12071 (defvar org-agenda-headline-snapshot-before-repeat)
12073 (defun org-current-effective-time ()
12074 "Return current time adjusted for `org-extend-today-until' variable."
12075 (let* ((ct (org-current-time))
12076 (dct (decode-time ct))
12077 (ct1
12078 (cond
12079 (org-use-last-clock-out-time-as-effective-time
12080 (or (org-clock-get-last-clock-out-time) ct))
12081 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12082 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12083 (t ct))))
12084 ct1))
12086 (defun org-todo-yesterday (&optional arg)
12087 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12088 (interactive "P")
12089 (if (eq major-mode 'org-agenda-mode)
12090 (apply 'org-agenda-todo-yesterday arg)
12091 (let* ((hour (third (decode-time
12092 (org-current-time))))
12093 (org-extend-today-until (1+ hour)))
12094 (org-todo arg))))
12096 (defvar org-block-entry-blocking ""
12097 "First entry preventing the TODO state change.")
12099 (defun org-todo (&optional arg)
12100 "Change the TODO state of an item.
12101 The state of an item is given by a keyword at the start of the heading,
12102 like
12103 *** TODO Write paper
12104 *** DONE Call mom
12106 The different keywords are specified in the variable `org-todo-keywords'.
12107 By default the available states are \"TODO\" and \"DONE\".
12108 So for this example: when the item starts with TODO, it is changed to DONE.
12109 When it starts with DONE, the DONE is removed. And when neither TODO nor
12110 DONE are present, add TODO at the beginning of the heading.
12112 With \\[universal-argument] prefix arg, use completion to determine the new \
12113 state.
12114 With numeric prefix arg, switch to that state.
12115 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12116 keywords (nextset).
12117 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12118 With a numeric prefix arg of 0, inhibit note taking for the change.
12120 For calling through lisp, arg is also interpreted in the following way:
12121 'none -> empty state
12122 \"\"(empty string) -> switch to empty state
12123 'done -> switch to DONE
12124 'nextset -> switch to the next set of keywords
12125 'previousset -> switch to the previous set of keywords
12126 \"WAITING\" -> switch to the specified keyword, but only if it
12127 really is a member of `org-todo-keywords'."
12128 (interactive "P")
12129 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12130 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12131 'region-start-level 'region))
12132 org-loop-over-headlines-in-active-region)
12133 (org-map-entries
12134 `(org-todo ,arg)
12135 org-loop-over-headlines-in-active-region
12136 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12137 (if (equal arg '(16)) (setq arg 'nextset))
12138 (let ((org-blocker-hook org-blocker-hook)
12139 commentp
12140 case-fold-search)
12141 (when (equal arg '(64))
12142 (setq arg nil org-blocker-hook nil))
12143 (when (and org-blocker-hook
12144 (or org-inhibit-blocking
12145 (org-entry-get nil "NOBLOCKING")))
12146 (setq org-blocker-hook nil))
12147 (save-excursion
12148 (catch 'exit
12149 (org-back-to-heading t)
12150 (when (looking-at (concat "^\\*+ " org-comment-string))
12151 (org-toggle-comment)
12152 (setq commentp t))
12153 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12154 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12155 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12156 (let* ((match-data (match-data))
12157 (startpos (point-at-bol))
12158 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12159 (org-log-done org-log-done)
12160 (org-log-repeat org-log-repeat)
12161 (org-todo-log-states org-todo-log-states)
12162 (org-inhibit-logging
12163 (if (equal arg 0)
12164 (progn (setq arg nil) 'note) org-inhibit-logging))
12165 (this (match-string 1))
12166 (hl-pos (match-beginning 0))
12167 (head (org-get-todo-sequence-head this))
12168 (ass (assoc head org-todo-kwd-alist))
12169 (interpret (nth 1 ass))
12170 (done-word (nth 3 ass))
12171 (final-done-word (nth 4 ass))
12172 (org-last-state (or this ""))
12173 (completion-ignore-case t)
12174 (member (member this org-todo-keywords-1))
12175 (tail (cdr member))
12176 (org-state (cond
12177 ((and org-todo-key-trigger
12178 (or (and (equal arg '(4))
12179 (eq org-use-fast-todo-selection 'prefix))
12180 (and (not arg) org-use-fast-todo-selection
12181 (not (eq org-use-fast-todo-selection
12182 'prefix)))))
12183 ;; Use fast selection
12184 (org-fast-todo-selection))
12185 ((and (equal arg '(4))
12186 (or (not org-use-fast-todo-selection)
12187 (not org-todo-key-trigger)))
12188 ;; Read a state with completion
12189 (org-icompleting-read
12190 "State: " (mapcar 'list org-todo-keywords-1)
12191 nil t))
12192 ((eq arg 'right)
12193 (if this
12194 (if tail (car tail) nil)
12195 (car org-todo-keywords-1)))
12196 ((eq arg 'left)
12197 (if (equal member org-todo-keywords-1)
12199 (if this
12200 (nth (- (length org-todo-keywords-1)
12201 (length tail) 2)
12202 org-todo-keywords-1)
12203 (org-last org-todo-keywords-1))))
12204 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12205 (setq arg nil))) ; hack to fall back to cycling
12206 (arg
12207 ;; user or caller requests a specific state
12208 (cond
12209 ((equal arg "") nil)
12210 ((eq arg 'none) nil)
12211 ((eq arg 'done) (or done-word (car org-done-keywords)))
12212 ((eq arg 'nextset)
12213 (or (car (cdr (member head org-todo-heads)))
12214 (car org-todo-heads)))
12215 ((eq arg 'previousset)
12216 (let ((org-todo-heads (reverse org-todo-heads)))
12217 (or (car (cdr (member head org-todo-heads)))
12218 (car org-todo-heads))))
12219 ((car (member arg org-todo-keywords-1)))
12220 ((stringp arg)
12221 (user-error "State `%s' not valid in this file" arg))
12222 ((nth (1- (prefix-numeric-value arg))
12223 org-todo-keywords-1))))
12224 ((null member) (or head (car org-todo-keywords-1)))
12225 ((equal this final-done-word) nil) ;; -> make empty
12226 ((null tail) nil) ;; -> first entry
12227 ((memq interpret '(type priority))
12228 (if (eq this-command last-command)
12229 (car tail)
12230 (if (> (length tail) 0)
12231 (or done-word (car org-done-keywords))
12232 nil)))
12234 (car tail))))
12235 (org-state (or
12236 (run-hook-with-args-until-success
12237 'org-todo-get-default-hook org-state org-last-state)
12238 org-state))
12239 (next (if org-state (concat " " org-state " ") " "))
12240 (change-plist (list :type 'todo-state-change :from this :to org-state
12241 :position startpos))
12242 dolog now-done-p)
12243 (when org-blocker-hook
12244 (setq org-last-todo-state-is-todo
12245 (not (member this org-done-keywords)))
12246 (unless (save-excursion
12247 (save-match-data
12248 (org-with-wide-buffer
12249 (run-hook-with-args-until-failure
12250 'org-blocker-hook change-plist))))
12251 (if (org-called-interactively-p 'interactive)
12252 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12253 this org-state org-block-entry-blocking)
12254 ;; fail silently
12255 (message "TODO state change from %s to %s blocked (by \"%s\")"
12256 this org-state org-block-entry-blocking)
12257 (throw 'exit nil))))
12258 (store-match-data match-data)
12259 (replace-match next t t)
12260 (unless (pos-visible-in-window-p hl-pos)
12261 (message "TODO state changed to %s" (org-trim next)))
12262 (unless head
12263 (setq head (org-get-todo-sequence-head org-state)
12264 ass (assoc head org-todo-kwd-alist)
12265 interpret (nth 1 ass)
12266 done-word (nth 3 ass)
12267 final-done-word (nth 4 ass)))
12268 (when (memq arg '(nextset previousset))
12269 (message "Keyword-Set %d/%d: %s"
12270 (- (length org-todo-sets) -1
12271 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12272 (length org-todo-sets)
12273 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12274 (setq org-last-todo-state-is-todo
12275 (not (member org-state org-done-keywords)))
12276 (setq now-done-p (and (member org-state org-done-keywords)
12277 (not (member this org-done-keywords))))
12278 (and logging (org-local-logging logging))
12279 (when (and (or org-todo-log-states org-log-done)
12280 (not (eq org-inhibit-logging t))
12281 (not (memq arg '(nextset previousset))))
12282 ;; we need to look at recording a time and note
12283 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12284 (nth 2 (assoc this org-todo-log-states))))
12285 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12286 (setq dolog 'time))
12287 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12288 (and org-state
12289 (member org-state org-not-done-keywords)
12290 (not (member this org-not-done-keywords))))
12291 ;; This is now a todo state and was not one before
12292 ;; If there was a CLOSED time stamp, get rid of it.
12293 (org-add-planning-info nil nil 'closed))
12294 (when (and now-done-p org-log-done)
12295 ;; It is now done, and it was not done before
12296 (org-add-planning-info 'closed (org-current-effective-time))
12297 (if (and (not dolog) (eq 'note org-log-done))
12298 (org-add-log-setup 'done org-state this 'findpos 'note)))
12299 (when (and org-state dolog)
12300 ;; This is a non-nil state, and we need to log it
12301 (org-add-log-setup 'state org-state this 'findpos dolog)))
12302 ;; Fixup tag positioning
12303 (org-todo-trigger-tag-changes org-state)
12304 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12305 (when org-provide-todo-statistics
12306 (org-update-parent-todo-statistics))
12307 (run-hooks 'org-after-todo-state-change-hook)
12308 (if (and arg (not (member org-state org-done-keywords)))
12309 (setq head (org-get-todo-sequence-head org-state)))
12310 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12311 ;; Do we need to trigger a repeat?
12312 (when now-done-p
12313 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12314 ;; This is for the agenda, take a snapshot of the headline.
12315 (save-match-data
12316 (setq org-agenda-headline-snapshot-before-repeat
12317 (org-get-heading))))
12318 (org-auto-repeat-maybe org-state))
12319 ;; Fixup cursor location if close to the keyword
12320 (if (and (outline-on-heading-p)
12321 (not (bolp))
12322 (save-excursion (beginning-of-line 1)
12323 (looking-at org-todo-line-regexp))
12324 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12325 (progn
12326 (goto-char (or (match-end 2) (match-end 1)))
12327 (and (looking-at " ") (just-one-space))))
12328 (when org-trigger-hook
12329 (save-excursion
12330 (run-hook-with-args 'org-trigger-hook change-plist)))
12331 (when commentp (org-toggle-comment))))))))
12333 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12334 "Block turning an entry into a TODO, using the hierarchy.
12335 This checks whether the current task should be blocked from state
12336 changes. Such blocking occurs when:
12338 1. The task has children which are not all in a completed state.
12340 2. A task has a parent with the property :ORDERED:, and there
12341 are siblings prior to the current task with incomplete
12342 status.
12344 3. The parent of the task is blocked because it has siblings that should
12345 be done first, or is child of a block grandparent TODO entry."
12347 (if (not org-enforce-todo-dependencies)
12348 t ; if locally turned off don't block
12349 (catch 'dont-block
12350 ;; If this is not a todo state change, or if this entry is already DONE,
12351 ;; do not block
12352 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12353 (member (plist-get change-plist :from)
12354 (cons 'done org-done-keywords))
12355 (member (plist-get change-plist :to)
12356 (cons 'todo org-not-done-keywords))
12357 (not (plist-get change-plist :to)))
12358 (throw 'dont-block t))
12359 ;; If this task has children, and any are undone, it's blocked
12360 (save-excursion
12361 (org-back-to-heading t)
12362 (let ((this-level (funcall outline-level)))
12363 (outline-next-heading)
12364 (let ((child-level (funcall outline-level)))
12365 (while (and (not (eobp))
12366 (> child-level this-level))
12367 ;; this todo has children, check whether they are all
12368 ;; completed
12369 (if (and (not (org-entry-is-done-p))
12370 (org-entry-is-todo-p))
12371 (progn (setq org-block-entry-blocking (org-get-heading))
12372 (throw 'dont-block nil)))
12373 (outline-next-heading)
12374 (setq child-level (funcall outline-level))))))
12375 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12376 ;; any previous siblings are undone, it's blocked
12377 (save-excursion
12378 (org-back-to-heading t)
12379 (let* ((pos (point))
12380 (parent-pos (and (org-up-heading-safe) (point))))
12381 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12382 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12383 (forward-line 1)
12384 (re-search-forward org-not-done-heading-regexp pos t))
12385 (setq org-block-entry-blocking (match-string 0))
12386 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12387 ;; Search further up the hierarchy, to see if an ancestor is blocked
12388 (while t
12389 (goto-char parent-pos)
12390 (if (not (looking-at org-not-done-heading-regexp))
12391 (throw 'dont-block t)) ; do not block, parent is not a TODO
12392 (setq pos (point))
12393 (setq parent-pos (and (org-up-heading-safe) (point)))
12394 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12395 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12396 (forward-line 1)
12397 (re-search-forward org-not-done-heading-regexp pos t)
12398 (setq org-block-entry-blocking (org-get-heading)))
12399 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12401 (defcustom org-track-ordered-property-with-tag nil
12402 "Should the ORDERED property also be shown as a tag?
12403 The ORDERED property decides if an entry should require subtasks to be
12404 completed in sequence. Since a property is not very visible, setting
12405 this option means that toggling the ORDERED property with the command
12406 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12407 not relevant for the behavior, but it makes things more visible.
12409 Note that toggling the tag with tags commands will not change the property
12410 and therefore not influence behavior!
12412 This can be t, meaning the tag ORDERED should be used, It can also be a
12413 string to select a different tag for this task."
12414 :group 'org-todo
12415 :type '(choice
12416 (const :tag "No tracking" nil)
12417 (const :tag "Track with ORDERED tag" t)
12418 (string :tag "Use other tag")))
12420 (defun org-toggle-ordered-property ()
12421 "Toggle the ORDERED property of the current entry.
12422 For better visibility, you can track the value of this property with a tag.
12423 See variable `org-track-ordered-property-with-tag'."
12424 (interactive)
12425 (let* ((t1 org-track-ordered-property-with-tag)
12426 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12427 (save-excursion
12428 (org-back-to-heading)
12429 (if (org-entry-get nil "ORDERED")
12430 (progn
12431 (org-delete-property "ORDERED" "PROPERTIES")
12432 (and tag (org-toggle-tag tag 'off))
12433 (message "Subtasks can be completed in arbitrary order"))
12434 (org-entry-put nil "ORDERED" "t")
12435 (and tag (org-toggle-tag tag 'on))
12436 (message "Subtasks must be completed in sequence")))))
12438 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12439 (defun org-block-todo-from-checkboxes (change-plist)
12440 "Block turning an entry into a TODO, using checkboxes.
12441 This checks whether the current task should be blocked from state
12442 changes because there are unchecked boxes in this entry."
12443 (if (not org-enforce-todo-checkbox-dependencies)
12444 t ; if locally turned off don't block
12445 (catch 'dont-block
12446 ;; If this is not a todo state change, or if this entry is already DONE,
12447 ;; do not block
12448 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12449 (member (plist-get change-plist :from)
12450 (cons 'done org-done-keywords))
12451 (member (plist-get change-plist :to)
12452 (cons 'todo org-not-done-keywords))
12453 (not (plist-get change-plist :to)))
12454 (throw 'dont-block t))
12455 ;; If this task has checkboxes that are not checked, it's blocked
12456 (save-excursion
12457 (org-back-to-heading t)
12458 (let ((beg (point)) end)
12459 (outline-next-heading)
12460 (setq end (point))
12461 (goto-char beg)
12462 (if (org-list-search-forward
12463 (concat (org-item-beginning-re)
12464 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12465 "\\[[- ]\\]")
12466 end t)
12467 (progn
12468 (if (boundp 'org-blocked-by-checkboxes)
12469 (setq org-blocked-by-checkboxes t))
12470 (throw 'dont-block nil)))))
12471 t))) ; do not block
12473 (defun org-entry-blocked-p ()
12474 "Is the current entry blocked?"
12475 (org-with-silent-modifications
12476 (if (org-entry-get nil "NOBLOCKING")
12477 nil ;; Never block this entry
12478 (not (run-hook-with-args-until-failure
12479 'org-blocker-hook
12480 (list :type 'todo-state-change
12481 :position (point)
12482 :from 'todo
12483 :to 'done))))))
12485 (defun org-update-statistics-cookies (all)
12486 "Update the statistics cookie, either from TODO or from checkboxes.
12487 This should be called with the cursor in a line with a statistics cookie."
12488 (interactive "P")
12489 (if all
12490 (progn
12491 (org-update-checkbox-count 'all)
12492 (org-map-entries 'org-update-parent-todo-statistics))
12493 (if (not (org-at-heading-p))
12494 (org-update-checkbox-count)
12495 (let ((pos (point-marker))
12496 end l1 l2)
12497 (ignore-errors (org-back-to-heading t))
12498 (if (not (org-at-heading-p))
12499 (org-update-checkbox-count)
12500 (setq l1 (org-outline-level))
12501 (setq end (save-excursion
12502 (outline-next-heading)
12503 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12504 (point)))
12505 (if (and (save-excursion
12506 (re-search-forward
12507 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12508 (not (save-excursion (re-search-forward
12509 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12510 (org-update-checkbox-count)
12511 (if (and l2 (> l2 l1))
12512 (progn
12513 (goto-char end)
12514 (org-update-parent-todo-statistics))
12515 (goto-char pos)
12516 (beginning-of-line 1)
12517 (while (re-search-forward
12518 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12519 (point-at-eol) t)
12520 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12521 (goto-char pos)
12522 (move-marker pos nil)))))
12524 (defvar org-entry-property-inherited-from) ;; defined below
12525 (defun org-update-parent-todo-statistics ()
12526 "Update any statistics cookie in the parent of the current headline.
12527 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12528 the entire subtree and this will travel up the hierarchy and update
12529 statistics everywhere."
12530 (let* ((prop (save-excursion (org-up-heading-safe)
12531 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12532 (recursive (or (not org-hierarchical-todo-statistics)
12533 (and prop (string-match "\\<recursive\\>" prop))))
12534 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12536 (first t)
12537 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12538 level ltoggle l1 new ndel
12539 (cnt-all 0) (cnt-done 0) is-percent kwd
12540 checkbox-beg ov ovs ove cookie-present)
12541 (catch 'exit
12542 (save-excursion
12543 (beginning-of-line 1)
12544 (setq ltoggle (funcall outline-level))
12545 ;; Three situations are to consider:
12547 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12548 ;; to the top-level ancestor on the headline;
12550 ;; 2. If parent has "recursive" property, repeat up to the
12551 ;; headline setting that property, taking inheritance into
12552 ;; account;
12554 ;; 3. Else, move up to direct parent and proceed only once.
12555 (while (and (setq level (org-up-heading-safe))
12556 (or recursive first)
12557 (>= (point) lim))
12558 (setq first nil cookie-present nil)
12559 (unless (and level
12560 (not (string-match
12561 "\\<checkbox\\>"
12562 (downcase (or (org-entry-get nil "COOKIE_DATA")
12563 "")))))
12564 (throw 'exit nil))
12565 (while (re-search-forward box-re (point-at-eol) t)
12566 (setq cnt-all 0 cnt-done 0 cookie-present t)
12567 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12568 (save-match-data
12569 (unless (outline-next-heading) (throw 'exit nil))
12570 (while (and (looking-at org-complex-heading-regexp)
12571 (> (setq l1 (length (match-string 1))) level))
12572 (setq kwd (and (or recursive (= l1 ltoggle))
12573 (match-string 2)))
12574 (if (or (eq org-provide-todo-statistics 'all-headlines)
12575 (and (listp org-provide-todo-statistics)
12576 (or (member kwd org-provide-todo-statistics)
12577 (member kwd org-done-keywords))))
12578 (setq cnt-all (1+ cnt-all))
12579 (if (eq org-provide-todo-statistics t)
12580 (and kwd (setq cnt-all (1+ cnt-all)))))
12581 (and (member kwd org-done-keywords)
12582 (setq cnt-done (1+ cnt-done)))
12583 (outline-next-heading)))
12584 (setq new
12585 (if is-percent
12586 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12587 (format "[%d/%d]" cnt-done cnt-all))
12588 ndel (- (match-end 0) checkbox-beg))
12589 ;; handle overlays when updating cookie from column view
12590 (when (setq ov (car (overlays-at checkbox-beg)))
12591 (setq ovs (overlay-start ov) ove (overlay-end ov))
12592 (delete-overlay ov))
12593 (goto-char checkbox-beg)
12594 (insert new)
12595 (delete-region (point) (+ (point) ndel))
12596 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12597 (when ov (move-overlay ov ovs ove)))
12598 (when cookie-present
12599 (run-hook-with-args 'org-after-todo-statistics-hook
12600 cnt-done (- cnt-all cnt-done))))))
12601 (run-hooks 'org-todo-statistics-hook)))
12603 (defvar org-after-todo-statistics-hook nil
12604 "Hook that is called after a TODO statistics cookie has been updated.
12605 Each function is called with two arguments: the number of not-done entries
12606 and the number of done entries.
12608 For example, the following function, when added to this hook, will switch
12609 an entry to DONE when all children are done, and back to TODO when new
12610 entries are set to a TODO status. Note that this hook is only called
12611 when there is a statistics cookie in the headline!
12613 (defun org-summary-todo (n-done n-not-done)
12614 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12615 (let (org-log-done org-log-states) ; turn off logging
12616 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12619 (defvar org-todo-statistics-hook nil
12620 "Hook that is run whenever Org thinks TODO statistics should be updated.
12621 This hook runs even if there is no statistics cookie present, in which case
12622 `org-after-todo-statistics-hook' would not run.")
12624 (defun org-todo-trigger-tag-changes (state)
12625 "Apply the changes defined in `org-todo-state-tags-triggers'."
12626 (let ((l org-todo-state-tags-triggers)
12627 changes)
12628 (when (or (not state) (equal state ""))
12629 (setq changes (append changes (cdr (assoc "" l)))))
12630 (when (and (stringp state) (> (length state) 0))
12631 (setq changes (append changes (cdr (assoc state l)))))
12632 (when (member state org-not-done-keywords)
12633 (setq changes (append changes (cdr (assoc 'todo l)))))
12634 (when (member state org-done-keywords)
12635 (setq changes (append changes (cdr (assoc 'done l)))))
12636 (dolist (c changes)
12637 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12639 (defun org-local-logging (value)
12640 "Get logging settings from a property VALUE."
12641 (let* (words w a)
12642 ;; directly set the variables, they are already local.
12643 (setq org-log-done nil
12644 org-log-repeat nil
12645 org-todo-log-states nil)
12646 (setq words (org-split-string value))
12647 (while (setq w (pop words))
12648 (cond
12649 ((setq a (assoc w org-startup-options))
12650 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12651 (set (nth 1 a) (nth 2 a))))
12652 ((setq a (org-extract-log-state-settings w))
12653 (and (member (car a) org-todo-keywords-1)
12654 (push a org-todo-log-states)))))))
12656 (defun org-get-todo-sequence-head (kwd)
12657 "Return the head of the TODO sequence to which KWD belongs.
12658 If KWD is not set, check if there is a text property remembering the
12659 right sequence."
12660 (let (p)
12661 (cond
12662 ((not kwd)
12663 (or (get-text-property (point-at-bol) 'org-todo-head)
12664 (progn
12665 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12666 nil (point-at-eol)))
12667 (get-text-property p 'org-todo-head))))
12668 ((not (member kwd org-todo-keywords-1))
12669 (car org-todo-keywords-1))
12670 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12672 (defun org-fast-todo-selection ()
12673 "Fast TODO keyword selection with single keys.
12674 Returns the new TODO keyword, or nil if no state change should occur."
12675 (let* ((fulltable org-todo-key-alist)
12676 (done-keywords org-done-keywords) ;; needed for the faces.
12677 (maxlen (apply 'max (mapcar
12678 (lambda (x)
12679 (if (stringp (car x)) (string-width (car x)) 0))
12680 fulltable)))
12681 (expert nil)
12682 (fwidth (+ maxlen 3 1 3))
12683 (ncol (/ (- (window-width) 4) fwidth))
12684 tg cnt e c tbl
12685 groups ingroup)
12686 (save-excursion
12687 (save-window-excursion
12688 (if expert
12689 (set-buffer (get-buffer-create " *Org todo*"))
12690 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12691 (erase-buffer)
12692 (org-set-local 'org-done-keywords done-keywords)
12693 (setq tbl fulltable cnt 0)
12694 (while (setq e (pop tbl))
12695 (cond
12696 ((equal e '(:startgroup))
12697 (push '() groups) (setq ingroup t)
12698 (when (not (= cnt 0))
12699 (setq cnt 0)
12700 (insert "\n"))
12701 (insert "{ "))
12702 ((equal e '(:endgroup))
12703 (setq ingroup nil cnt 0)
12704 (insert "}\n"))
12705 ((equal e '(:newline))
12706 (when (not (= cnt 0))
12707 (setq cnt 0)
12708 (insert "\n")
12709 (setq e (car tbl))
12710 (while (equal (car tbl) '(:newline))
12711 (insert "\n")
12712 (setq tbl (cdr tbl)))))
12714 (setq tg (car e) c (cdr e))
12715 (if ingroup (push tg (car groups)))
12716 (setq tg (org-add-props tg nil 'face
12717 (org-get-todo-face tg)))
12718 (if (and (= cnt 0) (not ingroup)) (insert " "))
12719 (insert "[" c "] " tg (make-string
12720 (- fwidth 4 (length tg)) ?\ ))
12721 (when (= (setq cnt (1+ cnt)) ncol)
12722 (insert "\n")
12723 (if ingroup (insert " "))
12724 (setq cnt 0)))))
12725 (insert "\n")
12726 (goto-char (point-min))
12727 (if (not expert) (org-fit-window-to-buffer))
12728 (message "[a-z..]:Set [SPC]:clear")
12729 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12730 (cond
12731 ((or (= c ?\C-g)
12732 (and (= c ?q) (not (rassoc c fulltable))))
12733 (setq quit-flag t))
12734 ((= c ?\ ) nil)
12735 ((setq e (rassoc c fulltable) tg (car e))
12737 (t (setq quit-flag t)))))))
12739 (defun org-entry-is-todo-p ()
12740 (member (org-get-todo-state) org-not-done-keywords))
12742 (defun org-entry-is-done-p ()
12743 (member (org-get-todo-state) org-done-keywords))
12745 (defun org-get-todo-state ()
12746 "Return the TODO keyword of the current subtree."
12747 (save-excursion
12748 (org-back-to-heading t)
12749 (and (looking-at org-todo-line-regexp)
12750 (match-end 2)
12751 (match-string 2))))
12753 (defun org-at-date-range-p (&optional inactive-ok)
12754 "Is the cursor inside a date range?"
12755 (interactive)
12756 (save-excursion
12757 (catch 'exit
12758 (let ((pos (point)))
12759 (skip-chars-backward "^[<\r\n")
12760 (skip-chars-backward "<[")
12761 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12762 (>= (match-end 0) pos)
12763 (throw 'exit t))
12764 (skip-chars-backward "^<[\r\n")
12765 (skip-chars-backward "<[")
12766 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12767 (>= (match-end 0) pos)
12768 (throw 'exit t)))
12769 nil)))
12771 (defun org-get-repeat (&optional tagline)
12772 "Check if there is a deadline/schedule with repeater in this entry."
12773 (save-match-data
12774 (save-excursion
12775 (org-back-to-heading t)
12776 (and (re-search-forward (if tagline
12777 (concat tagline "\\s-*" org-repeat-re)
12778 org-repeat-re)
12779 (org-entry-end-position) t)
12780 (match-string-no-properties 1)))))
12782 (defvar org-last-changed-timestamp)
12783 (defvar org-last-inserted-timestamp)
12784 (defvar org-log-post-message)
12785 (defvar org-log-note-purpose)
12786 (defvar org-log-note-how)
12787 (defvar org-log-note-extra)
12788 (defun org-auto-repeat-maybe (done-word)
12789 "Check if the current headline contains a repeated deadline/schedule.
12790 If yes, set TODO state back to what it was and change the base date
12791 of repeating deadline/scheduled time stamps to new date.
12792 This function is run automatically after each state change to a DONE state."
12793 ;; last-state is dynamically scoped into this function
12794 (let* ((repeat (org-get-repeat))
12795 (aa (assoc org-last-state org-todo-kwd-alist))
12796 (interpret (nth 1 aa))
12797 (head (nth 2 aa))
12798 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12799 (msg "Entry repeats: ")
12800 (org-log-done nil)
12801 (org-todo-log-states nil)
12802 re type n what ts time to-state)
12803 (when repeat
12804 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12805 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12806 org-todo-repeat-to-state))
12807 (unless (and to-state (member to-state org-todo-keywords-1))
12808 (setq to-state (if (eq interpret 'type) org-last-state head)))
12809 (org-todo to-state)
12810 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12811 (org-entry-put nil "LAST_REPEAT" (format-time-string
12812 (org-time-stamp-format t t))))
12813 (when org-log-repeat
12814 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12815 (memq 'org-add-log-note post-command-hook))
12816 ;; OK, we are already setup for some record
12817 (if (eq org-log-repeat 'note)
12818 ;; make sure we take a note, not only a time stamp
12819 (setq org-log-note-how 'note))
12820 ;; Set up for taking a record
12821 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12822 org-last-state
12823 'findpos org-log-repeat)))
12824 (org-back-to-heading t)
12825 (org-add-planning-info nil nil 'closed)
12826 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12827 org-deadline-time-regexp "\\)\\|\\("
12828 org-ts-regexp "\\)"))
12829 (while (re-search-forward
12830 re (save-excursion (outline-next-heading) (point)) t)
12831 (setq type (if (match-end 1) org-scheduled-string
12832 (if (match-end 3) org-deadline-string "Plain:"))
12833 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12834 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12835 (setq n (string-to-number (match-string 2 ts))
12836 what (match-string 3 ts))
12837 (if (equal what "w") (setq n (* n 7) what "d"))
12838 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12839 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12840 ;; Preparation, see if we need to modify the start date for the change
12841 (when (match-end 1)
12842 (setq time (save-match-data (org-time-string-to-time ts)))
12843 (cond
12844 ((equal (match-string 1 ts) ".")
12845 ;; Shift starting date to today
12846 (org-timestamp-change
12847 (- (org-today) (time-to-days time))
12848 'day))
12849 ((equal (match-string 1 ts) "+")
12850 (let ((nshiftmax 10) (nshift 0))
12851 (while (or (= nshift 0)
12852 (<= (time-to-days time)
12853 (time-to-days (current-time))))
12854 (when (= (incf nshift) nshiftmax)
12855 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12856 (error "Abort")))
12857 (org-timestamp-change n (cdr (assoc what whata)))
12858 (org-at-timestamp-p t)
12859 (setq ts (match-string 1))
12860 (setq time (save-match-data (org-time-string-to-time ts)))))
12861 (org-timestamp-change (- n) (cdr (assoc what whata)))
12862 ;; rematch, so that we have everything in place for the real shift
12863 (org-at-timestamp-p t)
12864 (setq ts (match-string 1))
12865 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12866 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12867 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12868 (setq org-log-post-message msg)
12869 (message "%s" msg))))
12871 (defun org-show-todo-tree (arg)
12872 "Make a compact tree which shows all headlines marked with TODO.
12873 The tree will show the lines where the regexp matches, and all higher
12874 headlines above the match.
12875 With a \\[universal-argument] prefix, prompt for a regexp to match.
12876 With a numeric prefix N, construct a sparse tree for the Nth element
12877 of `org-todo-keywords-1'."
12878 (interactive "P")
12879 (let ((case-fold-search nil)
12880 (kwd-re
12881 (cond ((null arg) org-not-done-regexp)
12882 ((equal arg '(4))
12883 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12884 (mapcar 'list org-todo-keywords-1))))
12885 (concat "\\("
12886 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12887 "\\)\\>")))
12888 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12889 (regexp-quote (nth (1- (prefix-numeric-value arg))
12890 org-todo-keywords-1)))
12891 (t (user-error "Invalid prefix argument: %s" arg)))))
12892 (message "%d TODO entries found"
12893 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12895 (defun org-deadline (arg &optional time)
12896 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12897 With one universal prefix argument, remove any deadline from the item.
12898 With two universal prefix arguments, prompt for a warning delay.
12899 With argument TIME, set the deadline at the corresponding date. TIME
12900 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12901 (interactive "P")
12902 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12903 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12904 'region-start-level 'region))
12905 org-loop-over-headlines-in-active-region)
12906 (org-map-entries
12907 `(org-deadline ',arg ,time)
12908 org-loop-over-headlines-in-active-region
12909 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12910 (let* ((old-date (org-entry-get nil "DEADLINE"))
12911 (old-date-time (if old-date (org-time-string-to-time old-date)))
12912 (repeater (and old-date
12913 (string-match
12914 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12915 old-date)
12916 (match-string 1 old-date))))
12917 (cond
12918 ((equal arg '(4))
12919 (when (and old-date org-log-redeadline)
12920 (org-add-log-setup 'deldeadline nil old-date 'findpos
12921 org-log-redeadline))
12922 (org-remove-timestamp-with-keyword org-deadline-string)
12923 (message "Item no longer has a deadline."))
12924 ((equal arg '(16))
12925 (save-excursion
12926 (if (re-search-forward
12927 org-deadline-time-regexp
12928 (save-excursion (outline-next-heading) (point)) t)
12929 (let* ((rpl0 (match-string 1))
12930 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12931 (replace-match
12932 (concat org-deadline-string
12933 " <" rpl
12934 (format " -%dd"
12935 (abs
12936 (- (time-to-days
12937 (save-match-data
12938 (org-read-date nil t nil "Warn starting from" old-date-time)))
12939 (time-to-days old-date-time))))
12940 ">") t t))
12941 (user-error "No deadline information to update"))))
12943 (org-add-planning-info 'deadline time 'closed)
12944 (when (and old-date org-log-redeadline
12945 (not (equal old-date
12946 (substring org-last-inserted-timestamp 1 -1))))
12947 (org-add-log-setup 'redeadline nil old-date 'findpos
12948 org-log-redeadline))
12949 (when repeater
12950 (save-excursion
12951 (org-back-to-heading t)
12952 (when (re-search-forward (concat org-deadline-string " "
12953 org-last-inserted-timestamp)
12954 (save-excursion
12955 (outline-next-heading) (point)) t)
12956 (goto-char (1- (match-end 0)))
12957 (insert " " repeater)
12958 (setq org-last-inserted-timestamp
12959 (concat (substring org-last-inserted-timestamp 0 -1)
12960 " " repeater
12961 (substring org-last-inserted-timestamp -1))))))
12962 (message "Deadline on %s" org-last-inserted-timestamp))))))
12964 (defun org-schedule (arg &optional time)
12965 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12966 With one universal prefix argument, remove any scheduling date from the item.
12967 With two universal prefix arguments, prompt for a delay cookie.
12968 With argument TIME, scheduled at the corresponding date. TIME can
12969 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12970 (interactive "P")
12971 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12972 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12973 'region-start-level 'region))
12974 org-loop-over-headlines-in-active-region)
12975 (org-map-entries
12976 `(org-schedule ',arg ,time)
12977 org-loop-over-headlines-in-active-region
12978 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12979 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12980 (old-date-time (if old-date (org-time-string-to-time old-date)))
12981 (repeater (and old-date
12982 (string-match
12983 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12984 old-date)
12985 (match-string 1 old-date))))
12986 (cond
12987 ((equal arg '(4))
12988 (progn
12989 (when (and old-date org-log-reschedule)
12990 (org-add-log-setup 'delschedule nil old-date 'findpos
12991 org-log-reschedule))
12992 (org-remove-timestamp-with-keyword org-scheduled-string)
12993 (message "Item is no longer scheduled.")))
12994 ((equal arg '(16))
12995 (save-excursion
12996 (if (re-search-forward
12997 org-scheduled-time-regexp
12998 (save-excursion (outline-next-heading) (point)) t)
12999 (let* ((rpl0 (match-string 1))
13000 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13001 (replace-match
13002 (concat org-scheduled-string
13003 " <" rpl
13004 (format " -%dd"
13005 (abs
13006 (- (time-to-days
13007 (save-match-data
13008 (org-read-date nil t nil "Delay until" old-date-time)))
13009 (time-to-days old-date-time))))
13010 ">") t t))
13011 (user-error "No scheduled information to update"))))
13013 (org-add-planning-info 'scheduled time 'closed)
13014 (when (and old-date org-log-reschedule
13015 (not (equal old-date
13016 (substring org-last-inserted-timestamp 1 -1))))
13017 (org-add-log-setup 'reschedule nil old-date 'findpos
13018 org-log-reschedule))
13019 (when repeater
13020 (save-excursion
13021 (org-back-to-heading t)
13022 (when (re-search-forward (concat org-scheduled-string " "
13023 org-last-inserted-timestamp)
13024 (save-excursion
13025 (outline-next-heading) (point)) t)
13026 (goto-char (1- (match-end 0)))
13027 (insert " " repeater)
13028 (setq org-last-inserted-timestamp
13029 (concat (substring org-last-inserted-timestamp 0 -1)
13030 " " repeater
13031 (substring org-last-inserted-timestamp -1))))))
13032 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13034 (defun org-get-scheduled-time (pom &optional inherit)
13035 "Get the scheduled time as a time tuple, of a format suitable
13036 for calling org-schedule with, or if there is no scheduling,
13037 returns nil."
13038 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13039 (when time
13040 (apply 'encode-time (org-parse-time-string time)))))
13042 (defun org-get-deadline-time (pom &optional inherit)
13043 "Get the deadline as a time tuple, of a format suitable for
13044 calling org-deadline with, or if there is no scheduling, returns
13045 nil."
13046 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13047 (when time
13048 (apply 'encode-time (org-parse-time-string time)))))
13050 (defun org-remove-timestamp-with-keyword (keyword)
13051 "Remove all time stamps with KEYWORD in the current entry."
13052 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13053 beg)
13054 (save-excursion
13055 (org-back-to-heading t)
13056 (setq beg (point))
13057 (outline-next-heading)
13058 (while (re-search-backward re beg t)
13059 (replace-match "")
13060 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13061 (equal (char-before) ?\ ))
13062 (backward-delete-char 1)
13063 (if (string-match "^[ \t]*$" (buffer-substring
13064 (point-at-bol) (point-at-eol)))
13065 (delete-region (point-at-bol)
13066 (min (point-max) (1+ (point-at-eol))))))))))
13068 (defun org-add-planning-info (what &optional time &rest remove)
13069 "Insert new timestamp with keyword in the line directly after the headline.
13070 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13071 If non is given, the user is prompted for a date.
13072 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13073 be removed."
13074 (interactive)
13075 (let (org-time-was-given org-end-time-was-given ts
13076 end default-time default-input)
13078 (catch 'exit
13079 (when (and (memq what '(scheduled deadline))
13080 (or (not time)
13081 (and (stringp time)
13082 (string-match "^[-+]+[0-9]" time))))
13083 ;; Try to get a default date/time from existing timestamp
13084 (save-excursion
13085 (org-back-to-heading t)
13086 (setq end (save-excursion (outline-next-heading) (point)))
13087 (when (re-search-forward (if (eq what 'scheduled)
13088 org-scheduled-time-regexp
13089 org-deadline-time-regexp)
13090 end t)
13091 (setq ts (match-string 1)
13092 default-time
13093 (apply 'encode-time (org-parse-time-string ts))
13094 default-input (and ts (org-get-compact-tod ts))))))
13095 (when what
13096 (setq time
13097 (if (stringp time)
13098 ;; This is a string (relative or absolute), set proper date
13099 (apply 'encode-time
13100 (org-read-date-analyze
13101 time default-time (decode-time default-time)))
13102 ;; If necessary, get the time from the user
13103 (or time (org-read-date nil 'to-time nil nil
13104 default-time default-input)))))
13106 (when (and org-insert-labeled-timestamps-at-point
13107 (member what '(scheduled deadline)))
13108 (insert
13109 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13110 (org-insert-time-stamp time org-time-was-given
13111 nil nil nil (list org-end-time-was-given))
13112 (setq what nil))
13113 (save-excursion
13114 (save-restriction
13115 (let (col list elt ts buffer-invisibility-spec)
13116 (org-back-to-heading t)
13117 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13118 (goto-char (match-end 1))
13119 (setq col (current-column))
13120 (goto-char (match-end 0))
13121 (if (eobp) (insert "\n") (forward-char 1))
13122 (when (and (not what)
13123 (not (looking-at
13124 (concat "[ \t]*"
13125 org-keyword-time-not-clock-regexp))))
13126 ;; Nothing to add, nothing to remove...... :-)
13127 (throw 'exit nil))
13128 (if (and (not (looking-at org-outline-regexp))
13129 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13130 "[^\r\n]*"))
13131 (not (equal (match-string 1) org-clock-string)))
13132 (narrow-to-region (match-beginning 0) (match-end 0))
13133 (insert-before-markers "\n")
13134 (backward-char 1)
13135 (narrow-to-region (point) (point))
13136 (and org-adapt-indentation (org-indent-to-column col)))
13137 ;; Check if we have to remove something.
13138 (setq list (cons what remove))
13139 (while list
13140 (setq elt (pop list))
13141 (when (or (and (eq elt 'scheduled)
13142 (re-search-forward org-scheduled-time-regexp nil t))
13143 (and (eq elt 'deadline)
13144 (re-search-forward org-deadline-time-regexp nil t))
13145 (and (eq elt 'closed)
13146 (re-search-forward org-closed-time-regexp nil t)))
13147 (replace-match "")
13148 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13149 (and (looking-at "[ \t]+") (replace-match ""))
13150 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13151 (when what
13152 (insert
13153 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13154 (cond ((eq what 'scheduled) org-scheduled-string)
13155 ((eq what 'deadline) org-deadline-string)
13156 ((eq what 'closed) org-closed-string))
13157 " ")
13158 (setq ts (org-insert-time-stamp
13159 time
13160 (or org-time-was-given
13161 (and (eq what 'closed) org-log-done-with-time))
13162 (eq what 'closed)
13163 nil nil (list org-end-time-was-given)))
13164 (insert
13165 (if (not (or (bolp) (eq (char-before) ?\ )
13166 (memq (char-after) '(32 10))
13167 (eobp))) " " ""))
13168 (end-of-line 1))
13169 (goto-char (point-min))
13170 (widen)
13171 (if (and (looking-at "[ \t]*\n")
13172 (equal (char-before) ?\n))
13173 (delete-region (1- (point)) (point-at-eol)))
13174 ts))))))
13176 (defvar org-log-note-marker (make-marker))
13177 (defvar org-log-note-purpose nil)
13178 (defvar org-log-note-state nil)
13179 (defvar org-log-note-previous-state nil)
13180 (defvar org-log-note-how nil)
13181 (defvar org-log-note-extra nil)
13182 (defvar org-log-note-window-configuration nil)
13183 (defvar org-log-note-return-to (make-marker))
13184 (defvar org-log-note-effective-time nil
13185 "Remembered current time so that dynamically scoped
13186 `org-extend-today-until' affects tha timestamps in state change
13187 log")
13189 (defvar org-log-post-message nil
13190 "Message to be displayed after a log note has been stored.
13191 The auto-repeater uses this.")
13193 (defun org-add-note ()
13194 "Add a note to the current entry.
13195 This is done in the same way as adding a state change note."
13196 (interactive)
13197 (org-add-log-setup 'note nil nil 'findpos nil))
13199 (defvar org-property-end-re)
13200 (defun org-add-log-setup (&optional purpose state prev-state
13201 findpos how extra)
13202 "Set up the post command hook to take a note.
13203 If this is about to TODO state change, the new state is expected in STATE.
13204 When FINDPOS is non-nil, find the correct position for the note in
13205 the current entry. If not, assume that it can be inserted at point.
13206 HOW is an indicator what kind of note should be created.
13207 EXTRA is additional text that will be inserted into the notes buffer."
13208 (let* ((org-log-into-drawer (org-log-into-drawer))
13209 (drawer (cond ((stringp org-log-into-drawer)
13210 org-log-into-drawer)
13211 (org-log-into-drawer "LOGBOOK"))))
13212 (save-restriction
13213 (save-excursion
13214 (when findpos
13215 (org-back-to-heading t)
13216 (narrow-to-region (point) (save-excursion
13217 (outline-next-heading) (point)))
13218 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13219 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13220 "[^\r\n]*\\)?"))
13221 (goto-char (match-end 0))
13222 (cond
13223 (drawer
13224 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13225 nil t)
13226 (progn
13227 (goto-char (match-end 0))
13228 (or org-log-states-order-reversed
13229 (and (re-search-forward org-property-end-re nil t)
13230 (goto-char (1- (match-beginning 0))))))
13231 (insert "\n:" drawer ":\n:END:")
13232 (beginning-of-line 0)
13233 (org-indent-line)
13234 (beginning-of-line 2)
13235 (org-indent-line)
13236 (end-of-line 0)))
13237 ((and org-log-state-notes-insert-after-drawers
13238 (save-excursion
13239 (forward-line) (looking-at org-drawer-regexp)))
13240 (forward-line)
13241 (while (looking-at org-drawer-regexp)
13242 (goto-char (match-end 0))
13243 (re-search-forward org-property-end-re (point-max) t)
13244 (forward-line))
13245 (forward-line -1)))
13246 (unless org-log-states-order-reversed
13247 (and (= (char-after) ?\n) (forward-char 1))
13248 (org-skip-over-state-notes)
13249 (skip-chars-backward " \t\n\r")))
13250 (move-marker org-log-note-marker (point))
13251 (setq org-log-note-purpose purpose
13252 org-log-note-state state
13253 org-log-note-previous-state prev-state
13254 org-log-note-how how
13255 org-log-note-extra extra
13256 org-log-note-effective-time (org-current-effective-time))
13257 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13259 (defun org-skip-over-state-notes ()
13260 "Skip past the list of State notes in an entry."
13261 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13262 (when (ignore-errors (goto-char (org-in-item-p)))
13263 (let* ((struct (org-list-struct))
13264 (prevs (org-list-prevs-alist struct)))
13265 (while (looking-at "[ \t]*- State")
13266 (goto-char (or (org-list-get-next-item (point) struct prevs)
13267 (org-list-get-item-end (point) struct)))))))
13269 (defun org-add-log-note (&optional purpose)
13270 "Pop up a window for taking a note, and add this note later at point."
13271 (remove-hook 'post-command-hook 'org-add-log-note)
13272 (setq org-log-note-window-configuration (current-window-configuration))
13273 (delete-other-windows)
13274 (move-marker org-log-note-return-to (point))
13275 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13276 (goto-char org-log-note-marker)
13277 (org-switch-to-buffer-other-window "*Org Note*")
13278 (erase-buffer)
13279 (if (memq org-log-note-how '(time state))
13280 (let (current-prefix-arg) (org-store-log-note))
13281 (let ((org-inhibit-startup t)) (org-mode))
13282 (insert (format "# Insert note for %s.
13283 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13284 (cond
13285 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13286 ((eq org-log-note-purpose 'done) "closed todo item")
13287 ((eq org-log-note-purpose 'state)
13288 (format "state change from \"%s\" to \"%s\""
13289 (or org-log-note-previous-state "")
13290 (or org-log-note-state "")))
13291 ((eq org-log-note-purpose 'reschedule)
13292 "rescheduling")
13293 ((eq org-log-note-purpose 'delschedule)
13294 "no longer scheduled")
13295 ((eq org-log-note-purpose 'redeadline)
13296 "changing deadline")
13297 ((eq org-log-note-purpose 'deldeadline)
13298 "removing deadline")
13299 ((eq org-log-note-purpose 'refile)
13300 "refiling")
13301 ((eq org-log-note-purpose 'note)
13302 "this entry")
13303 (t (error "This should not happen")))))
13304 (if org-log-note-extra (insert org-log-note-extra))
13305 (org-set-local 'org-finish-function 'org-store-log-note)
13306 (run-hooks 'org-log-buffer-setup-hook)))
13308 (defvar org-note-abort nil) ; dynamically scoped
13309 (defun org-store-log-note ()
13310 "Finish taking a log note, and insert it to where it belongs."
13311 (let ((txt (buffer-string)))
13312 (kill-buffer (current-buffer))
13313 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13314 lines ind bul)
13315 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13316 (setq txt (replace-match "" t t txt)))
13317 (if (string-match "\\s-+\\'" txt)
13318 (setq txt (replace-match "" t t txt)))
13319 (setq lines (org-split-string txt "\n"))
13320 (when (and note (string-match "\\S-" note))
13321 (setq note
13322 (org-replace-escapes
13323 note
13324 (list (cons "%u" (user-login-name))
13325 (cons "%U" user-full-name)
13326 (cons "%t" (format-time-string
13327 (org-time-stamp-format 'long 'inactive)
13328 org-log-note-effective-time))
13329 (cons "%T" (format-time-string
13330 (org-time-stamp-format 'long nil)
13331 org-log-note-effective-time))
13332 (cons "%d" (format-time-string
13333 (org-time-stamp-format nil 'inactive)
13334 org-log-note-effective-time))
13335 (cons "%D" (format-time-string
13336 (org-time-stamp-format nil nil)
13337 org-log-note-effective-time))
13338 (cons "%s" (if org-log-note-state
13339 (concat "\"" org-log-note-state "\"")
13340 ""))
13341 (cons "%S" (if org-log-note-previous-state
13342 (concat "\"" org-log-note-previous-state "\"")
13343 "\"\"")))))
13344 (if lines (setq note (concat note " \\\\")))
13345 (push note lines))
13346 (when (or current-prefix-arg org-note-abort)
13347 (when org-log-into-drawer
13348 (org-remove-empty-drawer-at
13349 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13350 org-log-note-marker))
13351 (setq lines nil))
13352 (when lines
13353 (with-current-buffer (marker-buffer org-log-note-marker)
13354 (save-excursion
13355 (goto-char org-log-note-marker)
13356 (move-marker org-log-note-marker nil)
13357 (end-of-line 1)
13358 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13359 (setq ind (save-excursion
13360 (if (ignore-errors (goto-char (org-in-item-p)))
13361 (let ((struct (org-list-struct)))
13362 (org-list-get-ind
13363 (org-list-get-top-point struct) struct))
13364 (skip-chars-backward " \r\t\n")
13365 (cond
13366 ((and (org-at-heading-p)
13367 org-adapt-indentation)
13368 (1+ (org-current-level)))
13369 ((org-at-heading-p) 0)
13370 (t (org-get-indentation))))))
13371 (setq bul (org-list-bullet-string "-"))
13372 (org-indent-line-to ind)
13373 (insert bul (pop lines))
13374 (let ((ind-body (+ (length bul) ind)))
13375 (while lines
13376 (insert "\n")
13377 (org-indent-line-to ind-body)
13378 (insert (pop lines))))
13379 (message "Note stored")
13380 (org-back-to-heading t)
13381 (org-cycle-hide-drawers 'children))
13382 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13383 ;; from within `org-add-log-note' because `buffer-undo-list'
13384 ;; is then modified outside of `org-with-remote-undo'.
13385 (when (eq this-command 'org-agenda-todo)
13386 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13387 ;; Don't add undo information when called from `org-agenda-todo'
13388 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13389 (set-window-configuration org-log-note-window-configuration)
13390 (with-current-buffer (marker-buffer org-log-note-return-to)
13391 (goto-char org-log-note-return-to))
13392 (move-marker org-log-note-return-to nil)
13393 (and org-log-post-message (message "%s" org-log-post-message))))
13395 (defun org-remove-empty-drawer-at (drawer pos)
13396 "Remove an empty drawer DRAWER at position POS.
13397 POS may also be a marker."
13398 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13399 (save-excursion
13400 (save-restriction
13401 (widen)
13402 (goto-char pos)
13403 (if (org-in-regexp
13404 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13405 (replace-match ""))))))
13407 (defvar org-ts-type nil)
13408 (defun org-sparse-tree (&optional arg type)
13409 "Create a sparse tree, prompt for the details.
13410 This command can create sparse trees. You first need to select the type
13411 of match used to create the tree:
13413 t Show all TODO entries.
13414 T Show entries with a specific TODO keyword.
13415 m Show entries selected by a tags/property match.
13416 p Enter a property name and its value (both with completion on existing
13417 names/values) and show entries with that property.
13418 r Show entries matching a regular expression (`/' can be used as well).
13419 b Show deadlines and scheduled items before a date.
13420 a Show deadlines and scheduled items after a date.
13421 d Show deadlines due within `org-deadline-warning-days'.
13422 D Show deadlines and scheduled items between a date range."
13423 (interactive "P")
13424 (let (ans kwd value ts-type)
13425 (setq type (or type org-sparse-tree-default-date-type))
13426 (setq org-ts-type type)
13427 (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"
13428 (cond ((eq type 'all) "all timestamps")
13429 ((eq type 'scheduled) "only scheduled")
13430 ((eq type 'deadline) "only deadline")
13431 ((eq type 'active) "only active timestamps")
13432 ((eq type 'inactive) "only inactive timestamps")
13433 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13434 ((eq type 'closed) "with a closed time-stamp")
13435 (t "scheduled/deadline")))
13436 (setq ans (read-char-exclusive))
13437 (cond
13438 ((equal ans ?c)
13439 (org-sparse-tree
13440 arg (cadr (member type '(scheduled-or-deadline
13441 all scheduled deadline active inactive closed)))))
13442 ((equal ans ?d)
13443 (call-interactively 'org-check-deadlines))
13444 ((equal ans ?b)
13445 (call-interactively 'org-check-before-date))
13446 ((equal ans ?a)
13447 (call-interactively 'org-check-after-date))
13448 ((equal ans ?D)
13449 (call-interactively 'org-check-dates-range))
13450 ((equal ans ?t)
13451 (call-interactively 'org-show-todo-tree))
13452 ((equal ans ?T)
13453 (org-show-todo-tree '(4)))
13454 ((member ans '(?T ?m))
13455 (call-interactively 'org-match-sparse-tree))
13456 ((member ans '(?p ?P))
13457 (setq kwd (org-icompleting-read "Property: "
13458 (mapcar 'list (org-buffer-property-keys))))
13459 (setq value (org-icompleting-read "Value: "
13460 (mapcar 'list (org-property-values kwd))))
13461 (unless (string-match "\\`{.*}\\'" value)
13462 (setq value (concat "\"" value "\"")))
13463 (org-match-sparse-tree arg (concat kwd "=" value)))
13464 ((member ans '(?r ?R ?/))
13465 (call-interactively 'org-occur))
13466 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13468 (defvar org-occur-highlights nil
13469 "List of overlays used for occur matches.")
13470 (make-variable-buffer-local 'org-occur-highlights)
13471 (defvar org-occur-parameters nil
13472 "Parameters of the active org-occur calls.
13473 This is a list, each call to org-occur pushes as cons cell,
13474 containing the regular expression and the callback, onto the list.
13475 The list can contain several entries if `org-occur' has been called
13476 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13477 will only contain one set of parameters. When the highlights are
13478 removed (for example with `C-c C-c', or with the next edit (depending
13479 on `org-remove-highlights-with-change'), this variable is emptied
13480 as well.")
13481 (make-variable-buffer-local 'org-occur-parameters)
13483 (defun org-occur (regexp &optional keep-previous callback)
13484 "Make a compact tree which shows all matches of REGEXP.
13485 The tree will show the lines where the regexp matches, and all higher
13486 headlines above the match. It will also show the heading after the match,
13487 to make sure editing the matching entry is easy.
13488 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13489 call to `org-occur' will be kept, to allow stacking of calls to this
13490 command.
13491 If CALLBACK is non-nil, it is a function which is called to confirm
13492 that the match should indeed be shown."
13493 (interactive "sRegexp: \nP")
13494 (when (equal regexp "")
13495 (user-error "Regexp cannot be empty"))
13496 (unless keep-previous
13497 (org-remove-occur-highlights nil nil t))
13498 (push (cons regexp callback) org-occur-parameters)
13499 (let ((cnt 0))
13500 (save-excursion
13501 (goto-char (point-min))
13502 (if (or (not keep-previous) ; do not want to keep
13503 (not org-occur-highlights)) ; no previous matches
13504 ;; hide everything
13505 (org-overview))
13506 (while (re-search-forward regexp nil t)
13507 (when (or (not callback)
13508 (save-match-data (funcall callback)))
13509 (setq cnt (1+ cnt))
13510 (when org-highlight-sparse-tree-matches
13511 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13512 (org-show-context 'occur-tree))))
13513 (when org-remove-highlights-with-change
13514 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13515 nil 'local))
13516 (unless org-sparse-tree-open-archived-trees
13517 (org-hide-archived-subtrees (point-min) (point-max)))
13518 (run-hooks 'org-occur-hook)
13519 (if (org-called-interactively-p 'interactive)
13520 (message "%d match(es) for regexp %s" cnt regexp))
13521 cnt))
13523 (defun org-occur-next-match (&optional n reset)
13524 "Function for `next-error-function' to find sparse tree matches.
13525 N is the number of matches to move, when negative move backwards.
13526 RESET is entirely ignored - this function always goes back to the
13527 starting point when no match is found."
13528 (let* ((limit (if (< n 0) (point-min) (point-max)))
13529 (search-func (if (< n 0)
13530 'previous-single-char-property-change
13531 'next-single-char-property-change))
13532 (n (abs n))
13533 (pos (point))
13535 (catch 'exit
13536 (while (setq p1 (funcall search-func (point) 'org-type))
13537 (when (equal p1 limit)
13538 (goto-char pos)
13539 (error "No more matches"))
13540 (when (equal (get-char-property p1 'org-type) 'org-occur)
13541 (setq n (1- n))
13542 (when (= n 0)
13543 (goto-char p1)
13544 (throw 'exit (point))))
13545 (goto-char p1))
13546 (goto-char p1)
13547 (error "No more matches"))))
13549 (defun org-show-context (&optional key)
13550 "Make sure point and context are visible.
13551 How much context is shown depends upon the variables
13552 `org-show-hierarchy-above', `org-show-following-heading',
13553 `org-show-entry-below' and `org-show-siblings'."
13554 (let ((heading-p (org-at-heading-p t))
13555 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13556 (following-p (org-get-alist-option org-show-following-heading key))
13557 (entry-p (org-get-alist-option org-show-entry-below key))
13558 (siblings-p (org-get-alist-option org-show-siblings key)))
13559 ;; Show heading or entry text
13560 (if (and heading-p (not entry-p))
13561 (org-flag-heading nil) ; only show the heading
13562 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13563 (org-show-hidden-entry))) ; show entire entry
13564 (when following-p
13565 ;; Show next sibling, or heading below text
13566 (save-excursion
13567 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13568 (org-flag-heading nil))))
13569 (when siblings-p (org-show-siblings))
13570 (when hierarchy-p
13571 ;; show all higher headings, possibly with siblings
13572 (save-excursion
13573 (while (and (condition-case nil
13574 (progn (org-up-heading-all 1) t)
13575 (error nil))
13576 (not (bobp)))
13577 (org-flag-heading nil)
13578 (when siblings-p (org-show-siblings)))))
13579 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13581 (defvar org-reveal-start-hook nil
13582 "Hook run before revealing a location.")
13584 (defun org-reveal (&optional siblings)
13585 "Show current entry, hierarchy above it, and the following headline.
13586 This can be used to show a consistent set of context around locations
13587 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13588 not t for the search context.
13590 With optional argument SIBLINGS, on each level of the hierarchy all
13591 siblings are shown. This repairs the tree structure to what it would
13592 look like when opened with hierarchical calls to `org-cycle'.
13593 With double optional argument \\[universal-argument] \\[universal-argument], \
13594 go to the parent and show the
13595 entire tree."
13596 (interactive "P")
13597 (run-hooks 'org-reveal-start-hook)
13598 (let ((org-show-hierarchy-above t)
13599 (org-show-following-heading t)
13600 (org-show-siblings (if siblings t org-show-siblings)))
13601 (org-show-context nil))
13602 (when (equal siblings '(16))
13603 (save-excursion
13604 (when (org-up-heading-safe)
13605 (org-show-subtree)
13606 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13608 (defun org-highlight-new-match (beg end)
13609 "Highlight from BEG to END and mark the highlight is an occur headline."
13610 (let ((ov (make-overlay beg end)))
13611 (overlay-put ov 'face 'secondary-selection)
13612 (overlay-put ov 'org-type 'org-occur)
13613 (push ov org-occur-highlights)))
13615 (defun org-remove-occur-highlights (&optional beg end noremove)
13616 "Remove the occur highlights from the buffer.
13617 BEG and END are ignored. If NOREMOVE is nil, remove this function
13618 from the `before-change-functions' in the current buffer."
13619 (interactive)
13620 (unless org-inhibit-highlight-removal
13621 (mapc 'delete-overlay org-occur-highlights)
13622 (setq org-occur-highlights nil)
13623 (setq org-occur-parameters nil)
13624 (unless noremove
13625 (remove-hook 'before-change-functions
13626 'org-remove-occur-highlights 'local))))
13628 ;;;; Priorities
13630 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13631 "Regular expression matching the priority indicator.")
13633 (defvar org-remove-priority-next-time nil)
13635 (defun org-priority-up ()
13636 "Increase the priority of the current item."
13637 (interactive)
13638 (org-priority 'up))
13640 (defun org-priority-down ()
13641 "Decrease the priority of the current item."
13642 (interactive)
13643 (org-priority 'down))
13645 (defun org-priority (&optional action show)
13646 "Change the priority of an item.
13647 ACTION can be `set', `up', `down', or a character."
13648 (interactive "P")
13649 (if (equal action '(4))
13650 (org-show-priority)
13651 (unless org-enable-priority-commands
13652 (user-error "Priority commands are disabled"))
13653 (setq action (or action 'set))
13654 (let (current new news have remove)
13655 (save-excursion
13656 (org-back-to-heading t)
13657 (if (looking-at org-priority-regexp)
13658 (setq current (string-to-char (match-string 2))
13659 have t))
13660 (cond
13661 ((eq action 'remove)
13662 (setq remove t new ?\ ))
13663 ((or (eq action 'set)
13664 (if (featurep 'xemacs) (characterp action) (integerp action)))
13665 (if (not (eq action 'set))
13666 (setq new action)
13667 (message "Priority %c-%c, SPC to remove: "
13668 org-highest-priority org-lowest-priority)
13669 (save-match-data
13670 (setq new (read-char-exclusive))))
13671 (if (and (= (upcase org-highest-priority) org-highest-priority)
13672 (= (upcase org-lowest-priority) org-lowest-priority))
13673 (setq new (upcase new)))
13674 (cond ((equal new ?\ ) (setq remove t))
13675 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13676 (user-error "Priority must be between `%c' and `%c'"
13677 org-highest-priority org-lowest-priority))))
13678 ((eq action 'up)
13679 (setq new (if have
13680 (1- current) ; normal cycling
13681 ;; last priority was empty
13682 (if (eq last-command this-command)
13683 org-lowest-priority ; wrap around empty to lowest
13684 ;; default
13685 (if org-priority-start-cycle-with-default
13686 org-default-priority
13687 (1- org-default-priority))))))
13688 ((eq action 'down)
13689 (setq new (if have
13690 (1+ current) ; normal cycling
13691 ;; last priority was empty
13692 (if (eq last-command this-command)
13693 org-highest-priority ; wrap around empty to highest
13694 ;; default
13695 (if org-priority-start-cycle-with-default
13696 org-default-priority
13697 (1+ org-default-priority))))))
13698 (t (user-error "Invalid action")))
13699 (if (or (< (upcase new) org-highest-priority)
13700 (> (upcase new) org-lowest-priority))
13701 (if (and (memq action '(up down))
13702 (not have) (not (eq last-command this-command)))
13703 ;; `new' is from default priority
13704 (error
13705 "The default can not be set, see `org-default-priority' why")
13706 ;; normal cycling: `new' is beyond highest/lowest priority
13707 ;; and is wrapped around to the empty priority
13708 (setq remove t)))
13709 (setq news (format "%c" new))
13710 (if have
13711 (if remove
13712 (replace-match "" t t nil 1)
13713 (replace-match news t t nil 2))
13714 (if remove
13715 (user-error "No priority cookie found in line")
13716 (let ((case-fold-search nil))
13717 (looking-at org-todo-line-regexp))
13718 (if (match-end 2)
13719 (progn
13720 (goto-char (match-end 2))
13721 (insert " [#" news "]"))
13722 (goto-char (match-beginning 3))
13723 (insert "[#" news "] "))))
13724 (org-preserve-lc (org-set-tags nil 'align)))
13725 (if remove
13726 (message "Priority removed")
13727 (message "Priority of current item set to %s" news)))))
13729 (defun org-show-priority ()
13730 "Show the priority of the current item.
13731 This priority is composed of the main priority given with the [#A] cookies,
13732 and by additional input from the age of a schedules or deadline entry."
13733 (interactive)
13734 (let ((pri (if (eq major-mode 'org-agenda-mode)
13735 (org-get-at-bol 'priority)
13736 (save-excursion
13737 (save-match-data
13738 (beginning-of-line)
13739 (and (looking-at org-heading-regexp)
13740 (org-get-priority (match-string 0))))))))
13741 (message "Priority is %d" (if pri pri -1000))))
13743 (defun org-get-priority (s)
13744 "Find priority cookie and return priority."
13745 (save-match-data
13746 (if (functionp org-get-priority-function)
13747 (funcall org-get-priority-function)
13748 (if (not (string-match org-priority-regexp s))
13749 (* 1000 (- org-lowest-priority org-default-priority))
13750 (* 1000 (- org-lowest-priority
13751 (string-to-char (match-string 2 s))))))))
13753 ;;;; Tags
13755 (defvar org-agenda-archives-mode)
13756 (defvar org-map-continue-from nil
13757 "Position from where mapping should continue.
13758 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13760 (defvar org-scanner-tags nil
13761 "The current tag list while the tags scanner is running.")
13762 (defvar org-trust-scanner-tags nil
13763 "Should `org-get-tags-at' use the tags for the scanner.
13764 This is for internal dynamical scoping only.
13765 When this is non-nil, the function `org-get-tags-at' will return the value
13766 of `org-scanner-tags' instead of building the list by itself. This
13767 can lead to large speed-ups when the tags scanner is used in a file with
13768 many entries, and when the list of tags is retrieved, for example to
13769 obtain a list of properties. Building the tags list for each entry in such
13770 a file becomes an N^2 operation - but with this variable set, it scales
13771 as N.")
13773 (defun org-scan-tags (action matcher todo-only &optional start-level)
13774 "Sca headline tags with inheritance and produce output ACTION.
13776 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13777 or `agenda' to produce an entry list for an agenda view. It can also be
13778 a Lisp form or a function that should be called at each matched headline, in
13779 this case the return value is a list of all return values from these calls.
13781 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13782 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13783 only lines with a not-done TODO keyword are included in the output.
13784 This should be the same variable that was scoped into
13785 and set by `org-make-tags-matcher' when it constructed MATCHER.
13787 START-LEVEL can be a string with asterisks, reducing the scope to
13788 headlines matching this string."
13789 (require 'org-agenda)
13790 (let* ((re (concat "^"
13791 (if start-level
13792 ;; Get the correct level to match
13793 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13794 org-outline-regexp)
13795 " *\\(\\<\\("
13796 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13797 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13798 (props (list 'face 'default
13799 'done-face 'org-agenda-done
13800 'undone-face 'default
13801 'mouse-face 'highlight
13802 'org-not-done-regexp org-not-done-regexp
13803 'org-todo-regexp org-todo-regexp
13804 'org-complex-heading-regexp org-complex-heading-regexp
13805 'help-echo
13806 (format "mouse-2 or RET jump to org file %s"
13807 (abbreviate-file-name
13808 (or (buffer-file-name (buffer-base-buffer))
13809 (buffer-name (buffer-base-buffer)))))))
13810 (case-fold-search nil)
13811 (org-map-continue-from nil)
13812 lspos tags tags-list
13813 (tags-alist (list (cons 0 org-file-tags)))
13814 (llast 0) rtn rtn1 level category i txt
13815 todo marker entry priority)
13816 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13817 (setq action (list 'lambda nil action)))
13818 (save-excursion
13819 (goto-char (point-min))
13820 (when (eq action 'sparse-tree)
13821 (org-overview)
13822 (org-remove-occur-highlights))
13823 (while (re-search-forward re nil t)
13824 (setq org-map-continue-from nil)
13825 (catch :skip
13826 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13827 tags (if (match-end 4) (org-match-string-no-properties 4)))
13828 (goto-char (setq lspos (match-beginning 0)))
13829 (setq level (org-reduced-level (org-outline-level))
13830 category (org-get-category))
13831 (setq i llast llast level)
13832 ;; remove tag lists from same and sublevels
13833 (while (>= i level)
13834 (when (setq entry (assoc i tags-alist))
13835 (setq tags-alist (delete entry tags-alist)))
13836 (setq i (1- i)))
13837 ;; add the next tags
13838 (when tags
13839 (setq tags (org-split-string tags ":")
13840 tags-alist
13841 (cons (cons level tags) tags-alist)))
13842 ;; compile tags for current headline
13843 (setq tags-list
13844 (if org-use-tag-inheritance
13845 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13846 tags)
13847 org-scanner-tags tags-list)
13848 (when org-use-tag-inheritance
13849 (setcdr (car tags-alist)
13850 (mapcar (lambda (x)
13851 (setq x (copy-sequence x))
13852 (org-add-prop-inherited x))
13853 (cdar tags-alist))))
13854 (when (and tags org-use-tag-inheritance
13855 (or (not (eq t org-use-tag-inheritance))
13856 org-tags-exclude-from-inheritance))
13857 ;; selective inheritance, remove uninherited ones
13858 (setcdr (car tags-alist)
13859 (org-remove-uninherited-tags (cdar tags-alist))))
13860 (when (and
13862 ;; eval matcher only when the todo condition is OK
13863 (and (or (not todo-only) (member todo org-not-done-keywords))
13864 (let ((case-fold-search t) (org-trust-scanner-tags t))
13865 (eval matcher)))
13867 ;; Call the skipper, but return t if it does not skip,
13868 ;; so that the `and' form continues evaluating
13869 (progn
13870 (unless (eq action 'sparse-tree) (org-agenda-skip))
13873 ;; Check if timestamps are deselecting this entry
13874 (or (not todo-only)
13875 (and (member todo org-not-done-keywords)
13876 (or (not org-agenda-tags-todo-honor-ignore-options)
13877 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13879 ;; select this headline
13880 (cond
13881 ((eq action 'sparse-tree)
13882 (and org-highlight-sparse-tree-matches
13883 (org-get-heading) (match-end 0)
13884 (org-highlight-new-match
13885 (match-beginning 1) (match-end 1)))
13886 (org-show-context 'tags-tree))
13887 ((eq action 'agenda)
13888 (setq txt (org-agenda-format-item
13890 (concat
13891 (if (eq org-tags-match-list-sublevels 'indented)
13892 (make-string (1- level) ?.) "")
13893 (org-get-heading))
13894 level category
13895 tags-list)
13896 priority (org-get-priority txt))
13897 (goto-char lspos)
13898 (setq marker (org-agenda-new-marker))
13899 (org-add-props txt props
13900 'org-marker marker 'org-hd-marker marker 'org-category category
13901 'todo-state todo
13902 'priority priority 'type "tagsmatch")
13903 (push txt rtn))
13904 ((functionp action)
13905 (setq org-map-continue-from nil)
13906 (save-excursion
13907 (setq rtn1 (funcall action))
13908 (push rtn1 rtn)))
13909 (t (user-error "Invalid action")))
13911 ;; if we are to skip sublevels, jump to end of subtree
13912 (unless org-tags-match-list-sublevels
13913 (org-end-of-subtree t)
13914 (backward-char 1))))
13915 ;; Get the correct position from where to continue
13916 (if org-map-continue-from
13917 (goto-char org-map-continue-from)
13918 (and (= (point) lspos) (end-of-line 1)))))
13919 (when (and (eq action 'sparse-tree)
13920 (not org-sparse-tree-open-archived-trees))
13921 (org-hide-archived-subtrees (point-min) (point-max)))
13922 (nreverse rtn)))
13924 (defun org-remove-uninherited-tags (tags)
13925 "Remove all tags that are not inherited from the list TAGS."
13926 (cond
13927 ((eq org-use-tag-inheritance t)
13928 (if org-tags-exclude-from-inheritance
13929 (org-delete-all org-tags-exclude-from-inheritance tags)
13930 tags))
13931 ((not org-use-tag-inheritance) nil)
13932 ((stringp org-use-tag-inheritance)
13933 (delq nil (mapcar
13934 (lambda (x)
13935 (if (and (string-match org-use-tag-inheritance x)
13936 (not (member x org-tags-exclude-from-inheritance)))
13937 x nil))
13938 tags)))
13939 ((listp org-use-tag-inheritance)
13940 (delq nil (mapcar
13941 (lambda (x)
13942 (if (member x org-use-tag-inheritance) x nil))
13943 tags)))))
13945 (defun org-match-sparse-tree (&optional todo-only match)
13946 "Create a sparse tree according to tags string MATCH.
13947 MATCH can contain positive and negative selection of tags, like
13948 \"+WORK+URGENT-WITHBOSS\".
13949 If optional argument TODO-ONLY is non-nil, only select lines that are
13950 also TODO lines."
13951 (interactive "P")
13952 (org-agenda-prepare-buffers (list (current-buffer)))
13953 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13955 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13957 (defvar org-cached-props nil)
13958 (defun org-cached-entry-get (pom property)
13959 (if (or (eq t org-use-property-inheritance)
13960 (and (stringp org-use-property-inheritance)
13961 (string-match org-use-property-inheritance property))
13962 (and (listp org-use-property-inheritance)
13963 (member property org-use-property-inheritance)))
13964 ;; Caching is not possible, check it directly
13965 (org-entry-get pom property 'inherit)
13966 ;; Get all properties, so that we can do complicated checks easily
13967 (cdr (assoc property (or org-cached-props
13968 (setq org-cached-props
13969 (org-entry-properties pom)))))))
13971 (defun org-global-tags-completion-table (&optional files)
13972 "Return the list of all tags in all agenda buffer/files.
13973 Optional FILES argument is a list of files which can be used
13974 instead of the agenda files."
13975 (save-excursion
13976 (org-uniquify
13977 (delq nil
13978 (apply 'append
13979 (mapcar
13980 (lambda (file)
13981 (set-buffer (find-file-noselect file))
13982 (append (org-get-buffer-tags)
13983 (mapcar (lambda (x) (if (stringp (car-safe x))
13984 (list (car-safe x)) nil))
13985 org-tag-alist)))
13986 (if (and files (car files))
13987 files
13988 (org-agenda-files))))))))
13990 (defun org-make-tags-matcher (match)
13991 "Create the TAGS/TODO matcher form for the selection string MATCH.
13993 The variable `todo-only' is scoped dynamically into this function.
13994 It will be set to t if the matcher restricts matching to TODO entries,
13995 otherwise will not be touched.
13997 Returns a cons of the selection string MATCH and the constructed
13998 lisp form implementing the matcher. The matcher is to be evaluated
13999 at an Org entry, with point on the headline, and returns t if the
14000 entry matches the selection string MATCH. The returned lisp form
14001 references two variables with information about the entry, which
14002 must be bound around the form's evaluation: todo, the TODO keyword
14003 at the entry (or nil of none); and tags-list, the list of all tags
14004 at the entry including inherited ones. Additionally, the category
14005 of the entry (if any) must be specified as the text property
14006 'org-category on the headline.
14008 See also `org-scan-tags'.
14010 (declare (special todo-only))
14011 (unless (boundp 'todo-only)
14012 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14013 (unless match
14014 ;; Get a new match request, with completion against the global
14015 ;; tags table and the local tags in current buffer
14016 (let ((org-last-tags-completion-table
14017 (org-uniquify
14018 (delq nil (append (org-get-buffer-tags)
14019 (org-global-tags-completion-table))))))
14020 (setq match (org-completing-read-no-i
14021 "Match: " 'org-tags-completion-function nil nil nil
14022 'org-tags-history))))
14024 ;; Parse the string and create a lisp form
14025 (let ((match0 match)
14026 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14027 minus tag mm
14028 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14029 orterms term orlist re-p str-p level-p level-op time-p
14030 prop-p pn pv po gv rest)
14031 ;; Expand group tags
14032 (setq match (org-tags-expand match))
14033 (if (string-match "/+" match)
14034 ;; match contains also a todo-matching request
14035 (progn
14036 (setq tagsmatch (substring match 0 (match-beginning 0))
14037 todomatch (substring match (match-end 0)))
14038 (if (string-match "^!" todomatch)
14039 (setq todo-only t todomatch (substring todomatch 1)))
14040 (if (string-match "^\\s-*$" todomatch)
14041 (setq todomatch nil)))
14042 ;; only matching tags
14043 (setq tagsmatch match todomatch nil))
14045 ;; Make the tags matcher
14046 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14047 (setq tagsmatcher t)
14048 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14049 (while (setq term (pop orterms))
14050 (while (and (equal (substring term -1) "\\") orterms)
14051 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14052 (while (string-match re term)
14053 (setq rest (substring term (match-end 0))
14054 minus (and (match-end 1)
14055 (equal (match-string 1 term) "-"))
14056 tag (save-match-data (replace-regexp-in-string
14057 "\\\\-" "-"
14058 (match-string 2 term)))
14059 re-p (equal (string-to-char tag) ?{)
14060 level-p (match-end 4)
14061 prop-p (match-end 5)
14062 mm (cond
14063 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14064 (level-p
14065 (setq level-op (org-op-to-function (match-string 3 term)))
14066 `(,level-op level ,(string-to-number
14067 (match-string 4 term))))
14068 (prop-p
14069 (setq pn (match-string 5 term)
14070 po (match-string 6 term)
14071 pv (match-string 7 term)
14072 re-p (equal (string-to-char pv) ?{)
14073 str-p (equal (string-to-char pv) ?\")
14074 time-p (save-match-data
14075 (string-match "^\"[[<].*[]>]\"$" pv))
14076 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14077 (if time-p (setq pv (org-matcher-time pv)))
14078 (setq po (org-op-to-function po (if time-p 'time str-p)))
14079 (cond
14080 ((equal pn "CATEGORY")
14081 (setq gv '(get-text-property (point) 'org-category)))
14082 ((equal pn "TODO")
14083 (setq gv 'todo))
14085 (setq gv `(org-cached-entry-get nil ,pn))))
14086 (if re-p
14087 (if (eq po 'org<>)
14088 `(not (string-match ,pv (or ,gv "")))
14089 `(string-match ,pv (or ,gv "")))
14090 (if str-p
14091 `(,po (or ,gv "") ,pv)
14092 `(,po (string-to-number (or ,gv ""))
14093 ,(string-to-number pv) ))))
14094 (t `(member ,tag tags-list)))
14095 mm (if minus (list 'not mm) mm)
14096 term rest)
14097 (push mm tagsmatcher))
14098 (push (if (> (length tagsmatcher) 1)
14099 (cons 'and tagsmatcher)
14100 (car tagsmatcher))
14101 orlist)
14102 (setq tagsmatcher nil))
14103 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14104 (setq tagsmatcher
14105 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14106 ;; Make the todo matcher
14107 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14108 (setq todomatcher t)
14109 (setq orterms (org-split-string todomatch "|") orlist nil)
14110 (while (setq term (pop orterms))
14111 (while (string-match re term)
14112 (setq minus (and (match-end 1)
14113 (equal (match-string 1 term) "-"))
14114 kwd (match-string 2 term)
14115 re-p (equal (string-to-char kwd) ?{)
14116 term (substring term (match-end 0))
14117 mm (if re-p
14118 `(string-match ,(substring kwd 1 -1) todo)
14119 (list 'equal 'todo kwd))
14120 mm (if minus (list 'not mm) mm))
14121 (push mm todomatcher))
14122 (push (if (> (length todomatcher) 1)
14123 (cons 'and todomatcher)
14124 (car todomatcher))
14125 orlist)
14126 (setq todomatcher nil))
14127 (setq todomatcher (if (> (length orlist) 1)
14128 (cons 'or orlist) (car orlist))))
14130 ;; Return the string and lisp forms of the matcher
14131 (setq matcher (if todomatcher
14132 (list 'and tagsmatcher todomatcher)
14133 tagsmatcher))
14134 (when todo-only
14135 (setq matcher (list 'and '(member todo org-not-done-keywords)
14136 matcher)))
14137 (cons match0 matcher)))
14139 (defun org-tags-expand (match &optional single-as-list downcased)
14140 "Expand group tags in MATCH.
14142 This replaces every group tag in MATCH with a regexp tag search.
14143 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14144 will be replaced like this:
14146 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14147 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14148 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14150 Replacing by a regexp preserves the structure of the match.
14151 E.g., this expansion
14153 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14155 will match anything tagged with \"Lab\" and \"Home\", or tagged
14156 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14158 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14159 assumed to be a single group tag, and the function will return
14160 the list of tags in this group.
14162 When DOWNCASE is non-nil, expand downcased TAGS."
14163 (if org-group-tags
14164 (let* ((case-fold-search t)
14165 (stable org-mode-syntax-table)
14166 (tal (or org-tag-groups-alist-for-agenda
14167 org-tag-groups-alist))
14168 (tal (if downcased
14169 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14170 (tml (mapcar 'car tal))
14171 (rtnmatch match) rpl)
14172 ;; @ and _ are allowed as word-components in tags
14173 (modify-syntax-entry ?@ "w" stable)
14174 (modify-syntax-entry ?_ "w" stable)
14175 (while (and tml
14176 (string-match
14177 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14178 (regexp-opt tml) "\\>\\)") rtnmatch))
14179 (let* ((dir (match-string 1 rtnmatch))
14180 (tag (match-string 2 rtnmatch))
14181 (tag (if downcased (downcase tag) tag)))
14182 (setq tml (delete tag tml))
14183 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14184 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14185 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14186 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14187 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14188 (if single-as-list
14189 (or (reverse rpl) (list rtnmatch))
14190 rtnmatch))
14191 (if single-as-list (list (if downcased (downcase match) match))
14192 match)))
14194 (defun org-op-to-function (op &optional stringp)
14195 "Turn an operator into the appropriate function."
14196 (setq op
14197 (cond
14198 ((equal op "<" ) '(< string< org-time<))
14199 ((equal op ">" ) '(> org-string> org-time>))
14200 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14201 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14202 ((member op '("=" "==")) '(= string= org-time=))
14203 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14204 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14206 (defun org<> (a b) (not (= a b)))
14207 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14208 (defun org-string>= (a b) (not (string< a b)))
14209 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14210 (defun org-string<> (a b) (not (string= a b)))
14211 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14212 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14213 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14214 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14215 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14216 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14217 (defun org-2ft (s)
14218 "Convert S to a floating point time.
14219 If S is already a number, just return it. If it is a string, parse
14220 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14221 (cond
14222 ((numberp s) s)
14223 ((stringp s)
14224 (condition-case nil
14225 (float-time (apply 'encode-time (org-parse-time-string s)))
14226 (error 0.)))
14227 (t 0.)))
14229 (defun org-time-today ()
14230 "Time in seconds today at 0:00.
14231 Returns the float number of seconds since the beginning of the
14232 epoch to the beginning of today (00:00)."
14233 (float-time (apply 'encode-time
14234 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14236 (defun org-matcher-time (s)
14237 "Interpret a time comparison value."
14238 (save-match-data
14239 (cond
14240 ((string= s "<now>") (float-time))
14241 ((string= s "<today>") (org-time-today))
14242 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14243 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14244 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14245 (+ (org-time-today)
14246 (* (string-to-number (match-string 1 s))
14247 (cdr (assoc (match-string 2 s)
14248 '(("d" . 86400.0) ("w" . 604800.0)
14249 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14250 (t (org-2ft s)))))
14252 (defun org-match-any-p (re list)
14253 "Does re match any element of list?"
14254 (setq list (mapcar (lambda (x) (string-match re x)) list))
14255 (delq nil list))
14257 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14258 (defvar org-tags-overlay (make-overlay 1 1))
14259 (org-detach-overlay org-tags-overlay)
14261 (defun org-get-local-tags-at (&optional pos)
14262 "Get a list of tags defined in the current headline."
14263 (org-get-tags-at pos 'local))
14265 (defun org-get-local-tags ()
14266 "Get a list of tags defined in the current headline."
14267 (org-get-tags-at nil 'local))
14269 (defun org-get-tags-at (&optional pos local)
14270 "Get a list of all headline tags applicable at POS.
14271 POS defaults to point. If tags are inherited, the list contains
14272 the targets in the same sequence as the headlines appear, i.e.
14273 the tags of the current headline come last.
14274 When LOCAL is non-nil, only return tags from the current headline,
14275 ignore inherited ones."
14276 (interactive)
14277 (if (and org-trust-scanner-tags
14278 (or (not pos) (equal pos (point)))
14279 (not local))
14280 org-scanner-tags
14281 (let (tags ltags lastpos parent)
14282 (save-excursion
14283 (save-restriction
14284 (widen)
14285 (goto-char (or pos (point)))
14286 (save-match-data
14287 (catch 'done
14288 (condition-case nil
14289 (progn
14290 (org-back-to-heading t)
14291 (while (not (equal lastpos (point)))
14292 (setq lastpos (point))
14293 (when (looking-at
14294 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14295 (setq ltags (org-split-string
14296 (org-match-string-no-properties 1) ":"))
14297 (when parent
14298 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14299 (setq tags (append
14300 (if parent
14301 (org-remove-uninherited-tags ltags)
14302 ltags)
14303 tags)))
14304 (or org-use-tag-inheritance (throw 'done t))
14305 (if local (throw 'done t))
14306 (or (org-up-heading-safe) (error nil))
14307 (setq parent t)))
14308 (error nil)))))
14309 (if local
14310 tags
14311 (reverse (delete-dups
14312 (reverse (append
14313 (org-remove-uninherited-tags
14314 org-file-tags) tags)))))))))
14316 (defun org-add-prop-inherited (s)
14317 (add-text-properties 0 (length s) '(inherited t) s)
14320 (defun org-toggle-tag (tag &optional onoff)
14321 "Toggle the tag TAG for the current line.
14322 If ONOFF is `on' or `off', don't toggle but set to this state."
14323 (let (res current)
14324 (save-excursion
14325 (org-back-to-heading t)
14326 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14327 (point-at-eol) t)
14328 (progn
14329 (setq current (match-string 1))
14330 (replace-match ""))
14331 (setq current ""))
14332 (setq current (nreverse (org-split-string current ":")))
14333 (cond
14334 ((eq onoff 'on)
14335 (setq res t)
14336 (or (member tag current) (push tag current)))
14337 ((eq onoff 'off)
14338 (or (not (member tag current)) (setq current (delete tag current))))
14339 (t (if (member tag current)
14340 (setq current (delete tag current))
14341 (setq res t)
14342 (push tag current))))
14343 (end-of-line 1)
14344 (if current
14345 (progn
14346 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14347 (org-set-tags nil t))
14348 (delete-horizontal-space))
14349 (run-hooks 'org-after-tags-change-hook))
14350 res))
14352 (defun org-align-tags-here (to-col)
14353 ;; Assumes that this is a headline
14354 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14355 (beginning-of-line 1)
14356 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14357 (< pos (match-beginning 2)))
14358 (progn
14359 (setq tags-l (- (match-end 2) (match-beginning 2)))
14360 (goto-char (match-beginning 1))
14361 (insert " ")
14362 (delete-region (point) (1+ (match-beginning 2)))
14363 (setq ncol (max (current-column)
14364 (1+ col)
14365 (if (> to-col 0)
14366 to-col
14367 (- (abs to-col) tags-l))))
14368 (setq p (point))
14369 (insert (make-string (- ncol (current-column)) ?\ ))
14370 (setq ncol (current-column))
14371 (when indent-tabs-mode (tabify p (point-at-eol)))
14372 (org-move-to-column (min ncol col) t))
14373 (goto-char pos))))
14375 (defun org-set-tags-command (&optional arg just-align)
14376 "Call the set-tags command for the current entry."
14377 (interactive "P")
14378 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14379 (org-set-tags arg just-align)
14380 (save-excursion
14381 (unless (and (org-region-active-p)
14382 org-loop-over-headlines-in-active-region)
14383 (org-back-to-heading t))
14384 (org-set-tags arg just-align))))
14386 (defun org-set-tags-to (data)
14387 "Set the tags of the current entry to DATA, replacing the current tags.
14388 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14389 If DATA is nil or the empty string, any tags will be removed."
14390 (interactive "sTags: ")
14391 (setq data
14392 (cond
14393 ((eq data nil) "")
14394 ((equal data "") "")
14395 ((stringp data)
14396 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14397 ":"))
14398 ((listp data)
14399 (concat ":" (mapconcat 'identity data ":") ":"))))
14400 (when data
14401 (save-excursion
14402 (org-back-to-heading t)
14403 (when (looking-at org-complex-heading-regexp)
14404 (if (match-end 5)
14405 (progn
14406 (goto-char (match-beginning 5))
14407 (insert data)
14408 (delete-region (point) (point-at-eol))
14409 (org-set-tags nil 'align))
14410 (goto-char (point-at-eol))
14411 (insert " " data)
14412 (org-set-tags nil 'align)))
14413 (beginning-of-line 1)
14414 (if (looking-at ".*?\\([ \t]+\\)$")
14415 (delete-region (match-beginning 1) (match-end 1))))))
14417 (defun org-align-all-tags ()
14418 "Align the tags i all headings."
14419 (interactive)
14420 (save-excursion
14421 (or (ignore-errors (org-back-to-heading t))
14422 (outline-next-heading))
14423 (if (org-at-heading-p)
14424 (org-set-tags t)
14425 (message "No headings"))))
14427 (defvar org-indent-indentation-per-level)
14428 (defun org-set-tags (&optional arg just-align)
14429 "Set the tags for the current headline.
14430 With prefix ARG, realign all tags in headings in the current buffer."
14431 (interactive "P")
14432 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14433 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14434 'region-start-level 'region))
14435 org-loop-over-headlines-in-active-region)
14436 (org-map-entries
14437 ;; We don't use ARG and JUST-ALIGN here these args are not
14438 ;; useful when looping over headlines
14439 `(org-set-tags)
14440 org-loop-over-headlines-in-active-region
14441 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14442 (let* ((re org-outline-regexp-bol)
14443 (current (unless arg (org-get-tags-string)))
14444 (col (current-column))
14445 (org-setting-tags t)
14446 table current-tags inherited-tags ; computed below when needed
14447 tags p0 c0 c1 rpl di tc level)
14448 (if arg
14449 (save-excursion
14450 (goto-char (point-min))
14451 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14452 (while (re-search-forward re nil t)
14453 (org-set-tags nil t)
14454 (end-of-line 1)))
14455 (message "All tags realigned to column %d" org-tags-column))
14456 (if just-align
14457 (setq tags current)
14458 ;; Get a new set of tags from the user
14459 (save-excursion
14460 (setq table (append org-tag-persistent-alist
14461 (or org-tag-alist (org-get-buffer-tags))
14462 (and
14463 org-complete-tags-always-offer-all-agenda-tags
14464 (org-global-tags-completion-table
14465 (org-agenda-files))))
14466 org-last-tags-completion-table table
14467 current-tags (org-split-string current ":")
14468 inherited-tags (nreverse
14469 (nthcdr (length current-tags)
14470 (nreverse (org-get-tags-at))))
14471 tags
14472 (if (or (eq t org-use-fast-tag-selection)
14473 (and org-use-fast-tag-selection
14474 (delq nil (mapcar 'cdr table))))
14475 (org-fast-tag-selection
14476 current-tags inherited-tags table
14477 (if org-fast-tag-selection-include-todo
14478 org-todo-key-alist))
14479 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14480 (org-trim
14481 (org-icompleting-read "Tags: "
14482 'org-tags-completion-function
14483 nil nil current 'org-tags-history))))))
14484 (while (string-match "[-+&]+" tags)
14485 ;; No boolean logic, just a list
14486 (setq tags (replace-match ":" t t tags))))
14488 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14490 (if org-tags-sort-function
14491 (setq tags (mapconcat 'identity
14492 (sort (org-split-string
14493 tags (org-re "[^[:alnum:]_@#%]+"))
14494 org-tags-sort-function) ":")))
14496 (if (string-match "\\`[\t ]*\\'" tags)
14497 (setq tags "")
14498 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14499 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14501 ;; Insert new tags at the correct column
14502 (beginning-of-line 1)
14503 (setq level (or (and (looking-at org-outline-regexp)
14504 (- (match-end 0) (point) 1))
14506 (cond
14507 ((and (equal current "") (equal tags "")))
14508 ((re-search-forward
14509 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14510 (point-at-eol) t)
14511 (if (equal tags "")
14512 (setq rpl "")
14513 (goto-char (match-beginning 0))
14514 (setq c0 (current-column)
14515 ;; compute offset for the case of org-indent-mode active
14516 di (if org-indent-mode
14517 (* (1- org-indent-indentation-per-level) (1- level))
14519 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14520 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14521 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14522 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14523 (replace-match rpl t t)
14524 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14525 tags)
14526 (t (error "Tags alignment failed")))
14527 (org-move-to-column col)
14528 (unless just-align
14529 (run-hooks 'org-after-tags-change-hook))))))
14531 (defun org-change-tag-in-region (beg end tag off)
14532 "Add or remove TAG for each entry in the region.
14533 This works in the agenda, and also in an org-mode buffer."
14534 (interactive
14535 (list (region-beginning) (region-end)
14536 (let ((org-last-tags-completion-table
14537 (if (derived-mode-p 'org-mode)
14538 (org-uniquify
14539 (delq nil (append (org-get-buffer-tags)
14540 (org-global-tags-completion-table))))
14541 (org-global-tags-completion-table))))
14542 (org-icompleting-read
14543 "Tag: " 'org-tags-completion-function nil nil nil
14544 'org-tags-history))
14545 (progn
14546 (message "[s]et or [r]emove? ")
14547 (equal (read-char-exclusive) ?r))))
14548 (if (fboundp 'deactivate-mark) (deactivate-mark))
14549 (let ((agendap (equal major-mode 'org-agenda-mode))
14550 l1 l2 m buf pos newhead (cnt 0))
14551 (goto-char end)
14552 (setq l2 (1- (org-current-line)))
14553 (goto-char beg)
14554 (setq l1 (org-current-line))
14555 (loop for l from l1 to l2 do
14556 (org-goto-line l)
14557 (setq m (get-text-property (point) 'org-hd-marker))
14558 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14559 (and agendap m))
14560 (setq buf (if agendap (marker-buffer m) (current-buffer))
14561 pos (if agendap m (point)))
14562 (with-current-buffer buf
14563 (save-excursion
14564 (save-restriction
14565 (goto-char pos)
14566 (setq cnt (1+ cnt))
14567 (org-toggle-tag tag (if off 'off 'on))
14568 (setq newhead (org-get-heading)))))
14569 (and agendap (org-agenda-change-all-lines newhead m))))
14570 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14572 (defun org-tags-completion-function (string predicate &optional flag)
14573 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14574 (confirm (lambda (x) (stringp (car x)))))
14575 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14576 (setq s1 (match-string 1 string)
14577 s2 (match-string 2 string))
14578 (setq s1 "" s2 string))
14579 (cond
14580 ((eq flag nil)
14581 ;; try completion
14582 (setq rtn (try-completion s2 ctable confirm))
14583 (if (stringp rtn)
14584 (setq rtn
14585 (concat s1 s2 (substring rtn (length s2))
14586 (if (and org-add-colon-after-tag-completion
14587 (assoc rtn ctable))
14588 ":" ""))))
14589 rtn)
14590 ((eq flag t)
14591 ;; all-completions
14592 (all-completions s2 ctable confirm))
14593 ((eq flag 'lambda)
14594 ;; exact match?
14595 (assoc s2 ctable)))))
14597 (defun org-fast-tag-insert (kwd tags face &optional end)
14598 "Insert KDW, and the TAGS, the latter with face FACE.
14599 Also insert END."
14600 (insert (format "%-12s" (concat kwd ":"))
14601 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14602 (or end "")))
14604 (defun org-fast-tag-show-exit (flag)
14605 (save-excursion
14606 (org-goto-line 3)
14607 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14608 (replace-match ""))
14609 (when flag
14610 (end-of-line 1)
14611 (org-move-to-column (- (window-width) 19) t)
14612 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14614 (defun org-set-current-tags-overlay (current prefix)
14615 "Add an overlay to CURRENT tag with PREFIX."
14616 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14617 (if (featurep 'xemacs)
14618 (org-overlay-display org-tags-overlay (concat prefix s)
14619 'secondary-selection)
14620 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14621 (org-overlay-display org-tags-overlay (concat prefix s)))))
14623 (defvar org-last-tag-selection-key nil)
14624 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14625 "Fast tag selection with single keys.
14626 CURRENT is the current list of tags in the headline, INHERITED is the
14627 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14628 possibly with grouping information. TODO-TABLE is a similar table with
14629 TODO keywords, should these have keys assigned to them.
14630 If the keys are nil, a-z are automatically assigned.
14631 Returns the new tags string, or nil to not change the current settings."
14632 (let* ((fulltable (append table todo-table))
14633 (maxlen (apply 'max (mapcar
14634 (lambda (x)
14635 (if (stringp (car x)) (string-width (car x)) 0))
14636 fulltable)))
14637 (buf (current-buffer))
14638 (expert (eq org-fast-tag-selection-single-key 'expert))
14639 (buffer-tags nil)
14640 (fwidth (+ maxlen 3 1 3))
14641 (ncol (/ (- (window-width) 4) fwidth))
14642 (i-face 'org-done)
14643 (c-face 'org-todo)
14644 tg cnt e c char c1 c2 ntable tbl rtn
14645 ov-start ov-end ov-prefix
14646 (exit-after-next org-fast-tag-selection-single-key)
14647 (done-keywords org-done-keywords)
14648 groups ingroup)
14649 (save-excursion
14650 (beginning-of-line 1)
14651 (if (looking-at
14652 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14653 (setq ov-start (match-beginning 1)
14654 ov-end (match-end 1)
14655 ov-prefix "")
14656 (setq ov-start (1- (point-at-eol))
14657 ov-end (1+ ov-start))
14658 (skip-chars-forward "^\n\r")
14659 (setq ov-prefix
14660 (concat
14661 (buffer-substring (1- (point)) (point))
14662 (if (> (current-column) org-tags-column)
14664 (make-string (- org-tags-column (current-column)) ?\ ))))))
14665 (move-overlay org-tags-overlay ov-start ov-end)
14666 (save-window-excursion
14667 (if expert
14668 (set-buffer (get-buffer-create " *Org tags*"))
14669 (delete-other-windows)
14670 (split-window-vertically)
14671 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14672 (erase-buffer)
14673 (org-set-local 'org-done-keywords done-keywords)
14674 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14675 (org-fast-tag-insert "Current" current c-face "\n\n")
14676 (org-fast-tag-show-exit exit-after-next)
14677 (org-set-current-tags-overlay current ov-prefix)
14678 (setq tbl fulltable char ?a cnt 0)
14679 (while (setq e (pop tbl))
14680 (cond
14681 ((equal (car e) :startgroup)
14682 (push '() groups) (setq ingroup t)
14683 (when (not (= cnt 0))
14684 (setq cnt 0)
14685 (insert "\n"))
14686 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14687 ((equal (car e) :endgroup)
14688 (setq ingroup nil cnt 0)
14689 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14690 ((equal e '(:newline))
14691 (when (not (= cnt 0))
14692 (setq cnt 0)
14693 (insert "\n")
14694 (setq e (car tbl))
14695 (while (equal (car tbl) '(:newline))
14696 (insert "\n")
14697 (setq tbl (cdr tbl)))))
14698 ((equal e '(:grouptags)) nil)
14700 (setq tg (copy-sequence (car e)) c2 nil)
14701 (if (cdr e)
14702 (setq c (cdr e))
14703 ;; automatically assign a character.
14704 (setq c1 (string-to-char
14705 (downcase (substring
14706 tg (if (= (string-to-char tg) ?@) 1 0)))))
14707 (if (or (rassoc c1 ntable) (rassoc c1 table))
14708 (while (or (rassoc char ntable) (rassoc char table))
14709 (setq char (1+ char)))
14710 (setq c2 c1))
14711 (setq c (or c2 char)))
14712 (if ingroup (push tg (car groups)))
14713 (setq tg (org-add-props tg nil 'face
14714 (cond
14715 ((not (assoc tg table))
14716 (org-get-todo-face tg))
14717 ((member tg current) c-face)
14718 ((member tg inherited) i-face))))
14719 (if (equal (caar tbl) :grouptags)
14720 (org-add-props tg nil 'face 'org-tag-group))
14721 (if (and (= cnt 0) (not ingroup)) (insert " "))
14722 (insert "[" c "] " tg (make-string
14723 (- fwidth 4 (length tg)) ?\ ))
14724 (push (cons tg c) ntable)
14725 (when (= (setq cnt (1+ cnt)) ncol)
14726 (insert "\n")
14727 (if ingroup (insert " "))
14728 (setq cnt 0)))))
14729 (setq ntable (nreverse ntable))
14730 (insert "\n")
14731 (goto-char (point-min))
14732 (if (not expert) (org-fit-window-to-buffer))
14733 (setq rtn
14734 (catch 'exit
14735 (while t
14736 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14737 (if (not groups) "no " "")
14738 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14739 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14740 (setq org-last-tag-selection-key c)
14741 (cond
14742 ((= c ?\r) (throw 'exit t))
14743 ((= c ?!)
14744 (setq groups (not groups))
14745 (goto-char (point-min))
14746 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14747 ((= c ?\C-c)
14748 (if (not expert)
14749 (org-fast-tag-show-exit
14750 (setq exit-after-next (not exit-after-next)))
14751 (setq expert nil)
14752 (delete-other-windows)
14753 (set-window-buffer (split-window-vertically) " *Org tags*")
14754 (org-switch-to-buffer-other-window " *Org tags*")
14755 (org-fit-window-to-buffer)))
14756 ((or (= c ?\C-g)
14757 (and (= c ?q) (not (rassoc c ntable))))
14758 (org-detach-overlay org-tags-overlay)
14759 (setq quit-flag t))
14760 ((= c ?\ )
14761 (setq current nil)
14762 (if exit-after-next (setq exit-after-next 'now)))
14763 ((= c ?\t)
14764 (condition-case nil
14765 (setq tg (org-icompleting-read
14766 "Tag: "
14767 (or buffer-tags
14768 (with-current-buffer buf
14769 (org-get-buffer-tags)))))
14770 (quit (setq tg "")))
14771 (when (string-match "\\S-" tg)
14772 (add-to-list 'buffer-tags (list tg))
14773 (if (member tg current)
14774 (setq current (delete tg current))
14775 (push tg current)))
14776 (if exit-after-next (setq exit-after-next 'now)))
14777 ((setq e (rassoc c todo-table) tg (car e))
14778 (with-current-buffer buf
14779 (save-excursion (org-todo tg)))
14780 (if exit-after-next (setq exit-after-next 'now)))
14781 ((setq e (rassoc c ntable) tg (car e))
14782 (if (member tg current)
14783 (setq current (delete tg current))
14784 (loop for g in groups do
14785 (if (member tg g)
14786 (mapc (lambda (x)
14787 (setq current (delete x current)))
14788 g)))
14789 (push tg current))
14790 (if exit-after-next (setq exit-after-next 'now))))
14792 ;; Create a sorted list
14793 (setq current
14794 (sort current
14795 (lambda (a b)
14796 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14797 (if (eq exit-after-next 'now) (throw 'exit t))
14798 (goto-char (point-min))
14799 (beginning-of-line 2)
14800 (delete-region (point) (point-at-eol))
14801 (org-fast-tag-insert "Current" current c-face)
14802 (org-set-current-tags-overlay current ov-prefix)
14803 (while (re-search-forward
14804 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14805 (setq tg (match-string 1))
14806 (add-text-properties
14807 (match-beginning 1) (match-end 1)
14808 (list 'face
14809 (cond
14810 ((member tg current) c-face)
14811 ((member tg inherited) i-face)
14812 (t (get-text-property (match-beginning 1) 'face))))))
14813 (goto-char (point-min)))))
14814 (org-detach-overlay org-tags-overlay)
14815 (if rtn
14816 (mapconcat 'identity current ":")
14817 nil))))
14819 (defun org-get-tags-string ()
14820 "Get the TAGS string in the current headline."
14821 (unless (org-at-heading-p t)
14822 (user-error "Not on a heading"))
14823 (save-excursion
14824 (beginning-of-line 1)
14825 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14826 (org-match-string-no-properties 1)
14827 "")))
14829 (defun org-get-tags ()
14830 "Get the list of tags specified in the current headline."
14831 (org-split-string (org-get-tags-string) ":"))
14833 (defun org-get-buffer-tags ()
14834 "Get a table of all tags used in the buffer, for completion."
14835 (let (tags)
14836 (save-excursion
14837 (goto-char (point-min))
14838 (while (re-search-forward
14839 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14840 (when (equal (char-after (point-at-bol 0)) ?*)
14841 (mapc (lambda (x) (add-to-list 'tags x))
14842 (org-split-string (org-match-string-no-properties 1) ":")))))
14843 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14844 (mapcar 'list tags)))
14846 ;;;; The mapping API
14848 (defun org-map-entries (func &optional match scope &rest skip)
14849 "Call FUNC at each headline selected by MATCH in SCOPE.
14851 FUNC is a function or a lisp form. The function will be called without
14852 arguments, with the cursor positioned at the beginning of the headline.
14853 The return values of all calls to the function will be collected and
14854 returned as a list.
14856 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14857 does not need to preserve point. After evaluation, the cursor will be
14858 moved to the end of the line (presumably of the headline of the
14859 processed entry) and search continues from there. Under some
14860 circumstances, this may not produce the wanted results. For example,
14861 if you have removed (e.g. archived) the current (sub)tree it could
14862 mean that the next entry will be skipped entirely. In such cases, you
14863 can specify the position from where search should continue by making
14864 FUNC set the variable `org-map-continue-from' to the desired buffer
14865 position.
14867 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14868 Only headlines that are matched by this query will be considered during
14869 the iteration. When MATCH is nil or t, all headlines will be
14870 visited by the iteration.
14872 SCOPE determines the scope of this command. It can be any of:
14874 nil The current buffer, respecting the restriction if any
14875 tree The subtree started with the entry at point
14876 region The entries within the active region, if any
14877 region-start-level
14878 The entries within the active region, but only those at
14879 the same level than the first one.
14880 file The current buffer, without restriction
14881 file-with-archives
14882 The current buffer, and any archives associated with it
14883 agenda All agenda files
14884 agenda-with-archives
14885 All agenda files with any archive files associated with them
14886 \(file1 file2 ...)
14887 If this is a list, all files in the list will be scanned
14889 The remaining args are treated as settings for the skipping facilities of
14890 the scanner. The following items can be given here:
14892 archive skip trees with the archive tag
14893 comment skip trees with the COMMENT keyword
14894 function or Emacs Lisp form:
14895 will be used as value for `org-agenda-skip-function', so
14896 whenever the function returns a position, FUNC will not be
14897 called for that entry and search will continue from the
14898 position returned
14900 If your function needs to retrieve the tags including inherited tags
14901 at the *current* entry, you can use the value of the variable
14902 `org-scanner-tags' which will be much faster than getting the value
14903 with `org-get-tags-at'. If your function gets properties with
14904 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14905 to t around the call to `org-entry-properties' to get the same speedup.
14906 Note that if your function moves around to retrieve tags and properties at
14907 a *different* entry, you cannot use these techniques."
14908 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14909 (not (org-region-active-p)))
14910 (let* ((org-agenda-archives-mode nil) ; just to make sure
14911 (org-agenda-skip-archived-trees (memq 'archive skip))
14912 (org-agenda-skip-comment-trees (memq 'comment skip))
14913 (org-agenda-skip-function
14914 (car (org-delete-all '(comment archive) skip)))
14915 (org-tags-match-list-sublevels t)
14916 (start-level (eq scope 'region-start-level))
14917 matcher file res
14918 org-todo-keywords-for-agenda
14919 org-done-keywords-for-agenda
14920 org-todo-keyword-alist-for-agenda
14921 org-drawers-for-agenda
14922 org-tag-alist-for-agenda
14923 todo-only)
14925 (cond
14926 ((eq match t) (setq matcher t))
14927 ((eq match nil) (setq matcher t))
14928 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14930 (save-window-excursion
14931 (save-restriction
14932 (cond ((eq scope 'tree)
14933 (org-back-to-heading t)
14934 (org-narrow-to-subtree)
14935 (setq scope nil))
14936 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14937 (org-region-active-p))
14938 ;; If needed, set start-level to a string like "2"
14939 (when start-level
14940 (save-excursion
14941 (goto-char (region-beginning))
14942 (unless (org-at-heading-p) (outline-next-heading))
14943 (setq start-level (org-current-level))))
14944 (narrow-to-region (region-beginning)
14945 (save-excursion
14946 (goto-char (region-end))
14947 (unless (and (bolp) (org-at-heading-p))
14948 (outline-next-heading))
14949 (point)))
14950 (setq scope nil)))
14952 (if (not scope)
14953 (progn
14954 (org-agenda-prepare-buffers
14955 (list (buffer-file-name (current-buffer))))
14956 (setq res (org-scan-tags func matcher todo-only start-level)))
14957 ;; Get the right scope
14958 (cond
14959 ((and scope (listp scope) (symbolp (car scope)))
14960 (setq scope (eval scope)))
14961 ((eq scope 'agenda)
14962 (setq scope (org-agenda-files t)))
14963 ((eq scope 'agenda-with-archives)
14964 (setq scope (org-agenda-files t))
14965 (setq scope (org-add-archive-files scope)))
14966 ((eq scope 'file)
14967 (setq scope (list (buffer-file-name))))
14968 ((eq scope 'file-with-archives)
14969 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14970 (org-agenda-prepare-buffers scope)
14971 (while (setq file (pop scope))
14972 (with-current-buffer (org-find-base-buffer-visiting file)
14973 (save-excursion
14974 (save-restriction
14975 (widen)
14976 (goto-char (point-min))
14977 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14978 res)))
14980 ;;;; Properties
14982 ;;; Setting and retrieving properties
14984 (defconst org-special-properties
14985 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14986 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14987 "The special properties valid in Org-mode.
14989 These are properties that are not defined in the property drawer,
14990 but in some other way.")
14992 (defconst org-default-properties
14993 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14994 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14995 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14996 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14997 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14998 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14999 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15000 "Some properties that are used by Org-mode for various purposes.
15001 Being in this list makes sure that they are offered for completion.")
15003 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15004 "Regular expression matching the first line of a property drawer.")
15006 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15007 "Regular expression matching the last line of a property drawer.")
15009 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15010 "Regular expression matching the first line of a property drawer.")
15012 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15013 "Regular expression matching the first line of a property drawer.")
15015 (defconst org-property-drawer-re
15016 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15017 org-property-end-re "\\)\n?")
15018 "Matches an entire property drawer.")
15020 (defconst org-clock-drawer-re
15021 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15022 org-property-end-re "\\)\n?")
15023 "Matches an entire clock drawer.")
15025 (defsubst org-re-property (property)
15026 "Return a regexp matching a PROPERTY line.
15027 Match group 1 will be set to the value."
15028 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15030 (defsubst org-re-property-keyword (property)
15031 "Return a regexp matching a PROPERTY line, possibly with no
15032 value for the property."
15033 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15035 (defun org-property-action ()
15036 "Do an action on properties."
15037 (interactive)
15038 (let (c)
15039 (org-at-property-p)
15040 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15041 (setq c (read-char-exclusive))
15042 (cond
15043 ((equal c ?s)
15044 (call-interactively 'org-set-property))
15045 ((equal c ?d)
15046 (call-interactively 'org-delete-property))
15047 ((equal c ?D)
15048 (call-interactively 'org-delete-property-globally))
15049 ((equal c ?c)
15050 (call-interactively 'org-compute-property-at-point))
15051 (t (user-error "No such property action %c" c)))))
15053 (defun org-inc-effort ()
15054 "Increment the value of the effort property in the current entry."
15055 (interactive)
15056 (org-set-effort nil t))
15058 (defvar org-clock-effort) ;; Defined in org-clock.el
15059 (defvar org-clock-current-task) ;; Defined in org-clock.el
15060 (defun org-set-effort (&optional value increment)
15061 "Set the effort property of the current entry.
15062 With numerical prefix arg, use the nth allowed value, 0 stands for the
15063 10th allowed value.
15065 When INCREMENT is non-nil, set the property to the next allowed value."
15066 (interactive "P")
15067 (if (equal value 0) (setq value 10))
15068 (let* ((completion-ignore-case t)
15069 (prop org-effort-property)
15070 (cur (org-entry-get nil prop))
15071 (allowed (org-property-get-allowed-values nil prop 'table))
15072 (existing (mapcar 'list (org-property-values prop)))
15073 (heading (nth 4 (org-heading-components)))
15075 (val (cond
15076 ((stringp value) value)
15077 ((and allowed (integerp value))
15078 (or (car (nth (1- value) allowed))
15079 (car (org-last allowed))))
15080 ((and allowed increment)
15081 (or (caadr (member (list cur) allowed))
15082 (user-error "Allowed effort values are not set")))
15083 (allowed
15084 (message "Select 1-9,0, [RET%s]: %s"
15085 (if cur (concat "=" cur) "")
15086 (mapconcat 'car allowed " "))
15087 (setq rpl (read-char-exclusive))
15088 (if (equal rpl ?\r)
15090 (setq rpl (- rpl ?0))
15091 (if (equal rpl 0) (setq rpl 10))
15092 (if (and (> rpl 0) (<= rpl (length allowed)))
15093 (car (nth (1- rpl) allowed))
15094 (org-completing-read "Effort: " allowed nil))))
15096 (let (org-completion-use-ido org-completion-use-iswitchb)
15097 (org-completing-read
15098 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15099 (concat "[" cur "]") "")
15100 ": ")
15101 existing nil nil "" nil cur))))))
15102 (unless (equal (org-entry-get nil prop) val)
15103 (org-entry-put nil prop val))
15104 (save-excursion
15105 (org-back-to-heading t)
15106 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15107 (when (string= heading org-clock-current-task)
15108 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15109 (org-clock-update-mode-line))
15110 (message "%s is now %s" prop val)))
15112 (defun org-at-property-p ()
15113 "Is cursor inside a property drawer?"
15114 (save-excursion
15115 (when (equal 'node-property (car (org-element-at-point)))
15116 (beginning-of-line 1)
15117 (looking-at org-property-re))))
15119 (defun org-get-property-block (&optional beg end force)
15120 "Return the (beg . end) range of the body of the property drawer.
15121 BEG and END are the beginning and end of the current subtree, or of
15122 the part before the first headline. If they are not given, they will
15123 be found. If the drawer does not exist and FORCE is non-nil, create
15124 the drawer."
15125 (catch 'exit
15126 (save-excursion
15127 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15128 (progn (org-back-to-heading t) (point))))
15129 (end (or end (and (not (outline-next-heading)) (point-max))
15130 (point))))
15131 (goto-char beg)
15132 (if (re-search-forward org-property-start-re end t)
15133 (setq beg (1+ (match-end 0)))
15134 (if force
15135 (save-excursion
15136 (org-insert-property-drawer)
15137 (setq end (progn (outline-next-heading) (point))))
15138 (throw 'exit nil))
15139 (goto-char beg)
15140 (if (re-search-forward org-property-start-re end t)
15141 (setq beg (1+ (match-end 0)))))
15142 (if (re-search-forward org-property-end-re end t)
15143 (setq end (match-beginning 0))
15144 (or force (throw 'exit nil))
15145 (goto-char beg)
15146 (setq end beg)
15147 (org-indent-line)
15148 (insert ":END:\n"))
15149 (cons beg end)))))
15151 (defun org-entry-properties (&optional pom which specific)
15152 "Get all properties of the entry at point-or-marker POM.
15153 This includes the TODO keyword, the tags, time strings for deadline,
15154 scheduled, and clocking, and any additional properties defined in the
15155 entry. The return value is an alist, keys may occur multiple times
15156 if the property key was used several times.
15157 POM may also be nil, in which case the current entry is used.
15158 If WHICH is nil or `all', get all properties. If WHICH is
15159 `special' or `standard', only get that subclass. If WHICH
15160 is a string only get exactly this property. SPECIFIC can be a string, the
15161 specific property we are interested in. Specifying it can speed
15162 things up because then unnecessary parsing is avoided."
15163 (setq which (or which 'all))
15164 (org-with-point-at pom
15165 (let ((clockstr (substring org-clock-string 0 -1))
15166 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15167 (case-fold-search nil)
15168 beg end range props sum-props key key1 value string clocksum clocksumt)
15169 (save-excursion
15170 (when (condition-case nil
15171 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15172 (error nil))
15173 (setq beg (point))
15174 (setq sum-props (get-text-property (point) 'org-summaries))
15175 (setq clocksum (get-text-property (point) :org-clock-minutes)
15176 clocksumt (get-text-property (point) :org-clock-minutes-today))
15177 (outline-next-heading)
15178 (setq end (point))
15179 (when (memq which '(all special))
15180 ;; Get the special properties, like TODO and tags
15181 (goto-char beg)
15182 (when (and (or (not specific) (string= specific "TODO"))
15183 (looking-at org-todo-line-regexp) (match-end 2))
15184 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15185 (when (and (or (not specific) (string= specific "PRIORITY"))
15186 (looking-at org-priority-regexp))
15187 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15188 (when (or (not specific) (string= specific "FILE"))
15189 (push (cons "FILE" buffer-file-name) props))
15190 (when (and (or (not specific) (string= specific "TAGS"))
15191 (setq value (org-get-tags-string))
15192 (string-match "\\S-" value))
15193 (push (cons "TAGS" value) props))
15194 (when (and (or (not specific) (string= specific "ALLTAGS"))
15195 (setq value (org-get-tags-at)))
15196 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15197 ":"))
15198 props))
15199 (when (or (not specific) (string= specific "BLOCKED"))
15200 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15201 (when (or (not specific)
15202 (member specific
15203 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15204 "TIMESTAMP" "TIMESTAMP_IA")))
15205 (catch 'match
15206 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15207 (setq key (if (match-end 1)
15208 (substring (org-match-string-no-properties 1)
15209 0 -1))
15210 string (if (equal key clockstr)
15211 (org-trim
15212 (buffer-substring-no-properties
15213 (match-beginning 3) (goto-char
15214 (point-at-eol))))
15215 (substring (org-match-string-no-properties 3)
15216 1 -1)))
15217 ;; Get the correct property name from the key. This is
15218 ;; necessary if the user has configured time keywords.
15219 (setq key1 (concat key ":"))
15220 (cond
15221 ((not key)
15222 (setq key
15223 (if (= (char-after (match-beginning 3)) ?\[)
15224 "TIMESTAMP_IA" "TIMESTAMP")))
15225 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15226 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15227 ((equal key1 org-closed-string) (setq key "CLOSED"))
15228 ((equal key1 org-clock-string) (setq key "CLOCK")))
15229 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15230 (progn
15231 (push (cons key string) props)
15232 ;; no need to search further if match is found
15233 (throw 'match t))
15234 (when (or (equal key "CLOCK") (not (assoc key props)))
15235 (push (cons key string) props)))))))
15237 (when (memq which '(all standard))
15238 ;; Get the standard properties, like :PROP: ...
15239 (setq range (org-get-property-block beg end))
15240 (when range
15241 (goto-char (car range))
15242 (while (re-search-forward org-property-re
15243 (cdr range) t)
15244 (setq key (org-match-string-no-properties 2)
15245 value (org-trim (or (org-match-string-no-properties 3) "")))
15246 (unless (member key excluded)
15247 (push (cons key (or value "")) props)))))
15248 (if clocksum
15249 (push (cons "CLOCKSUM"
15250 (org-columns-number-to-string (/ (float clocksum) 60.)
15251 'add_times))
15252 props))
15253 (if clocksumt
15254 (push (cons "CLOCKSUM_T"
15255 (org-columns-number-to-string (/ (float clocksumt) 60.)
15256 'add_times))
15257 props))
15258 (unless (assoc "CATEGORY" props)
15259 (push (cons "CATEGORY" (org-get-category)) props))
15260 (append sum-props (nreverse props)))))))
15262 (defun org-entry-get (pom property &optional inherit literal-nil)
15263 "Get value of PROPERTY for entry or content at point-or-marker POM.
15264 If INHERIT is non-nil and the entry does not have the property,
15265 then also check higher levels of the hierarchy.
15266 If INHERIT is the symbol `selective', use inheritance only if the setting
15267 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15268 If the property is present but empty, the return value is the empty string.
15269 If the property is not present at all, nil is returned.
15271 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15272 do not interpret it as the list atom nil. This is used for inheritance
15273 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15274 (org-with-point-at pom
15275 (if (and inherit (if (eq inherit 'selective)
15276 (org-property-inherit-p property)
15278 (org-entry-get-with-inheritance property literal-nil)
15279 (if (member property org-special-properties)
15280 ;; We need a special property. Use `org-entry-properties' to
15281 ;; retrieve it, but specify the wanted property
15282 (cdr (assoc property (org-entry-properties nil 'special property)))
15283 (let ((range (org-get-property-block)))
15284 (when (and range (not (eq (car range) (cdr range))))
15285 (let* ((props (list (or (assoc property org-file-properties)
15286 (assoc property org-global-properties)
15287 (assoc property org-global-properties-fixed))))
15288 (ap (lambda (key)
15289 (when (re-search-forward
15290 (org-re-property key) (cdr range) t)
15291 (setq props
15292 (org-update-property-plist
15294 (if (match-end 1)
15295 (org-match-string-no-properties 1) "")
15296 props)))))
15297 val)
15298 (goto-char (car range))
15299 (funcall ap property)
15300 (goto-char (car range))
15301 (while (funcall ap (concat property "+")))
15302 (setq val (cdr (assoc property props)))
15303 (when val (if literal-nil val (org-not-nil val))))))))))
15305 (defun org-property-or-variable-value (var &optional inherit)
15306 "Check if there is a property fixing the value of VAR.
15307 If yes, return this value. If not, return the current value of the variable."
15308 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15309 (if (and prop (stringp prop) (string-match "\\S-" prop))
15310 (read prop)
15311 (symbol-value var))))
15313 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15314 "Delete the property PROPERTY from entry at point-or-marker POM.
15315 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15316 an empty drawer to delete."
15317 (org-with-point-at pom
15318 (if (member property org-special-properties)
15319 nil ; cannot delete these properties.
15320 (let ((range (org-get-property-block)))
15321 (if (and range
15322 (goto-char (car range))
15323 (re-search-forward
15324 (org-re-property property)
15325 (cdr range) t))
15326 (progn
15327 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15328 (and delete-empty-drawer
15329 (org-remove-empty-drawer-at
15330 delete-empty-drawer (car range)))
15332 nil)))))
15334 ;; Multi-values properties are properties that contain multiple values
15335 ;; These values are assumed to be single words, separated by whitespace.
15336 (defun org-entry-add-to-multivalued-property (pom property value)
15337 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15338 (let* ((old (org-entry-get pom property))
15339 (values (and old (org-split-string old "[ \t]"))))
15340 (setq value (org-entry-protect-space value))
15341 (unless (member value values)
15342 (setq values (append values (list value)))
15343 (org-entry-put pom property
15344 (mapconcat 'identity values " ")))))
15346 (defun org-entry-remove-from-multivalued-property (pom property value)
15347 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15348 (let* ((old (org-entry-get pom property))
15349 (values (and old (org-split-string old "[ \t]"))))
15350 (setq value (org-entry-protect-space value))
15351 (when (member value values)
15352 (setq values (delete value values))
15353 (org-entry-put pom property
15354 (mapconcat 'identity values " ")))))
15356 (defun org-entry-member-in-multivalued-property (pom property value)
15357 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15358 (let* ((old (org-entry-get pom property))
15359 (values (and old (org-split-string old "[ \t]"))))
15360 (setq value (org-entry-protect-space value))
15361 (member value values)))
15363 (defun org-entry-get-multivalued-property (pom property)
15364 "Return a list of values in a multivalued property."
15365 (let* ((value (org-entry-get pom property))
15366 (values (and value (org-split-string value "[ \t]"))))
15367 (mapcar 'org-entry-restore-space values)))
15369 (defun org-entry-put-multivalued-property (pom property &rest values)
15370 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15371 VALUES should be a list of strings. Spaces will be protected."
15372 (org-entry-put pom property
15373 (mapconcat 'org-entry-protect-space values " "))
15374 (let* ((value (org-entry-get pom property))
15375 (values (and value (org-split-string value "[ \t]"))))
15376 (mapcar 'org-entry-restore-space values)))
15378 (defun org-entry-protect-space (s)
15379 "Protect spaces and newline in string S."
15380 (while (string-match " " s)
15381 (setq s (replace-match "%20" t t s)))
15382 (while (string-match "\n" s)
15383 (setq s (replace-match "%0A" t t s)))
15386 (defun org-entry-restore-space (s)
15387 "Restore spaces and newline in string S."
15388 (while (string-match "%20" s)
15389 (setq s (replace-match " " t t s)))
15390 (while (string-match "%0A" s)
15391 (setq s (replace-match "\n" t t s)))
15394 (defvar org-entry-property-inherited-from (make-marker)
15395 "Marker pointing to the entry from where a property was inherited.
15396 Each call to `org-entry-get-with-inheritance' will set this marker to the
15397 location of the entry where the inheritance search matched. If there was
15398 no match, the marker will point nowhere.
15399 Note that also `org-entry-get' calls this function, if the INHERIT flag
15400 is set.")
15402 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15403 "Get PROPERTY of entry or content at point, search higher levels if needed.
15404 The search will stop at the first ancestor which has the property defined.
15405 If the value found is \"nil\", return nil to show that the property
15406 should be considered as undefined (this is the meaning of nil here).
15407 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15408 (move-marker org-entry-property-inherited-from nil)
15409 (let (tmp)
15410 (save-excursion
15411 (save-restriction
15412 (widen)
15413 (catch 'ex
15414 (while t
15415 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15416 (or (ignore-errors (org-back-to-heading t))
15417 (goto-char (point-min)))
15418 (move-marker org-entry-property-inherited-from (point))
15419 (throw 'ex tmp))
15420 (or (ignore-errors (org-up-heading-safe))
15421 (throw 'ex nil))))))
15422 (setq tmp (or tmp
15423 (cdr (assoc property org-file-properties))
15424 (cdr (assoc property org-global-properties))
15425 (cdr (assoc property org-global-properties-fixed))))
15426 (if literal-nil tmp (org-not-nil tmp))))
15428 (defvar org-property-changed-functions nil
15429 "Hook called when the value of a property has changed.
15430 Each hook function should accept two arguments, the name of the property
15431 and the new value.")
15433 (defun org-entry-put (pom property value)
15434 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15435 (org-with-point-at pom
15436 (org-back-to-heading t)
15437 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15438 range)
15439 (cond
15440 ((equal property "TODO")
15441 (when (and (stringp value) (string-match "\\S-" value)
15442 (not (member value org-todo-keywords-1)))
15443 (user-error "\"%s\" is not a valid TODO state" value))
15444 (if (or (not value)
15445 (not (string-match "\\S-" value)))
15446 (setq value 'none))
15447 (org-todo value)
15448 (org-set-tags nil 'align))
15449 ((equal property "PRIORITY")
15450 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15451 (string-to-char value) ?\ ))
15452 (org-set-tags nil 'align))
15453 ((equal property "CLOCKSUM")
15454 (if (not (re-search-forward
15455 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15456 (error "Cannot find a clock log")
15457 (goto-char (- (match-end 1) 2))
15458 (cond
15459 ((eq value 'earlier) (org-timestamp-down))
15460 ((eq value 'later) (org-timestamp-up)))
15461 (org-clock-sum-current-item)))
15462 ((equal property "SCHEDULED")
15463 (if (re-search-forward org-scheduled-time-regexp end t)
15464 (cond
15465 ((eq value 'earlier) (org-timestamp-change -1 'day))
15466 ((eq value 'later) (org-timestamp-change 1 'day))
15467 (t (call-interactively 'org-schedule)))
15468 (call-interactively 'org-schedule)))
15469 ((equal property "DEADLINE")
15470 (if (re-search-forward org-deadline-time-regexp end t)
15471 (cond
15472 ((eq value 'earlier) (org-timestamp-change -1 'day))
15473 ((eq value 'later) (org-timestamp-change 1 'day))
15474 (t (call-interactively 'org-deadline)))
15475 (call-interactively 'org-deadline)))
15476 ((member property org-special-properties)
15477 (error "The %s property can not yet be set with `org-entry-put'"
15478 property))
15479 (t ; a non-special property
15480 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15481 (setq range (org-get-property-block beg end 'force))
15482 (goto-char (car range))
15483 (if (re-search-forward
15484 (org-re-property-keyword property) (cdr range) t)
15485 (progn
15486 (delete-region (match-beginning 0) (match-end 0))
15487 (goto-char (match-beginning 0)))
15488 (goto-char (cdr range))
15489 (insert "\n")
15490 (backward-char 1)
15491 (org-indent-line))
15492 (insert ":" property ":")
15493 (and value (insert " " value))
15494 (org-indent-line)))))
15495 (run-hook-with-args 'org-property-changed-functions property value)))
15497 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15498 "Get all property keys in the current buffer.
15499 With INCLUDE-SPECIALS, also list the special properties that reflect things
15500 like tags and TODO state.
15501 With INCLUDE-DEFAULTS, also include properties that has special meaning
15502 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15503 and others.
15504 With INCLUDE-COLUMNS, also include property names given in COLUMN
15505 formats in the current buffer."
15506 (let (rtn range cfmt s p)
15507 (save-excursion
15508 (save-restriction
15509 (widen)
15510 (goto-char (point-min))
15511 (while (re-search-forward org-property-start-re nil t)
15512 (setq range (org-get-property-block))
15513 (goto-char (car range))
15514 (while (re-search-forward org-property-re
15515 (cdr range) t)
15516 (add-to-list 'rtn (org-match-string-no-properties 2)))
15517 (outline-next-heading))))
15519 (when include-specials
15520 (setq rtn (append org-special-properties rtn)))
15522 (when include-defaults
15523 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15524 (add-to-list 'rtn org-effort-property))
15526 (when include-columns
15527 (save-excursion
15528 (save-restriction
15529 (widen)
15530 (goto-char (point-min))
15531 (while (re-search-forward
15532 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15533 nil t)
15534 (setq cfmt (match-string 2) s 0)
15535 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15536 cfmt s)
15537 (setq s (match-end 0)
15538 p (match-string 1 cfmt))
15539 (unless (or (equal p "ITEM")
15540 (member p org-special-properties))
15541 (add-to-list 'rtn (match-string 1 cfmt))))))))
15543 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15545 (defun org-property-values (key)
15546 "Return a list of all values of property KEY in the current buffer."
15547 (save-excursion
15548 (save-restriction
15549 (widen)
15550 (goto-char (point-min))
15551 (let ((re (org-re-property key))
15552 values)
15553 (while (re-search-forward re nil t)
15554 (add-to-list 'values (org-trim (match-string 1))))
15555 (delete "" values)))))
15557 (defun org-insert-property-drawer ()
15558 "Insert a property drawer into the current entry."
15559 (org-back-to-heading t)
15560 (looking-at org-outline-regexp)
15561 (let ((indent (if org-adapt-indentation
15562 (- (match-end 0) (match-beginning 0))
15564 (beg (point))
15565 (re (concat "^[ \t]*" org-keyword-time-regexp))
15566 end hiddenp)
15567 (outline-next-heading)
15568 (setq end (point))
15569 (goto-char beg)
15570 (while (re-search-forward re end t))
15571 (setq hiddenp (outline-invisible-p))
15572 (end-of-line 1)
15573 (and (equal (char-after) ?\n) (forward-char 1))
15574 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15575 (if (member (match-string 1) '("CLOCK:" ":END:"))
15576 ;; just skip this line
15577 (beginning-of-line 2)
15578 ;; Drawer start, find the end
15579 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15580 (beginning-of-line 1)))
15581 (org-skip-over-state-notes)
15582 (skip-chars-backward " \t\n\r")
15583 (if (eq (char-before) ?*) (forward-char 1))
15584 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15585 (beginning-of-line 0)
15586 (org-indent-to-column indent)
15587 (beginning-of-line 2)
15588 (org-indent-to-column indent)
15589 (beginning-of-line 0)
15590 (if hiddenp
15591 (save-excursion
15592 (org-back-to-heading t)
15593 (hide-entry))
15594 (org-flag-drawer t))))
15596 (defun org-insert-drawer (&optional arg drawer)
15597 "Insert a drawer at point.
15599 Optional argument DRAWER, when non-nil, is a string representing
15600 drawer's name. Otherwise, the user is prompted for a name.
15602 If a region is active, insert the drawer around that region
15603 instead.
15605 Point is left between drawer's boundaries."
15606 (interactive "P")
15607 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15608 "LOGBOOK"))
15609 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15610 ;; internally by Org. They are meant to be inserted
15611 ;; automatically.
15612 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15613 ;; Remove system drawers from list. Note: For some reason,
15614 ;; `org-completing-read' ignores the predicate while
15615 ;; `completing-read' handles it fine.
15616 (drawer (if arg "PROPERTIES"
15617 (or drawer
15618 (completing-read
15619 "Drawer: " org-drawers
15620 (lambda (d) (not (member d system-drawers))))))))
15621 (cond
15622 ;; With C-u, fall back on `org-insert-property-drawer'
15623 (arg (org-insert-property-drawer))
15624 ;; With an active region, insert a drawer at point.
15625 ((not (org-region-active-p))
15626 (progn
15627 (unless (bolp) (insert "\n"))
15628 (insert (format ":%s:\n\n:END:\n" drawer))
15629 (forward-line -2)))
15630 ;; Otherwise, insert the drawer at point
15632 (let ((rbeg (region-beginning))
15633 (rend (copy-marker (region-end))))
15634 (unwind-protect
15635 (progn
15636 (goto-char rbeg)
15637 (beginning-of-line)
15638 (when (save-excursion
15639 (re-search-forward org-outline-regexp-bol rend t))
15640 (user-error "Drawers cannot contain headlines"))
15641 ;; Position point at the beginning of the first
15642 ;; non-blank line in region. Insert drawer's opening
15643 ;; there, then indent it.
15644 (org-skip-whitespace)
15645 (beginning-of-line)
15646 (insert ":" drawer ":\n")
15647 (forward-line -1)
15648 (indent-for-tab-command)
15649 ;; Move point to the beginning of the first blank line
15650 ;; after the last non-blank line in region. Insert
15651 ;; drawer's closing, then indent it.
15652 (goto-char rend)
15653 (skip-chars-backward " \r\t\n")
15654 (insert "\n:END:")
15655 (deactivate-mark t)
15656 (indent-for-tab-command)
15657 (unless (eolp) (insert "\n")))
15658 ;; Clear marker, whatever the outcome of insertion is.
15659 (set-marker rend nil)))))))
15661 (defvar org-property-set-functions-alist nil
15662 "Property set function alist.
15663 Each entry should have the following format:
15665 (PROPERTY . READ-FUNCTION)
15667 The read function will be called with the same argument as
15668 `org-completing-read'.")
15670 (defun org-set-property-function (property)
15671 "Get the function that should be used to set PROPERTY.
15672 This is computed according to `org-property-set-functions-alist'."
15673 (or (cdr (assoc property org-property-set-functions-alist))
15674 'org-completing-read))
15676 (defun org-read-property-value (property)
15677 "Read PROPERTY value from user."
15678 (let* ((completion-ignore-case t)
15679 (allowed (org-property-get-allowed-values nil property 'table))
15680 (cur (org-entry-get nil property))
15681 (prompt (concat property " value"
15682 (if (and cur (string-match "\\S-" cur))
15683 (concat " [" cur "]") "") ": "))
15684 (set-function (org-set-property-function property))
15685 (val (if allowed
15686 (funcall set-function prompt allowed nil
15687 (not (get-text-property 0 'org-unrestricted
15688 (caar allowed))))
15689 (let (org-completion-use-ido org-completion-use-iswitchb)
15690 (funcall set-function prompt
15691 (mapcar 'list (org-property-values property))
15692 nil nil "" nil cur)))))
15693 (if (equal val "")
15695 val)))
15697 (defvar org-last-set-property nil)
15698 (defvar org-last-set-property-value nil)
15699 (defun org-read-property-name ()
15700 "Read a property name."
15701 (let* ((completion-ignore-case t)
15702 (keys (org-buffer-property-keys nil t t))
15703 (default-prop (or (save-excursion
15704 (save-match-data
15705 (beginning-of-line)
15706 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15707 (null (string= (match-string 1) "END"))
15708 (match-string 1))))
15709 org-last-set-property))
15710 (property (org-icompleting-read
15711 (concat "Property"
15712 (if default-prop (concat " [" default-prop "]") "")
15713 ": ")
15714 (mapcar 'list keys)
15715 nil nil nil nil
15716 default-prop)))
15717 (if (member property keys)
15718 property
15719 (or (cdr (assoc (downcase property)
15720 (mapcar (lambda (x) (cons (downcase x) x))
15721 keys)))
15722 property))))
15724 (defun org-set-property-and-value (use-last)
15725 "Allow to set [PROPERTY]: [value] direction from prompt.
15726 When use-default, don't even ask, just use the last
15727 \"[PROPERTY]: [value]\" string from the history."
15728 (interactive "P")
15729 (let* ((completion-ignore-case t)
15730 (pv (or (and use-last org-last-set-property-value)
15731 (org-completing-read
15732 "Enter a \"[Property]: [value]\" pair: "
15733 nil nil nil nil nil
15734 org-last-set-property-value)))
15735 prop val)
15736 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15737 (setq prop (match-string 1 pv)
15738 val (match-string 2 pv))
15739 (org-set-property prop val))))
15741 (defun org-set-property (property value)
15742 "In the current entry, set PROPERTY to VALUE.
15743 When called interactively, this will prompt for a property name, offering
15744 completion on existing and default properties. And then it will prompt
15745 for a value, offering completion either on allowed values (via an inherited
15746 xxx_ALL property) or on existing values in other instances of this property
15747 in the current file."
15748 (interactive (list nil nil))
15749 (let* ((property (or property (org-read-property-name)))
15750 (value (or value (org-read-property-value property)))
15751 (fn (cdr (assoc property org-properties-postprocess-alist))))
15752 (setq org-last-set-property property)
15753 (setq org-last-set-property-value (concat property ": " value))
15754 ;; Possibly postprocess the inserted value:
15755 (when fn (setq value (funcall fn value)))
15756 (unless (equal (org-entry-get nil property) value)
15757 (org-entry-put nil property value))))
15759 (defun org-delete-property (property &optional delete-empty-drawer)
15760 "In the current entry, delete PROPERTY.
15761 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15762 an empty drawer to delete."
15763 (interactive
15764 (let* ((completion-ignore-case t)
15765 (prop (org-icompleting-read "Property: "
15766 (org-entry-properties nil 'standard))))
15767 (list prop)))
15768 (message "Property %s %s" property
15769 (if (org-entry-delete nil property delete-empty-drawer)
15770 "deleted"
15771 "was not present in the entry")))
15773 (defun org-delete-property-globally (property)
15774 "Remove PROPERTY globally, from all entries."
15775 (interactive
15776 (let* ((completion-ignore-case t)
15777 (prop (org-icompleting-read
15778 "Globally remove property: "
15779 (mapcar 'list (org-buffer-property-keys)))))
15780 (list prop)))
15781 (save-excursion
15782 (save-restriction
15783 (widen)
15784 (goto-char (point-min))
15785 (let ((cnt 0))
15786 (while (re-search-forward
15787 (org-re-property property)
15788 nil t)
15789 (setq cnt (1+ cnt))
15790 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15791 (message "Property \"%s\" removed from %d entries" property cnt)))))
15793 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15795 (defun org-compute-property-at-point ()
15796 "Compute the property at point.
15797 This looks for an enclosing column format, extracts the operator and
15798 then applies it to the property in the column format's scope."
15799 (interactive)
15800 (unless (org-at-property-p)
15801 (user-error "Not at a property"))
15802 (let ((prop (org-match-string-no-properties 2)))
15803 (org-columns-get-format-and-top-level)
15804 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15805 (user-error "No operator defined for property %s" prop))
15806 (org-columns-compute prop)))
15808 (defvar org-property-allowed-value-functions nil
15809 "Hook for functions supplying allowed values for a specific property.
15810 The functions must take a single argument, the name of the property, and
15811 return a flat list of allowed values. If \":ETC\" is one of
15812 the values, this means that these values are intended as defaults for
15813 completion, but that other values should be allowed too.
15814 The functions must return nil if they are not responsible for this
15815 property.")
15817 (defun org-property-get-allowed-values (pom property &optional table)
15818 "Get allowed values for the property PROPERTY.
15819 When TABLE is non-nil, return an alist that can directly be used for
15820 completion."
15821 (let (vals)
15822 (cond
15823 ((equal property "TODO")
15824 (setq vals (org-with-point-at pom
15825 (append org-todo-keywords-1 '("")))))
15826 ((equal property "PRIORITY")
15827 (let ((n org-lowest-priority))
15828 (while (>= n org-highest-priority)
15829 (push (char-to-string n) vals)
15830 (setq n (1- n)))))
15831 ((member property org-special-properties))
15832 ((setq vals (run-hook-with-args-until-success
15833 'org-property-allowed-value-functions property)))
15835 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15836 (when (and vals (string-match "\\S-" vals))
15837 (setq vals (car (read-from-string (concat "(" vals ")"))))
15838 (setq vals (mapcar (lambda (x)
15839 (cond ((stringp x) x)
15840 ((numberp x) (number-to-string x))
15841 ((symbolp x) (symbol-name x))
15842 (t "???")))
15843 vals)))))
15844 (when (member ":ETC" vals)
15845 (setq vals (remove ":ETC" vals))
15846 (org-add-props (car vals) '(org-unrestricted t)))
15847 (if table (mapcar 'list vals) vals)))
15849 (defun org-property-previous-allowed-value (&optional previous)
15850 "Switch to the next allowed value for this property."
15851 (interactive)
15852 (org-property-next-allowed-value t))
15854 (defun org-property-next-allowed-value (&optional previous)
15855 "Switch to the next allowed value for this property."
15856 (interactive)
15857 (unless (org-at-property-p)
15858 (user-error "Not at a property"))
15859 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15860 (key (match-string 2))
15861 (value (match-string 3))
15862 (allowed (or (org-property-get-allowed-values (point) key)
15863 (and (member value '("[ ]" "[-]" "[X]"))
15864 '("[ ]" "[X]"))))
15865 (heading (save-match-data (nth 4 (org-heading-components))))
15866 nval)
15867 (unless allowed
15868 (user-error "Allowed values for this property have not been defined"))
15869 (if previous (setq allowed (reverse allowed)))
15870 (if (member value allowed)
15871 (setq nval (car (cdr (member value allowed)))))
15872 (setq nval (or nval (car allowed)))
15873 (if (equal nval value)
15874 (user-error "Only one allowed value for this property"))
15875 (org-at-property-p)
15876 (replace-match (concat " :" key ": " nval) t t)
15877 (org-indent-line)
15878 (beginning-of-line 1)
15879 (skip-chars-forward " \t")
15880 (when (equal prop org-effort-property)
15881 (save-excursion
15882 (org-back-to-heading t)
15883 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15884 (when (string= org-clock-current-task heading)
15885 (setq org-clock-effort nval)
15886 (org-clock-update-mode-line)))
15887 (run-hook-with-args 'org-property-changed-functions key nval)))
15889 (defun org-find-olp (path &optional this-buffer)
15890 "Return a marker pointing to the entry at outline path OLP.
15891 If anything goes wrong, throw an error.
15892 You can wrap this call to catch the error like this:
15894 (condition-case msg
15895 (org-mobile-locate-entry (match-string 4))
15896 (error (nth 1 msg)))
15898 The return value will then be either a string with the error message,
15899 or a marker if everything is OK.
15901 If THIS-BUFFER is set, the outline path does not contain a file,
15902 only headings."
15903 (let* ((file (if this-buffer buffer-file-name (pop path)))
15904 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15905 (level 1)
15906 (lmin 1)
15907 (lmax 1)
15908 limit re end found pos heading cnt flevel)
15909 (unless buffer (error "File not found :%s" file))
15910 (with-current-buffer buffer
15911 (save-excursion
15912 (save-restriction
15913 (widen)
15914 (setq limit (point-max))
15915 (goto-char (point-min))
15916 (while (setq heading (pop path))
15917 (setq re (format org-complex-heading-regexp-format
15918 (regexp-quote heading)))
15919 (setq cnt 0 pos (point))
15920 (while (re-search-forward re end t)
15921 (setq level (- (match-end 1) (match-beginning 1)))
15922 (if (and (>= level lmin) (<= level lmax))
15923 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15924 (when (= cnt 0) (error "Heading not found on level %d: %s"
15925 lmax heading))
15926 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15927 lmax heading))
15928 (goto-char found)
15929 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15930 (setq end (save-excursion (org-end-of-subtree t t))))
15931 (when (org-at-heading-p)
15932 (point-marker)))))))
15934 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15935 "Find node HEADING in BUFFER.
15936 Return a marker to the heading if it was found, or nil if not.
15937 If POS-ONLY is set, return just the position instead of a marker.
15939 The heading text must match exact, but it may have a TODO keyword,
15940 a priority cookie and tags in the standard locations."
15941 (with-current-buffer (or buffer (current-buffer))
15942 (save-excursion
15943 (save-restriction
15944 (widen)
15945 (goto-char (point-min))
15946 (let (case-fold-search)
15947 (if (re-search-forward
15948 (format org-complex-heading-regexp-format
15949 (regexp-quote heading)) nil t)
15950 (if pos-only
15951 (match-beginning 0)
15952 (move-marker (make-marker) (match-beginning 0)))))))))
15954 (defun org-find-exact-heading-in-directory (heading &optional dir)
15955 "Find Org node headline HEADING in all .org files in directory DIR.
15956 When the target headline is found, return a marker to this location."
15957 (let ((files (directory-files (or dir default-directory)
15958 nil "\\`[^.#].*\\.org\\'"))
15959 file visiting m buffer)
15960 (catch 'found
15961 (while (setq file (pop files))
15962 (message "trying %s" file)
15963 (setq visiting (org-find-base-buffer-visiting file))
15964 (setq buffer (or visiting (find-file-noselect file)))
15965 (setq m (org-find-exact-headline-in-buffer
15966 heading buffer))
15967 (when (and (not m) (not visiting)) (kill-buffer buffer))
15968 (and m (throw 'found m))))))
15970 (defun org-find-entry-with-id (ident)
15971 "Locate the entry that contains the ID property with exact value IDENT.
15972 IDENT can be a string, a symbol or a number, this function will search for
15973 the string representation of it.
15974 Return the position where this entry starts, or nil if there is no such entry."
15975 (interactive "sID: ")
15976 (let ((id (cond
15977 ((stringp ident) ident)
15978 ((symbol-name ident) (symbol-name ident))
15979 ((numberp ident) (number-to-string ident))
15980 (t (error "IDENT %s must be a string, symbol or number" ident))))
15981 (case-fold-search nil))
15982 (save-excursion
15983 (save-restriction
15984 (widen)
15985 (goto-char (point-min))
15986 (when (re-search-forward
15987 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15988 nil t)
15989 (org-back-to-heading t)
15990 (point))))))
15992 ;;;; Timestamps
15994 (defvar org-last-changed-timestamp nil)
15995 (defvar org-last-inserted-timestamp nil
15996 "The last time stamp inserted with `org-insert-time-stamp'.")
15997 (defvar org-time-was-given) ; dynamically scoped parameter
15998 (defvar org-end-time-was-given) ; dynamically scoped parameter
15999 (defvar org-ts-what) ; dynamically scoped parameter
16001 (defun org-time-stamp (arg &optional inactive)
16002 "Prompt for a date/time and insert a time stamp.
16003 If the user specifies a time like HH:MM or if this command is
16004 called with at least one prefix argument, the time stamp contains
16005 the date and the time. Otherwise, only the date is be included.
16007 All parts of a date not specified by the user is filled in from
16008 the current date/time. So if you just press return without
16009 typing anything, the time stamp will represent the current
16010 date/time.
16012 If there is already a timestamp at the cursor, it will be
16013 modified.
16015 With two universal prefix arguments, insert an active timestamp
16016 with the current time without prompting the user."
16017 (interactive "P")
16018 (let* ((ts nil)
16019 (default-time
16020 ;; Default time is either today, or, when entering a range,
16021 ;; the range start.
16022 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16023 (save-excursion
16024 (re-search-backward
16025 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16026 (- (point) 20) t)))
16027 (apply 'encode-time (org-parse-time-string (match-string 1)))
16028 (current-time)))
16029 (default-input (and ts (org-get-compact-tod ts)))
16030 (repeater (save-excursion
16031 (save-match-data
16032 (beginning-of-line)
16033 (when (re-search-forward
16034 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16035 (save-excursion (progn (end-of-line) (point))) t)
16036 (match-string 0)))))
16037 org-time-was-given org-end-time-was-given time)
16038 (cond
16039 ((and (org-at-timestamp-p t)
16040 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16041 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16042 (insert "--")
16043 (setq time (let ((this-command this-command))
16044 (org-read-date arg 'totime nil nil
16045 default-time default-input inactive)))
16046 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16047 ((org-at-timestamp-p t)
16048 (setq time (let ((this-command this-command))
16049 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16050 (when (org-at-timestamp-p t) ; just to get the match data
16051 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16052 (replace-match "")
16053 (setq org-last-changed-timestamp
16054 (org-insert-time-stamp
16055 time (or org-time-was-given arg)
16056 inactive nil nil (list org-end-time-was-given)))
16057 (when repeater (goto-char (1- (point))) (insert " " repeater)
16058 (setq org-last-changed-timestamp
16059 (concat (substring org-last-inserted-timestamp 0 -1)
16060 " " repeater ">"))))
16061 (message "Timestamp updated"))
16062 ((equal arg '(16))
16063 (org-insert-time-stamp (current-time) t))
16065 (setq time (let ((this-command this-command))
16066 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16067 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16068 nil nil (list org-end-time-was-given))))))
16070 ;; FIXME: can we use this for something else, like computing time differences?
16071 (defun org-get-compact-tod (s)
16072 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16073 (let* ((t1 (match-string 1 s))
16074 (h1 (string-to-number (match-string 2 s)))
16075 (m1 (string-to-number (match-string 3 s)))
16076 (t2 (and (match-end 4) (match-string 5 s)))
16077 (h2 (and t2 (string-to-number (match-string 6 s))))
16078 (m2 (and t2 (string-to-number (match-string 7 s))))
16079 dh dm)
16080 (if (not t2)
16082 (setq dh (- h2 h1) dm (- m2 m1))
16083 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16084 (concat t1 "+" (number-to-string dh)
16085 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16087 (defun org-time-stamp-inactive (&optional arg)
16088 "Insert an inactive time stamp.
16089 An inactive time stamp is enclosed in square brackets instead of angle
16090 brackets. It is inactive in the sense that it does not trigger agenda entries,
16091 does not link to the calendar and cannot be changed with the S-cursor keys.
16092 So these are more for recording a certain time/date."
16093 (interactive "P")
16094 (org-time-stamp arg 'inactive))
16096 (defvar org-date-ovl (make-overlay 1 1))
16097 (overlay-put org-date-ovl 'face 'org-date-selected)
16098 (org-detach-overlay org-date-ovl)
16100 (defvar org-ans1) ; dynamically scoped parameter
16101 (defvar org-ans2) ; dynamically scoped parameter
16103 (defvar org-plain-time-of-day-regexp) ; defined below
16105 (defvar org-overriding-default-time nil) ; dynamically scoped
16106 (defvar org-read-date-overlay nil)
16107 (defvar org-dcst nil) ; dynamically scoped
16108 (defvar org-read-date-history nil)
16109 (defvar org-read-date-final-answer nil)
16110 (defvar org-read-date-analyze-futurep nil)
16111 (defvar org-read-date-analyze-forced-year nil)
16112 (defvar org-read-date-inactive)
16114 (defvar org-read-date-minibuffer-local-map
16115 (let ((map (make-sparse-keymap)))
16116 (set-keymap-parent map minibuffer-local-map)
16117 (org-defkey map (kbd ".")
16118 (lambda () (interactive)
16119 ;; Are we at the beginning of the prompt?
16120 (if (looking-back "^[^:]+: ")
16121 (org-eval-in-calendar '(calendar-goto-today))
16122 (insert "."))))
16123 (org-defkey map (kbd "C-.")
16124 (lambda () (interactive)
16125 (org-eval-in-calendar '(calendar-goto-today))))
16126 (org-defkey map [(meta shift left)]
16127 (lambda () (interactive)
16128 (org-eval-in-calendar '(calendar-backward-month 1))))
16129 (org-defkey map [(meta shift right)]
16130 (lambda () (interactive)
16131 (org-eval-in-calendar '(calendar-forward-month 1))))
16132 (org-defkey map [(meta shift up)]
16133 (lambda () (interactive)
16134 (org-eval-in-calendar '(calendar-backward-year 1))))
16135 (org-defkey map [(meta shift down)]
16136 (lambda () (interactive)
16137 (org-eval-in-calendar '(calendar-forward-year 1))))
16138 (org-defkey map [?\e (shift left)]
16139 (lambda () (interactive)
16140 (org-eval-in-calendar '(calendar-backward-month 1))))
16141 (org-defkey map [?\e (shift right)]
16142 (lambda () (interactive)
16143 (org-eval-in-calendar '(calendar-forward-month 1))))
16144 (org-defkey map [?\e (shift up)]
16145 (lambda () (interactive)
16146 (org-eval-in-calendar '(calendar-backward-year 1))))
16147 (org-defkey map [?\e (shift down)]
16148 (lambda () (interactive)
16149 (org-eval-in-calendar '(calendar-forward-year 1))))
16150 (org-defkey map [(shift up)]
16151 (lambda () (interactive)
16152 (org-eval-in-calendar '(calendar-backward-week 1))))
16153 (org-defkey map [(shift down)]
16154 (lambda () (interactive)
16155 (org-eval-in-calendar '(calendar-forward-week 1))))
16156 (org-defkey map [(shift left)]
16157 (lambda () (interactive)
16158 (org-eval-in-calendar '(calendar-backward-day 1))))
16159 (org-defkey map [(shift right)]
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(calendar-forward-day 1))))
16162 (org-defkey map "!"
16163 (lambda () (interactive)
16164 (org-eval-in-calendar '(diary-view-entries))
16165 (message "")))
16166 (org-defkey map ">"
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(scroll-calendar-left 1))))
16169 (org-defkey map "<"
16170 (lambda () (interactive)
16171 (org-eval-in-calendar '(scroll-calendar-right 1))))
16172 (org-defkey map "\C-v"
16173 (lambda () (interactive)
16174 (org-eval-in-calendar
16175 '(calendar-scroll-left-three-months 1))))
16176 (org-defkey map "\M-v"
16177 (lambda () (interactive)
16178 (org-eval-in-calendar
16179 '(calendar-scroll-right-three-months 1))))
16180 map)
16181 "Keymap for minibuffer commands when using `org-read-date'.")
16183 (defun org-read-date (&optional org-with-time to-time from-string prompt
16184 default-time default-input inactive)
16185 "Read a date, possibly a time, and make things smooth for the user.
16186 The prompt will suggest to enter an ISO date, but you can also enter anything
16187 which will at least partially be understood by `parse-time-string'.
16188 Unrecognized parts of the date will default to the current day, month, year,
16189 hour and minute. If this command is called to replace a timestamp at point,
16190 or to enter the second timestamp of a range, the default time is taken
16191 from the existing stamp. Furthermore, the command prefers the future,
16192 so if you are giving a date where the year is not given, and the day-month
16193 combination is already past in the current year, it will assume you
16194 mean next year. For details, see the manual. A few examples:
16196 3-2-5 --> 2003-02-05
16197 feb 15 --> currentyear-02-15
16198 2/15 --> currentyear-02-15
16199 sep 12 9 --> 2009-09-12
16200 12:45 --> today 12:45
16201 22 sept 0:34 --> currentyear-09-22 0:34
16202 12 --> currentyear-currentmonth-12
16203 Fri --> nearest Friday after today
16204 -Tue --> last Tuesday
16205 etc.
16207 Furthermore you can specify a relative date by giving, as the *first* thing
16208 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16209 change in days weeks, months, years.
16210 With a single plus or minus, the date is relative to today. With a double
16211 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16212 +4d --> four days from today
16213 +4 --> same as above
16214 +2w --> two weeks from today
16215 ++5 --> five days from default date
16217 The function understands only English month and weekday abbreviations.
16219 While prompting, a calendar is popped up - you can also select the
16220 date with the mouse (button 1). The calendar shows a period of three
16221 months. To scroll it to other months, use the keys `>' and `<'.
16222 If you don't like the calendar, turn it off with
16223 \(setq org-read-date-popup-calendar nil)
16225 With optional argument TO-TIME, the date will immediately be converted
16226 to an internal time.
16227 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16228 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16229 still enter a time, and this function will inform the calling routine
16230 about this change. The calling routine may then choose to change the
16231 format used to insert the time stamp into the buffer to include the time.
16232 With optional argument FROM-STRING, read from this string instead from
16233 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16234 the time/date that is used for everything that is not specified by the
16235 user."
16236 (require 'parse-time)
16237 (let* ((org-time-stamp-rounding-minutes
16238 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16239 (org-dcst org-display-custom-times)
16240 (ct (org-current-time))
16241 (org-def (or org-overriding-default-time default-time ct))
16242 (org-defdecode (decode-time org-def))
16243 (dummy (progn
16244 (when (< (nth 2 org-defdecode) org-extend-today-until)
16245 (setcar (nthcdr 2 org-defdecode) -1)
16246 (setcar (nthcdr 1 org-defdecode) 59)
16247 (setq org-def (apply 'encode-time org-defdecode)
16248 org-defdecode (decode-time org-def)))))
16249 (mouse-autoselect-window nil) ; Don't let the mouse jump
16250 (calendar-frame-setup nil)
16251 (calendar-setup nil)
16252 (calendar-move-hook nil)
16253 (calendar-view-diary-initially-flag nil)
16254 (calendar-view-holidays-initially-flag nil)
16255 (timestr (format-time-string
16256 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16257 (prompt (concat (if prompt (concat prompt " ") "")
16258 (format "Date+time [%s]: " timestr)))
16259 ans (org-ans0 "") org-ans1 org-ans2 final)
16261 (cond
16262 (from-string (setq ans from-string))
16263 (org-read-date-popup-calendar
16264 (save-excursion
16265 (save-window-excursion
16266 (calendar)
16267 (org-eval-in-calendar '(setq cursor-type nil) t)
16268 (unwind-protect
16269 (progn
16270 (calendar-forward-day (- (time-to-days org-def)
16271 (calendar-absolute-from-gregorian
16272 (calendar-current-date))))
16273 (org-eval-in-calendar nil t)
16274 (let* ((old-map (current-local-map))
16275 (map (copy-keymap calendar-mode-map))
16276 (minibuffer-local-map
16277 (copy-keymap org-read-date-minibuffer-local-map)))
16278 (org-defkey map (kbd "RET") 'org-calendar-select)
16279 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16280 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16281 (unwind-protect
16282 (progn
16283 (use-local-map map)
16284 (setq org-read-date-inactive inactive)
16285 (add-hook 'post-command-hook 'org-read-date-display)
16286 (setq org-ans0 (read-string prompt default-input
16287 'org-read-date-history nil))
16288 ;; org-ans0: from prompt
16289 ;; org-ans1: from mouse click
16290 ;; org-ans2: from calendar motion
16291 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16292 (remove-hook 'post-command-hook 'org-read-date-display)
16293 (use-local-map old-map)
16294 (when org-read-date-overlay
16295 (delete-overlay org-read-date-overlay)
16296 (setq org-read-date-overlay nil)))))
16297 (bury-buffer "*Calendar*")))))
16299 (t ; Naked prompt only
16300 (unwind-protect
16301 (setq ans (read-string prompt default-input
16302 'org-read-date-history timestr))
16303 (when org-read-date-overlay
16304 (delete-overlay org-read-date-overlay)
16305 (setq org-read-date-overlay nil)))))
16307 (setq final (org-read-date-analyze ans org-def org-defdecode))
16309 (when org-read-date-analyze-forced-year
16310 (message "Year was forced into %s"
16311 (if org-read-date-force-compatible-dates
16312 "compatible range (1970-2037)"
16313 "range representable on this machine"))
16314 (ding))
16316 ;; One round trip to get rid of 34th of August and stuff like that....
16317 (setq final (decode-time (apply 'encode-time final)))
16319 (setq org-read-date-final-answer ans)
16321 (if to-time
16322 (apply 'encode-time final)
16323 (if (and (boundp 'org-time-was-given) org-time-was-given)
16324 (format "%04d-%02d-%02d %02d:%02d"
16325 (nth 5 final) (nth 4 final) (nth 3 final)
16326 (nth 2 final) (nth 1 final))
16327 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16329 (defvar org-def)
16330 (defvar org-defdecode)
16331 (defvar org-with-time)
16332 (defun org-read-date-display ()
16333 "Display the current date prompt interpretation in the minibuffer."
16334 (when org-read-date-display-live
16335 (when org-read-date-overlay
16336 (delete-overlay org-read-date-overlay))
16337 (when (minibufferp (current-buffer))
16338 (save-excursion
16339 (end-of-line 1)
16340 (while (not (equal (buffer-substring
16341 (max (point-min) (- (point) 4)) (point))
16342 " "))
16343 (insert " ")))
16344 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16345 " " (or org-ans1 org-ans2)))
16346 (org-end-time-was-given nil)
16347 (f (org-read-date-analyze ans org-def org-defdecode))
16348 (fmts (if org-dcst
16349 org-time-stamp-custom-formats
16350 org-time-stamp-formats))
16351 (fmt (if (or org-with-time
16352 (and (boundp 'org-time-was-given) org-time-was-given))
16353 (cdr fmts)
16354 (car fmts)))
16355 (txt (format-time-string fmt (apply 'encode-time f)))
16356 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16357 (txt (concat "=> " txt)))
16358 (when (and org-end-time-was-given
16359 (string-match org-plain-time-of-day-regexp txt))
16360 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16361 org-end-time-was-given
16362 (substring txt (match-end 0)))))
16363 (when org-read-date-analyze-futurep
16364 (setq txt (concat txt " (=>F)")))
16365 (setq org-read-date-overlay
16366 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16367 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16369 (defun org-read-date-analyze (ans org-def org-defdecode)
16370 "Analyze the combined answer of the date prompt."
16371 ;; FIXME: cleanup and comment
16372 (let ((nowdecode (decode-time (current-time)))
16373 delta deltan deltaw deltadef year month day
16374 hour minute second wday pm h2 m2 tl wday1
16375 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16376 (setq org-read-date-analyze-futurep nil
16377 org-read-date-analyze-forced-year nil)
16378 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16379 (setq ans "+0"))
16381 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16382 (setq ans (replace-match "" t t ans)
16383 deltan (car delta)
16384 deltaw (nth 1 delta)
16385 deltadef (nth 2 delta)))
16387 ;; Check if there is an iso week date in there. If yes, store the
16388 ;; info and postpone interpreting it until the rest of the parsing
16389 ;; is done.
16390 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16391 (setq iso-year (if (match-end 1)
16392 (org-small-year-to-year
16393 (string-to-number (match-string 1 ans))))
16394 iso-weekday (if (match-end 3)
16395 (string-to-number (match-string 3 ans)))
16396 iso-week (string-to-number (match-string 2 ans)))
16397 (setq ans (replace-match "" t t ans)))
16399 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16400 (when (string-match
16401 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16402 (setq year (if (match-end 2)
16403 (string-to-number (match-string 2 ans))
16404 (progn (setq kill-year t)
16405 (string-to-number (format-time-string "%Y"))))
16406 month (string-to-number (match-string 3 ans))
16407 day (string-to-number (match-string 4 ans)))
16408 (if (< year 100) (setq year (+ 2000 year)))
16409 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16410 t nil ans)))
16412 ;; Help matching dotted european dates
16413 (when (string-match
16414 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16415 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16416 (setq kill-year t)
16417 (string-to-number (format-time-string "%Y")))
16418 day (string-to-number (match-string 1 ans))
16419 month (string-to-number (match-string 2 ans))
16420 ans (replace-match (format "%04d-%02d-%02d" year month day)
16421 t nil ans)))
16423 ;; Help matching american dates, like 5/30 or 5/30/7
16424 (when (string-match
16425 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16426 (setq year (if (match-end 4)
16427 (string-to-number (match-string 4 ans))
16428 (progn (setq kill-year t)
16429 (string-to-number (format-time-string "%Y"))))
16430 month (string-to-number (match-string 1 ans))
16431 day (string-to-number (match-string 2 ans)))
16432 (if (< year 100) (setq year (+ 2000 year)))
16433 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16434 t nil ans)))
16435 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16436 ;; If there is a time with am/pm, and *no* time without it, we convert
16437 ;; so that matching will be successful.
16438 (loop for i from 1 to 2 do ; twice, for end time as well
16439 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16440 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16441 (setq hour (string-to-number (match-string 1 ans))
16442 minute (if (match-end 3)
16443 (string-to-number (match-string 3 ans))
16445 pm (equal ?p
16446 (string-to-char (downcase (match-string 4 ans)))))
16447 (if (and (= hour 12) (not pm))
16448 (setq hour 0)
16449 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16450 (setq ans (replace-match (format "%02d:%02d" hour minute)
16451 t t ans))))
16453 ;; Check if a time range is given as a duration
16454 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16455 (setq hour (string-to-number (match-string 1 ans))
16456 h2 (+ hour (string-to-number (match-string 3 ans)))
16457 minute (string-to-number (match-string 2 ans))
16458 m2 (+ minute (if (match-end 5) (string-to-number
16459 (match-string 5 ans))0)))
16460 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16461 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16462 t t ans)))
16464 ;; Check if there is a time range
16465 (when (boundp 'org-end-time-was-given)
16466 (setq org-time-was-given nil)
16467 (when (and (string-match org-plain-time-of-day-regexp ans)
16468 (match-end 8))
16469 (setq org-end-time-was-given (match-string 8 ans))
16470 (setq ans (concat (substring ans 0 (match-beginning 7))
16471 (substring ans (match-end 7))))))
16473 (setq tl (parse-time-string ans)
16474 day (or (nth 3 tl) (nth 3 org-defdecode))
16475 month (or (nth 4 tl)
16476 (if (and org-read-date-prefer-future
16477 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16478 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16479 (nth 4 org-defdecode)))
16480 year (or (and (not kill-year) (nth 5 tl))
16481 (if (and org-read-date-prefer-future
16482 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16483 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16484 (nth 5 org-defdecode)))
16485 hour (or (nth 2 tl) (nth 2 org-defdecode))
16486 minute (or (nth 1 tl) (nth 1 org-defdecode))
16487 second (or (nth 0 tl) 0)
16488 wday (nth 6 tl))
16490 (when (and (eq org-read-date-prefer-future 'time)
16491 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16492 (equal day (nth 3 nowdecode))
16493 (equal month (nth 4 nowdecode))
16494 (equal year (nth 5 nowdecode))
16495 (nth 2 tl)
16496 (or (< (nth 2 tl) (nth 2 nowdecode))
16497 (and (= (nth 2 tl) (nth 2 nowdecode))
16498 (nth 1 tl)
16499 (< (nth 1 tl) (nth 1 nowdecode)))))
16500 (setq day (1+ day)
16501 futurep t))
16503 ;; Special date definitions below
16504 (cond
16505 (iso-week
16506 ;; There was an iso week
16507 (require 'cal-iso)
16508 (setq futurep nil)
16509 (setq year (or iso-year year)
16510 day (or iso-weekday wday 1)
16511 wday nil ; to make sure that the trigger below does not match
16512 iso-date (calendar-gregorian-from-absolute
16513 (calendar-absolute-from-iso
16514 (list iso-week day year))))
16515 ; FIXME: Should we also push ISO weeks into the future?
16516 ; (when (and org-read-date-prefer-future
16517 ; (not iso-year)
16518 ; (< (calendar-absolute-from-gregorian iso-date)
16519 ; (time-to-days (current-time))))
16520 ; (setq year (1+ year)
16521 ; iso-date (calendar-gregorian-from-absolute
16522 ; (calendar-absolute-from-iso
16523 ; (list iso-week day year)))))
16524 (setq month (car iso-date)
16525 year (nth 2 iso-date)
16526 day (nth 1 iso-date)))
16527 (deltan
16528 (setq futurep nil)
16529 (unless deltadef
16530 (let ((now (decode-time (current-time))))
16531 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16532 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16533 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16534 ((equal deltaw "m") (setq month (+ month deltan)))
16535 ((equal deltaw "y") (setq year (+ year deltan)))))
16536 ((and wday (not (nth 3 tl)))
16537 ;; Weekday was given, but no day, so pick that day in the week
16538 ;; on or after the derived date.
16539 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16540 (unless (equal wday wday1)
16541 (setq day (+ day (% (- wday wday1 -7) 7))))))
16542 (if (and (boundp 'org-time-was-given)
16543 (nth 2 tl))
16544 (setq org-time-was-given t))
16545 (if (< year 100) (setq year (+ 2000 year)))
16546 ;; Check of the date is representable
16547 (if org-read-date-force-compatible-dates
16548 (progn
16549 (if (< year 1970)
16550 (setq year 1970 org-read-date-analyze-forced-year t))
16551 (if (> year 2037)
16552 (setq year 2037 org-read-date-analyze-forced-year t)))
16553 (condition-case nil
16554 (ignore (encode-time second minute hour day month year))
16555 (error
16556 (setq year (nth 5 org-defdecode))
16557 (setq org-read-date-analyze-forced-year t))))
16558 (setq org-read-date-analyze-futurep futurep)
16559 (list second minute hour day month year)))
16561 (defvar parse-time-weekdays)
16562 (defun org-read-date-get-relative (s today default)
16563 "Check string S for special relative date string.
16564 TODAY and DEFAULT are internal times, for today and for a default.
16565 Return shift list (N what def-flag)
16566 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16567 N is the number of WHATs to shift.
16568 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16569 the DEFAULT date rather than TODAY."
16570 (require 'parse-time)
16571 (when (and
16572 (string-match
16573 (concat
16574 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16575 "\\([0-9]+\\)?"
16576 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16577 "\\([ \t]\\|$\\)") s)
16578 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16579 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16580 (string-to-char (substring (match-string 1 s) -1))
16581 ?+))
16582 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16583 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16584 (what (if (match-end 3) (match-string 3 s) "d"))
16585 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16586 (date (if rel default today))
16587 (wday (nth 6 (decode-time date)))
16588 delta)
16589 (if wday1
16590 (progn
16591 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16592 (if (= delta 0) (setq delta 7))
16593 (if (= dir ?-)
16594 (progn
16595 (setq delta (- delta 7))
16596 (if (= delta 0) (setq delta -7))))
16597 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16598 (list delta "d" rel))
16599 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16601 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16602 "Turn a user-specified date into the internal representation.
16603 The internal representation needed by the calendar is (month day year).
16604 This is a wrapper to handle the brain-dead convention in calendar that
16605 user function argument order change dependent on argument order."
16606 (if (boundp 'calendar-date-style)
16607 (cond
16608 ((eq calendar-date-style 'american)
16609 (list arg1 arg2 arg3))
16610 ((eq calendar-date-style 'european)
16611 (list arg2 arg1 arg3))
16612 ((eq calendar-date-style 'iso)
16613 (list arg2 arg3 arg1)))
16614 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16615 (if (org-bound-and-true-p european-calendar-style)
16616 (list arg2 arg1 arg3)
16617 (list arg1 arg2 arg3)))))
16619 (defun org-eval-in-calendar (form &optional keepdate)
16620 "Eval FORM in the calendar window and return to current window.
16621 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16622 otherwise stick to the current value of `org-ans2'."
16623 (let ((sf (selected-frame))
16624 (sw (selected-window)))
16625 (select-window (get-buffer-window "*Calendar*" t))
16626 (eval form)
16627 (when (and (not keepdate) (calendar-cursor-to-date))
16628 (let* ((date (calendar-cursor-to-date))
16629 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16630 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16631 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16632 (select-window sw)
16633 (org-select-frame-set-input-focus sf)))
16635 (defun org-calendar-select ()
16636 "Return to `org-read-date' with the date currently selected.
16637 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16638 (interactive)
16639 (when (calendar-cursor-to-date)
16640 (let* ((date (calendar-cursor-to-date))
16641 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16642 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16643 (if (active-minibuffer-window) (exit-minibuffer))))
16645 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16646 "Insert a date stamp for the date given by the internal TIME.
16647 WITH-HM means use the stamp format that includes the time of the day.
16648 INACTIVE means use square brackets instead of angular ones, so that the
16649 stamp will not contribute to the agenda.
16650 PRE and POST are optional strings to be inserted before and after the
16651 stamp.
16652 The command returns the inserted time stamp."
16653 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16654 stamp)
16655 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16656 (insert-before-markers (or pre ""))
16657 (when (listp extra)
16658 (setq extra (car extra))
16659 (if (and (stringp extra)
16660 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16661 (setq extra (format "-%02d:%02d"
16662 (string-to-number (match-string 1 extra))
16663 (string-to-number (match-string 2 extra))))
16664 (setq extra nil)))
16665 (when extra
16666 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16667 (insert-before-markers (setq stamp (format-time-string fmt time)))
16668 (insert-before-markers (or post ""))
16669 (setq org-last-inserted-timestamp stamp)))
16671 (defun org-toggle-time-stamp-overlays ()
16672 "Toggle the use of custom time stamp formats."
16673 (interactive)
16674 (setq org-display-custom-times (not org-display-custom-times))
16675 (unless org-display-custom-times
16676 (let ((p (point-min)) (bmp (buffer-modified-p)))
16677 (while (setq p (next-single-property-change p 'display))
16678 (if (and (get-text-property p 'display)
16679 (eq (get-text-property p 'face) 'org-date))
16680 (remove-text-properties
16681 p (setq p (next-single-property-change p 'display))
16682 '(display t))))
16683 (set-buffer-modified-p bmp)))
16684 (if (featurep 'xemacs)
16685 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16686 (org-restart-font-lock)
16687 (setq org-table-may-need-update t)
16688 (if org-display-custom-times
16689 (message "Time stamps are overlaid with custom format")
16690 (message "Time stamp overlays removed")))
16692 (defun org-display-custom-time (beg end)
16693 "Overlay modified time stamp format over timestamp between BEG and END."
16694 (let* ((ts (buffer-substring beg end))
16695 t1 w1 with-hm tf time str w2 (off 0))
16696 (save-match-data
16697 (setq t1 (org-parse-time-string ts t))
16698 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16699 (setq off (- (match-end 0) (match-beginning 0)))))
16700 (setq end (- end off))
16701 (setq w1 (- end beg)
16702 with-hm (and (nth 1 t1) (nth 2 t1))
16703 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16704 time (org-fix-decoded-time t1)
16705 str (org-add-props
16706 (format-time-string
16707 (substring tf 1 -1) (apply 'encode-time time))
16708 nil 'mouse-face 'highlight)
16709 w2 (length str))
16710 (if (not (= w2 w1))
16711 (add-text-properties (1+ beg) (+ 2 beg)
16712 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16713 (if (featurep 'xemacs)
16714 (progn
16715 (put-text-property beg end 'invisible t)
16716 (put-text-property beg end 'end-glyph (make-glyph str)))
16717 (put-text-property beg end 'display str))))
16719 (defun org-translate-time (string)
16720 "Translate all timestamps in STRING to custom format.
16721 But do this only if the variable `org-display-custom-times' is set."
16722 (when org-display-custom-times
16723 (save-match-data
16724 (let* ((start 0)
16725 (re org-ts-regexp-both)
16726 t1 with-hm inactive tf time str beg end)
16727 (while (setq start (string-match re string start))
16728 (setq beg (match-beginning 0)
16729 end (match-end 0)
16730 t1 (save-match-data
16731 (org-parse-time-string (substring string beg end) t))
16732 with-hm (and (nth 1 t1) (nth 2 t1))
16733 inactive (equal (substring string beg (1+ beg)) "[")
16734 tf (funcall (if with-hm 'cdr 'car)
16735 org-time-stamp-custom-formats)
16736 time (org-fix-decoded-time t1)
16737 str (format-time-string
16738 (concat
16739 (if inactive "[" "<") (substring tf 1 -1)
16740 (if inactive "]" ">"))
16741 (apply 'encode-time time))
16742 string (replace-match str t t string)
16743 start (+ start (length str)))))))
16744 string)
16746 (defun org-fix-decoded-time (time)
16747 "Set 0 instead of nil for the first 6 elements of time.
16748 Don't touch the rest."
16749 (let ((n 0))
16750 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16752 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16754 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16755 "Difference between TIMESTAMP-STRING and now in days.
16756 If SECONDS is non-nil, return the difference in seconds."
16757 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16758 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16759 (funcall fdiff (current-time)))))
16761 (defun org-deadline-close (timestamp-string &optional ndays)
16762 "Is the time in TIMESTAMP-STRING close to the current date?"
16763 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16764 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16765 (not (org-entry-is-done-p))))
16767 (defun org-get-wdays (ts &optional delay zero-delay)
16768 "Get the deadline lead time appropriate for timestring TS.
16769 When DELAY is non-nil, get the delay time for scheduled items
16770 instead of the deadline lead time. When ZERO-DELAY is non-nil
16771 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16772 don't try to find the delay cookie in the scheduled timestamp."
16773 (let ((tv (if delay org-scheduled-delay-days
16774 org-deadline-warning-days)))
16775 (cond
16776 ((or (and delay (< tv 0))
16777 (and delay zero-delay (<= tv 0))
16778 (and (not delay) (<= tv 0)))
16779 ;; Enforce this value no matter what
16780 (- tv))
16781 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16782 ;; lead time is specified.
16783 (floor (* (string-to-number (match-string 1 ts))
16784 (cdr (assoc (match-string 2 ts)
16785 '(("d" . 1) ("w" . 7)
16786 ("m" . 30.4) ("y" . 365.25)
16787 ("h" . 0.041667)))))))
16788 ;; go for the default.
16789 (t tv))))
16791 (defun org-calendar-select-mouse (ev)
16792 "Return to `org-read-date' with the date currently selected.
16793 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16794 (interactive "e")
16795 (mouse-set-point ev)
16796 (when (calendar-cursor-to-date)
16797 (let* ((date (calendar-cursor-to-date))
16798 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16799 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16800 (if (active-minibuffer-window) (exit-minibuffer))))
16802 (defun org-check-deadlines (ndays)
16803 "Check if there are any deadlines due or past due.
16804 A deadline is considered due if it happens within `org-deadline-warning-days'
16805 days from today's date. If the deadline appears in an entry marked DONE,
16806 it is not shown. The prefix arg NDAYS can be used to test that many
16807 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16808 (interactive "P")
16809 (let* ((org-warn-days
16810 (cond
16811 ((equal ndays '(4)) 100000)
16812 (ndays (prefix-numeric-value ndays))
16813 (t (abs org-deadline-warning-days))))
16814 (case-fold-search nil)
16815 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16816 (callback
16817 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16819 (message "%d deadlines past-due or due within %d days"
16820 (org-occur regexp nil callback)
16821 org-warn-days)))
16823 (defsubst org-re-timestamp (type)
16824 "Return a regexp for timestamp TYPE.
16825 Allowed values for TYPE are:
16827 all: all timestamps
16828 active: only active timestamps (<...>)
16829 inactive: only inactive timestamps ([...])
16830 scheduled: only scheduled timestamps
16831 deadline: only deadline timestamps
16832 closed: only closed time-stamps
16834 When TYPE is nil, fall back on returning a regexp that matches
16835 both scheduled and deadline timestamps."
16836 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16837 ((eq type 'active) org-ts-regexp)
16838 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16839 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16840 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16841 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16842 ((eq type 'scheduled-or-deadline)
16843 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16845 (defun org-check-before-date (date)
16846 "Check if there are deadlines or scheduled entries before DATE."
16847 (interactive (list (org-read-date)))
16848 (let ((case-fold-search nil)
16849 (regexp (org-re-timestamp org-ts-type))
16850 (callback
16851 (lambda () (time-less-p
16852 (org-time-string-to-time (match-string 1))
16853 (org-time-string-to-time date)))))
16854 (message "%d entries before %s"
16855 (org-occur regexp nil callback) date)))
16857 (defun org-check-after-date (date)
16858 "Check if there are deadlines or scheduled entries after DATE."
16859 (interactive (list (org-read-date)))
16860 (let ((case-fold-search nil)
16861 (regexp (org-re-timestamp org-ts-type))
16862 (callback
16863 (lambda () (not
16864 (time-less-p
16865 (org-time-string-to-time (match-string 1))
16866 (org-time-string-to-time date))))))
16867 (message "%d entries after %s"
16868 (org-occur regexp nil callback) date)))
16870 (defun org-check-dates-range (start-date end-date)
16871 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16872 (interactive (list (org-read-date nil nil nil "Range starts")
16873 (org-read-date nil nil nil "Range end")))
16874 (let ((case-fold-search nil)
16875 (regexp (org-re-timestamp org-ts-type))
16876 (callback
16877 (lambda ()
16878 (let ((match (match-string 1)))
16879 (and
16880 (not (time-less-p
16881 (org-time-string-to-time match)
16882 (org-time-string-to-time start-date)))
16883 (time-less-p
16884 (org-time-string-to-time match)
16885 (org-time-string-to-time end-date)))))))
16886 (message "%d entries between %s and %s"
16887 (org-occur regexp nil callback) start-date end-date)))
16889 (defun org-evaluate-time-range (&optional to-buffer)
16890 "Evaluate a time range by computing the difference between start and end.
16891 Normally the result is just printed in the echo area, but with prefix arg
16892 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16893 If the time range is actually in a table, the result is inserted into the
16894 next column.
16895 For time difference computation, a year is assumed to be exactly 365
16896 days in order to avoid rounding problems."
16897 (interactive "P")
16899 (org-clock-update-time-maybe)
16900 (save-excursion
16901 (unless (org-at-date-range-p t)
16902 (goto-char (point-at-bol))
16903 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16904 (if (not (org-at-date-range-p t))
16905 (user-error "Not at a time-stamp range, and none found in current line")))
16906 (let* ((ts1 (match-string 1))
16907 (ts2 (match-string 2))
16908 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16909 (match-end (match-end 0))
16910 (time1 (org-time-string-to-time ts1))
16911 (time2 (org-time-string-to-time ts2))
16912 (t1 (org-float-time time1))
16913 (t2 (org-float-time time2))
16914 (diff (abs (- t2 t1)))
16915 (negative (< (- t2 t1) 0))
16916 ;; (ys (floor (* 365 24 60 60)))
16917 (ds (* 24 60 60))
16918 (hs (* 60 60))
16919 (fy "%dy %dd %02d:%02d")
16920 (fy1 "%dy %dd")
16921 (fd "%dd %02d:%02d")
16922 (fd1 "%dd")
16923 (fh "%02d:%02d")
16924 y d h m align)
16925 (if havetime
16926 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16928 d (floor (/ diff ds)) diff (mod diff ds)
16929 h (floor (/ diff hs)) diff (mod diff hs)
16930 m (floor (/ diff 60)))
16931 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16933 d (floor (+ (/ diff ds) 0.5))
16934 h 0 m 0))
16935 (if (not to-buffer)
16936 (message "%s" (org-make-tdiff-string y d h m))
16937 (if (org-at-table-p)
16938 (progn
16939 (goto-char match-end)
16940 (setq align t)
16941 (and (looking-at " *|") (goto-char (match-end 0))))
16942 (goto-char match-end))
16943 (if (looking-at
16944 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16945 (replace-match ""))
16946 (if negative (insert " -"))
16947 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16948 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16949 (insert " " (format fh h m))))
16950 (if align (org-table-align))
16951 (message "Time difference inserted")))))
16953 (defun org-make-tdiff-string (y d h m)
16954 (let ((fmt "")
16955 (l nil))
16956 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16957 l (push y l)))
16958 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16959 l (push d l)))
16960 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16961 l (push h l)))
16962 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16963 l (push m l)))
16964 (apply 'format fmt (nreverse l))))
16966 (defun org-time-string-to-time (s &optional buffer pos)
16967 "Convert a timestamp string into internal time."
16968 (condition-case errdata
16969 (apply 'encode-time (org-parse-time-string s))
16970 (error (error "Bad timestamp `%s'%s\nError was: %s"
16971 s (if (not (and buffer pos))
16973 (format " at %d in buffer `%s'" pos buffer))
16974 (cdr errdata)))))
16976 (defun org-time-string-to-seconds (s)
16977 "Convert a timestamp string to a number of seconds."
16978 (org-float-time (org-time-string-to-time s)))
16980 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16981 "Convert a time stamp to an absolute day number.
16982 If there is a specifier for a cyclic time stamp, get the closest
16983 date to DAYNR.
16984 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16985 The variable `date' is bound by the calendar when this is called."
16986 (cond
16987 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16988 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16989 daynr
16990 (+ daynr 1000)))
16991 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16992 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16993 (time-to-days (current-time))) (match-string 0 s)
16994 prefer show-all))
16995 (t (time-to-days
16996 (condition-case errdata
16997 (apply 'encode-time (org-parse-time-string s))
16998 (error (error "Bad timestamp `%s'%s\nError was: %s"
16999 s (if (not (and buffer pos))
17001 (format " at %d in buffer `%s'" pos buffer))
17002 (cdr errdata))))))))
17004 (defun org-days-to-iso-week (days)
17005 "Return the iso week number."
17006 (require 'cal-iso)
17007 (car (calendar-iso-from-absolute days)))
17009 (defun org-small-year-to-year (year)
17010 "Convert 2-digit years into 4-digit years.
17011 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17012 The year 2000 cannot be abbreviated. Any year larger than 99
17013 is returned unchanged."
17014 (if (< year 38)
17015 (setq year (+ 2000 year))
17016 (if (< year 100)
17017 (setq year (+ 1900 year))))
17018 year)
17020 (defun org-time-from-absolute (d)
17021 "Return the time corresponding to date D.
17022 D may be an absolute day number, or a calendar-type list (month day year)."
17023 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17024 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17026 (defun org-calendar-holiday ()
17027 "List of holidays, for Diary display in Org-mode."
17028 (require 'holidays)
17029 (let ((hl (funcall
17030 (if (fboundp 'calendar-check-holidays)
17031 'calendar-check-holidays 'check-calendar-holidays) date)))
17032 (if hl (mapconcat 'identity hl "; "))))
17034 (defun org-diary-sexp-entry (sexp entry date)
17035 "Process a SEXP diary ENTRY for DATE."
17036 (require 'diary-lib)
17037 (let ((result (if calendar-debug-sexp
17038 (let ((stack-trace-on-error t))
17039 (eval (car (read-from-string sexp))))
17040 (condition-case nil
17041 (eval (car (read-from-string sexp)))
17042 (error
17043 (beep)
17044 (message "Bad sexp at line %d in %s: %s"
17045 (org-current-line)
17046 (buffer-file-name) sexp)
17047 (sleep-for 2))))))
17048 (cond ((stringp result) (split-string result "; "))
17049 ((and (consp result)
17050 (not (consp (cdr result)))
17051 (stringp (cdr result))) (cdr result))
17052 ((and (consp result)
17053 (stringp (car result))) result)
17054 (result entry))))
17056 (defun org-diary-to-ical-string (frombuf)
17057 "Get iCalendar entries from diary entries in buffer FROMBUF.
17058 This uses the icalendar.el library."
17059 (let* ((tmpdir (if (featurep 'xemacs)
17060 (temp-directory)
17061 temporary-file-directory))
17062 (tmpfile (make-temp-name
17063 (expand-file-name "orgics" tmpdir)))
17064 buf rtn b e)
17065 (with-current-buffer frombuf
17066 (icalendar-export-region (point-min) (point-max) tmpfile)
17067 (setq buf (find-buffer-visiting tmpfile))
17068 (set-buffer buf)
17069 (goto-char (point-min))
17070 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17071 (setq b (match-beginning 0)))
17072 (goto-char (point-max))
17073 (if (re-search-backward "^END:VEVENT" nil t)
17074 (setq e (match-end 0)))
17075 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17076 (kill-buffer buf)
17077 (delete-file tmpfile)
17078 rtn))
17080 (defun org-closest-date (start current change prefer show-all)
17081 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17082 When PREFER is `past', return a date that is either CURRENT or past.
17083 When PREFER is `future', return a date that is either CURRENT or future.
17084 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17085 ;; Make the proper lists from the dates
17086 (catch 'exit
17087 (let ((a1 '(("h" . hour)
17088 ("d" . day)
17089 ("w" . week)
17090 ("m" . month)
17091 ("y" . year)))
17092 (shour (nth 2 (org-parse-time-string start)))
17093 dn dw sday cday n1 n2 n0
17094 d m y y1 y2 date1 date2 nmonths nm ny m2)
17096 (setq start (org-date-to-gregorian start)
17097 current (org-date-to-gregorian
17098 (if show-all
17099 current
17100 (time-to-days (current-time))))
17101 sday (calendar-absolute-from-gregorian start)
17102 cday (calendar-absolute-from-gregorian current))
17104 (if (<= cday sday) (throw 'exit sday))
17106 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17107 (setq dn (string-to-number (match-string 1 change))
17108 dw (cdr (assoc (match-string 2 change) a1)))
17109 (user-error "Invalid change specifier: %s" change))
17110 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17111 (cond
17112 ((eq dw 'hour)
17113 (let ((missing-hours
17114 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17115 dn)))
17116 (setq n1 (if (zerop missing-hours) cday
17117 (- cday (1+ (floor (/ missing-hours 24)))))
17118 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17119 ((eq dw 'day)
17120 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17121 n2 (+ n1 dn)))
17122 ((eq dw 'year)
17123 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17124 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17125 (setq date1 (list m d y1)
17126 n1 (calendar-absolute-from-gregorian date1)
17127 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17128 n2 (calendar-absolute-from-gregorian date2)))
17129 ((eq dw 'month)
17130 ;; approx number of month between the two dates
17131 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17132 ;; How often does dn fit in there?
17133 (setq d (nth 1 start) m (car start) y (nth 2 start)
17134 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17135 m (+ m nm)
17136 ny (floor (/ m 12))
17137 y (+ y ny)
17138 m (- m (* ny 12)))
17139 (while (> m 12) (setq m (- m 12) y (1+ y)))
17140 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17141 (setq m2 (+ m dn) y2 y)
17142 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17143 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17144 (while (<= n2 cday)
17145 (setq n1 n2 m m2 y y2)
17146 (setq m2 (+ m dn) y2 y)
17147 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17148 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17149 ;; Make sure n1 is the earlier date
17150 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17151 (if show-all
17152 (cond
17153 ((eq prefer 'past) (if (= cday n2) n2 n1))
17154 ((eq prefer 'future) (if (= cday n1) n1 n2))
17155 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17156 (cond
17157 ((eq prefer 'past) (if (= cday n2) n2 n1))
17158 ((eq prefer 'future) (if (= cday n1) n1 n2))
17159 (t (if (= cday n1) n1 n2)))))))
17161 (defun org-date-to-gregorian (date)
17162 "Turn any specification of DATE into a Gregorian date for the calendar."
17163 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17164 ((and (listp date) (= (length date) 3)) date)
17165 ((stringp date)
17166 (setq date (org-parse-time-string date))
17167 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17168 ((listp date)
17169 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17171 (defun org-parse-time-string (s &optional nodefault)
17172 "Parse the standard Org-mode time string.
17173 This should be a lot faster than the normal `parse-time-string'.
17174 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17175 hour and minute fields will be nil if not given."
17176 (cond ((string-match org-ts-regexp0 s)
17177 (list 0
17178 (if (or (match-beginning 8) (not nodefault))
17179 (string-to-number (or (match-string 8 s) "0")))
17180 (if (or (match-beginning 7) (not nodefault))
17181 (string-to-number (or (match-string 7 s) "0")))
17182 (string-to-number (match-string 4 s))
17183 (string-to-number (match-string 3 s))
17184 (string-to-number (match-string 2 s))
17185 nil nil nil))
17186 ((string-match "^<[^>]+>$" s)
17187 (decode-time (seconds-to-time (org-matcher-time s))))
17188 (t (error "Not a standard Org-mode time string: %s" s))))
17190 (defun org-timestamp-up (&optional arg)
17191 "Increase the date item at the cursor by one.
17192 If the cursor is on the year, change the year. If it is on the month,
17193 the day or the time, change that.
17194 With prefix ARG, change by that many units."
17195 (interactive "p")
17196 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17198 (defun org-timestamp-down (&optional arg)
17199 "Decrease the date item at the cursor by one.
17200 If the cursor is on the year, change the year. If it is on the month,
17201 the day or the time, change that.
17202 With prefix ARG, change by that many units."
17203 (interactive "p")
17204 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17206 (defun org-timestamp-up-day (&optional arg)
17207 "Increase the date in the time stamp by one day.
17208 With prefix ARG, change that many days."
17209 (interactive "p")
17210 (if (and (not (org-at-timestamp-p t))
17211 (org-at-heading-p))
17212 (org-todo 'up)
17213 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17215 (defun org-timestamp-down-day (&optional arg)
17216 "Decrease the date in the time stamp by one day.
17217 With prefix ARG, change that many days."
17218 (interactive "p")
17219 (if (and (not (org-at-timestamp-p t))
17220 (org-at-heading-p))
17221 (org-todo 'down)
17222 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17224 (defun org-at-timestamp-p (&optional inactive-ok)
17225 "Determine if the cursor is in or at a timestamp."
17226 (interactive)
17227 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17228 (pos (point))
17229 (ans (or (looking-at tsr)
17230 (save-excursion
17231 (skip-chars-backward "^[<\n\r\t")
17232 (if (> (point) (point-min)) (backward-char 1))
17233 (and (looking-at tsr)
17234 (> (- (match-end 0) pos) -1))))))
17235 (and ans
17236 (boundp 'org-ts-what)
17237 (setq org-ts-what
17238 (cond
17239 ((= pos (match-beginning 0)) 'bracket)
17240 ;; Point is considered to be "on the bracket" whether
17241 ;; it's really on it or right after it.
17242 ((= pos (1- (match-end 0))) 'bracket)
17243 ((= pos (match-end 0)) 'after)
17244 ((org-pos-in-match-range pos 2) 'year)
17245 ((org-pos-in-match-range pos 3) 'month)
17246 ((org-pos-in-match-range pos 7) 'hour)
17247 ((org-pos-in-match-range pos 8) 'minute)
17248 ((or (org-pos-in-match-range pos 4)
17249 (org-pos-in-match-range pos 5)) 'day)
17250 ((and (> pos (or (match-end 8) (match-end 5)))
17251 (< pos (match-end 0)))
17252 (- pos (or (match-end 8) (match-end 5))))
17253 (t 'day))))
17254 ans))
17256 (defun org-toggle-timestamp-type ()
17257 "Toggle the type (<active> or [inactive]) of a time stamp."
17258 (interactive)
17259 (when (org-at-timestamp-p t)
17260 (let ((beg (match-beginning 0)) (end (match-end 0))
17261 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17262 (save-excursion
17263 (goto-char beg)
17264 (while (re-search-forward "[][<>]" end t)
17265 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17266 t t)))
17267 (message "Timestamp is now %sactive"
17268 (if (equal (char-after beg) ?<) "" "in")))))
17270 (defun org-at-clock-log-p nil
17271 "Is the cursor on the clock log line?"
17272 (save-excursion
17273 (move-beginning-of-line 1)
17274 (looking-at "^[ \t]*CLOCK:")))
17276 (defvar org-clock-history) ; defined in org-clock.el
17277 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17278 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17279 "Change the date in the time stamp at point.
17280 The date will be changed by N times WHAT. WHAT can be `day', `month',
17281 `year', `minute', `second'. If WHAT is not given, the cursor position
17282 in the timestamp determines what will be changed.
17283 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17284 (let ((origin (point)) origin-cat
17285 with-hm inactive
17286 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17287 org-ts-what
17288 extra rem
17289 ts time time0 fixnext clrgx)
17290 (if (not (org-at-timestamp-p t))
17291 (user-error "Not at a timestamp"))
17292 (if (and (not what) (eq org-ts-what 'bracket))
17293 (org-toggle-timestamp-type)
17294 ;; Point isn't on brackets. Remember the part of the time-stamp
17295 ;; the point was in. Indeed, size of time-stamps may change,
17296 ;; but point must be kept in the same category nonetheless.
17297 (setq origin-cat org-ts-what)
17298 (if (and (not what) (not (eq org-ts-what 'day))
17299 org-display-custom-times
17300 (get-text-property (point) 'display)
17301 (not (get-text-property (1- (point)) 'display)))
17302 (setq org-ts-what 'day))
17303 (setq org-ts-what (or what org-ts-what)
17304 inactive (= (char-after (match-beginning 0)) ?\[)
17305 ts (match-string 0))
17306 (replace-match "")
17307 (when (string-match
17308 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17310 (setq extra (match-string 1 ts))
17311 (if suppress-tmp-delay
17312 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17313 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17314 (setq with-hm t))
17315 (setq time0 (org-parse-time-string ts))
17316 (when (and updown
17317 (eq org-ts-what 'minute)
17318 (not current-prefix-arg))
17319 ;; This looks like s-up and s-down. Change by one rounding step.
17320 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17321 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17322 (setcar (cdr time0) (+ (nth 1 time0)
17323 (if (> n 0) (- rem) (- dm rem))))))
17324 (setq time
17325 (encode-time (or (car time0) 0)
17326 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17327 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17328 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17329 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17330 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17331 (nthcdr 6 time0)))
17332 (when (and (member org-ts-what '(hour minute))
17333 extra
17334 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17335 (setq extra (org-modify-ts-extra
17336 extra
17337 (if (eq org-ts-what 'hour) 2 5)
17338 n dm)))
17339 (when (integerp org-ts-what)
17340 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17341 (if (eq what 'calendar)
17342 (let ((cal-date (org-get-date-from-calendar)))
17343 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17344 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17345 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17346 (setcar time0 (or (car time0) 0))
17347 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17348 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17349 (setq time (apply 'encode-time time0))))
17350 ;; Insert the new time-stamp, and ensure point stays in the same
17351 ;; category as before (i.e. not after the last position in that
17352 ;; category).
17353 (let ((pos (point)))
17354 ;; Stay before inserted string. `save-excursion' is of no use.
17355 (setq org-last-changed-timestamp
17356 (org-insert-time-stamp time with-hm inactive nil nil extra))
17357 (goto-char pos))
17358 (save-match-data
17359 (looking-at org-ts-regexp3)
17360 (goto-char (cond
17361 ;; `day' category ends before `hour' if any, or at
17362 ;; the end of the day name.
17363 ((eq origin-cat 'day)
17364 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17365 ((eq origin-cat 'hour) (min (match-end 7) origin))
17366 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17367 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17368 ;; `year' and `month' have both fixed size: point
17369 ;; couldn't have moved into another part.
17370 (t origin))))
17371 ;; Update clock if on a CLOCK line.
17372 (org-clock-update-time-maybe)
17373 ;; Maybe adjust the closest clock in `org-clock-history'
17374 (when org-clock-adjust-closest
17375 (if (not (and (org-at-clock-log-p)
17376 (< 1 (length (delq nil (mapcar 'marker-position
17377 org-clock-history))))))
17378 (message "No clock to adjust")
17379 (cond ((save-excursion ; fix previous clock?
17380 (re-search-backward org-ts-regexp0 nil t)
17381 (org-looking-back (concat org-clock-string " \\[")))
17382 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17383 ((save-excursion ; fix next clock?
17384 (re-search-backward org-ts-regexp0 nil t)
17385 (looking-at (concat org-ts-regexp0 "\\] =>")))
17386 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17387 (save-window-excursion
17388 ;; Find closest clock to point, adjust the previous/next one in history
17389 (let* ((p (save-excursion (org-back-to-heading t)))
17390 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17391 (clfixnth
17392 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17393 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17394 (if (not clfixpos)
17395 (message "No clock to adjust")
17396 (save-excursion
17397 (org-goto-marker-or-bmk clfixpos)
17398 (org-show-subtree)
17399 (when (re-search-forward clrgx nil t)
17400 (goto-char (match-beginning 1))
17401 (let (org-clock-adjust-closest)
17402 (org-timestamp-change n org-ts-what updown))
17403 (message "Clock adjusted in %s for heading: %s"
17404 (file-name-nondirectory (buffer-file-name))
17405 (org-get-heading t t)))))))))
17406 ;; Try to recenter the calendar window, if any.
17407 (if (and org-calendar-follow-timestamp-change
17408 (get-buffer-window "*Calendar*" t)
17409 (memq org-ts-what '(day month year)))
17410 (org-recenter-calendar (time-to-days time))))))
17412 (defun org-modify-ts-extra (s pos n dm)
17413 "Change the different parts of the lead-time and repeat fields in timestamp."
17414 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17415 ng h m new rem)
17416 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17417 (cond
17418 ((or (org-pos-in-match-range pos 2)
17419 (org-pos-in-match-range pos 3))
17420 (setq m (string-to-number (match-string 3 s))
17421 h (string-to-number (match-string 2 s)))
17422 (if (org-pos-in-match-range pos 2)
17423 (setq h (+ h n))
17424 (setq n (* dm (org-no-warnings (signum n))))
17425 (when (not (= 0 (setq rem (% m dm))))
17426 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17427 (setq m (+ m n)))
17428 (if (< m 0) (setq m (+ m 60) h (1- h)))
17429 (if (> m 59) (setq m (- m 60) h (1+ h)))
17430 (setq h (min 24 (max 0 h)))
17431 (setq ng 1 new (format "-%02d:%02d" h m)))
17432 ((org-pos-in-match-range pos 6)
17433 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17434 ((org-pos-in-match-range pos 5)
17435 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17437 ((org-pos-in-match-range pos 9)
17438 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17439 ((org-pos-in-match-range pos 8)
17440 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17442 (when ng
17443 (setq s (concat
17444 (substring s 0 (match-beginning ng))
17446 (substring s (match-end ng))))))
17449 (defun org-recenter-calendar (date)
17450 "If the calendar is visible, recenter it to DATE."
17451 (let ((cwin (get-buffer-window "*Calendar*" t)))
17452 (when cwin
17453 (let ((calendar-move-hook nil))
17454 (with-selected-window cwin
17455 (calendar-goto-date (if (listp date) date
17456 (calendar-gregorian-from-absolute date))))))))
17458 (defun org-goto-calendar (&optional arg)
17459 "Go to the Emacs calendar at the current date.
17460 If there is a time stamp in the current line, go to that date.
17461 A prefix ARG can be used to force the current date."
17462 (interactive "P")
17463 (let ((tsr org-ts-regexp) diff
17464 (calendar-move-hook nil)
17465 (calendar-view-holidays-initially-flag nil)
17466 (calendar-view-diary-initially-flag nil))
17467 (if (or (org-at-timestamp-p)
17468 (save-excursion
17469 (beginning-of-line 1)
17470 (looking-at (concat ".*" tsr))))
17471 (let ((d1 (time-to-days (current-time)))
17472 (d2 (time-to-days
17473 (org-time-string-to-time (match-string 1)))))
17474 (setq diff (- d2 d1))))
17475 (calendar)
17476 (calendar-goto-today)
17477 (if (and diff (not arg)) (calendar-forward-day diff))))
17479 (defun org-get-date-from-calendar ()
17480 "Return a list (month day year) of date at point in calendar."
17481 (with-current-buffer "*Calendar*"
17482 (save-match-data
17483 (calendar-cursor-to-date))))
17485 (defun org-date-from-calendar ()
17486 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17487 If there is already a time stamp at the cursor position, update it."
17488 (interactive)
17489 (if (org-at-timestamp-p t)
17490 (org-timestamp-change 0 'calendar)
17491 (let ((cal-date (org-get-date-from-calendar)))
17492 (org-insert-time-stamp
17493 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17495 (defcustom org-effort-durations
17496 `(("h" . 60)
17497 ("d" . ,(* 60 8))
17498 ("w" . ,(* 60 8 5))
17499 ("m" . ,(* 60 8 5 4))
17500 ("y" . ,(* 60 8 5 40)))
17501 "Conversion factor to minutes for an effort modifier.
17503 Each entry has the form (MODIFIER . MINUTES).
17505 In an effort string, a number followed by MODIFIER is multiplied
17506 by the specified number of MINUTES to obtain an effort in
17507 minutes.
17509 For example, if the value of this variable is ((\"hours\" . 60)), then an
17510 effort string \"2hours\" is equivalent to 120 minutes."
17511 :group 'org-agenda
17512 :version "24.1"
17513 :type '(alist :key-type (string :tag "Modifier")
17514 :value-type (number :tag "Minutes")))
17516 (defun org-minutes-to-clocksum-string (m)
17517 "Format number of minutes as a clocksum string.
17518 The format is determined by `org-time-clocksum-format',
17519 `org-time-clocksum-use-fractional' and
17520 `org-time-clocksum-fractional-format' and
17521 `org-time-clocksum-use-effort-durations'."
17522 (let ((clocksum "")
17523 (m (round m)) ; Don't allow fractions of minutes
17524 h d w mo y fmt n)
17525 (setq h (if org-time-clocksum-use-effort-durations
17526 (cdr (assoc "h" org-effort-durations)) 60)
17527 d (if org-time-clocksum-use-effort-durations
17528 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17529 w (if org-time-clocksum-use-effort-durations
17530 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17531 mo (if org-time-clocksum-use-effort-durations
17532 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17533 y (if org-time-clocksum-use-effort-durations
17534 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17535 ;; fractional format
17536 (if org-time-clocksum-use-fractional
17537 (cond
17538 ;; single format string
17539 ((stringp org-time-clocksum-fractional-format)
17540 (format org-time-clocksum-fractional-format (/ m (float h))))
17541 ;; choice of fractional formats for different time units
17542 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17543 (> (/ (truncate m) (* y d h)) 0))
17544 (format fmt (/ m (* y d (float h)))))
17545 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17546 (> (/ (truncate m) (* mo d h)) 0))
17547 (format fmt (/ m (* mo d (float h)))))
17548 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17549 (> (/ (truncate m) (* w d h)) 0))
17550 (format fmt (/ m (* w d (float h)))))
17551 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17552 (> (/ (truncate m) (* d h)) 0))
17553 (format fmt (/ m (* d (float h)))))
17554 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17555 (> (/ (truncate m) h) 0))
17556 (format fmt (/ m (float h))))
17557 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17558 (format fmt m))
17559 ;; fall back to smallest time unit with a format
17560 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17561 (format fmt (/ m (float h))))
17562 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17563 (format fmt (/ m (* d (float h)))))
17564 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17565 (format fmt (/ m (* w d (float h)))))
17566 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17567 (format fmt (/ m (* mo d (float h)))))
17568 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17569 (format fmt (/ m (* y d (float h))))))
17570 ;; standard (non-fractional) format, with single format string
17571 (if (stringp org-time-clocksum-format)
17572 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17573 ;; separate formats components
17574 (and (setq fmt (plist-get org-time-clocksum-format :years))
17575 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17576 (plist-get org-time-clocksum-format :require-years))
17577 (setq clocksum (concat clocksum (format fmt n))
17578 m (- m (* n y d h))))
17579 (and (setq fmt (plist-get org-time-clocksum-format :months))
17580 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17581 (plist-get org-time-clocksum-format :require-months))
17582 (setq clocksum (concat clocksum (format fmt n))
17583 m (- m (* n mo d h))))
17584 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17585 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17586 (plist-get org-time-clocksum-format :require-weeks))
17587 (setq clocksum (concat clocksum (format fmt n))
17588 m (- m (* n w d h))))
17589 (and (setq fmt (plist-get org-time-clocksum-format :days))
17590 (or (> (setq n (/ (truncate m) (* d h))) 0)
17591 (plist-get org-time-clocksum-format :require-days))
17592 (setq clocksum (concat clocksum (format fmt n))
17593 m (- m (* n d h))))
17594 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17595 (or (> (setq n (/ (truncate m) h)) 0)
17596 (plist-get org-time-clocksum-format :require-hours))
17597 (setq clocksum (concat clocksum (format fmt n))
17598 m (- m (* n h))))
17599 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17600 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17601 (setq clocksum (concat clocksum (format fmt m))))
17602 ;; return formatted time duration
17603 clocksum))))
17605 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17606 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17607 "Org mode version 8.0")
17609 (defun org-hours-to-clocksum-string (n)
17610 (org-minutes-to-clocksum-string (* n 60)))
17612 (defun org-hh:mm-string-to-minutes (s)
17613 "Convert a string H:MM to a number of minutes.
17614 If the string is just a number, interpret it as minutes.
17615 In fact, the first hh:mm or number in the string will be taken,
17616 there can be extra stuff in the string.
17617 If no number is found, the return value is 0."
17618 (cond
17619 ((integerp s) s)
17620 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17621 (+ (* (string-to-number (match-string 1 s)) 60)
17622 (string-to-number (match-string 2 s))))
17623 ((string-match "\\([0-9]+\\)" s)
17624 (string-to-number (match-string 1 s)))
17625 (t 0)))
17627 (defcustom org-image-actual-width t
17628 "Should we use the actual width of images when inlining them?
17630 When set to `t', always use the image width.
17632 When set to a number, use imagemagick (when available) to set
17633 the image's width to this value.
17635 When set to a number in a list, try to get the width from any
17636 #+ATTR.* keyword if it matches a width specification like
17638 #+ATTR_HTML: :width 300px
17640 and fall back on that number if none is found.
17642 When set to nil, try to get the width from an #+ATTR.* keyword
17643 and fall back on the original width if none is found.
17645 This requires Emacs >= 24.1, build with imagemagick support."
17646 :group 'org-appearance
17647 :version "24.4"
17648 :package-version '(Org . "8.0")
17649 :type '(choice
17650 (const :tag "Use the image width" t)
17651 (integer :tag "Use a number of pixels")
17652 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17653 (const :tag "Use #+ATTR* or don't resize" nil)))
17655 (defcustom org-agenda-inhibit-startup nil
17656 "Inhibit startup when preparing agenda buffers.
17657 When this variable is `t' (the default), the initialization of
17658 the Org agenda buffers is inhibited: e.g. the visibility state
17659 is not set, the tables are not re-aligned, etc."
17660 :type 'boolean
17661 :version "24.3"
17662 :group 'org-agenda)
17664 (defun org-duration-string-to-minutes (s &optional output-to-string)
17665 "Convert a duration string S to minutes.
17667 A bare number is interpreted as minutes, modifiers can be set by
17668 customizing `org-effort-durations' (which see).
17670 Entries containing a colon are interpreted as H:MM by
17671 `org-hh:mm-string-to-minutes'."
17672 (let ((result 0)
17673 (re (concat "\\([0-9.]+\\) *\\("
17674 (regexp-opt (mapcar 'car org-effort-durations))
17675 "\\)")))
17676 (while (string-match re s)
17677 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17678 (string-to-number (match-string 1 s))))
17679 (setq s (replace-match "" nil t s)))
17680 (setq result (floor result))
17681 (incf result (org-hh:mm-string-to-minutes s))
17682 (if output-to-string (number-to-string result) result)))
17684 ;;;; Files
17686 (defun org-save-all-org-buffers ()
17687 "Save all Org-mode buffers without user confirmation."
17688 (interactive)
17689 (message "Saving all Org-mode buffers...")
17690 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17691 (when (featurep 'org-id) (org-id-locations-save))
17692 (message "Saving all Org-mode buffers... done"))
17694 (defun org-revert-all-org-buffers ()
17695 "Revert all Org-mode buffers.
17696 Prompt for confirmation when there are unsaved changes.
17697 Be sure you know what you are doing before letting this function
17698 overwrite your changes.
17700 This function is useful in a setup where one tracks org files
17701 with a version control system, to revert on one machine after pulling
17702 changes from another. I believe the procedure must be like this:
17704 1. M-x org-save-all-org-buffers
17705 2. Pull changes from the other machine, resolve conflicts
17706 3. M-x org-revert-all-org-buffers"
17707 (interactive)
17708 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17709 (user-error "Abort"))
17710 (save-excursion
17711 (save-window-excursion
17712 (mapc
17713 (lambda (b)
17714 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17715 (with-current-buffer b buffer-file-name))
17716 (org-pop-to-buffer-same-window b)
17717 (revert-buffer t 'no-confirm)))
17718 (buffer-list))
17719 (when (and (featurep 'org-id) org-id-track-globally)
17720 (org-id-locations-load)))))
17722 ;;;; Agenda files
17724 ;;;###autoload
17725 (defun org-switchb (&optional arg)
17726 "Switch between Org buffers.
17727 With one prefix argument, restrict available buffers to files.
17728 With two prefix arguments, restrict available buffers to agenda files.
17730 Defaults to `iswitchb' for buffer name completion.
17731 Set `org-completion-use-ido' to make it use ido instead."
17732 (interactive "P")
17733 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17734 ((equal arg '(16)) (org-buffer-list 'agenda))
17735 (t (org-buffer-list))))
17736 (org-completion-use-iswitchb org-completion-use-iswitchb)
17737 (org-completion-use-ido org-completion-use-ido))
17738 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17739 (setq org-completion-use-iswitchb t))
17740 (org-pop-to-buffer-same-window
17741 (org-icompleting-read "Org buffer: "
17742 (mapcar 'list (mapcar 'buffer-name blist))
17743 nil t))))
17745 ;;; Define some older names previously used for this functionality
17746 ;;;###autoload
17747 (defalias 'org-ido-switchb 'org-switchb)
17748 ;;;###autoload
17749 (defalias 'org-iswitchb 'org-switchb)
17751 (defun org-buffer-list (&optional predicate exclude-tmp)
17752 "Return a list of Org buffers.
17753 PREDICATE can be `export', `files' or `agenda'.
17755 export restrict the list to Export buffers.
17756 files restrict the list to buffers visiting Org files.
17757 agenda restrict the list to buffers visiting agenda files.
17759 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17760 (let* ((bfn nil)
17761 (agenda-files (and (eq predicate 'agenda)
17762 (mapcar 'file-truename (org-agenda-files t))))
17763 (filter
17764 (cond
17765 ((eq predicate 'files)
17766 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17767 ((eq predicate 'export)
17768 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17769 ((eq predicate 'agenda)
17770 (lambda (b)
17771 (with-current-buffer b
17772 (and (derived-mode-p 'org-mode)
17773 (setq bfn (buffer-file-name b))
17774 (member (file-truename bfn) agenda-files)))))
17775 (t (lambda (b) (with-current-buffer b
17776 (or (derived-mode-p 'org-mode)
17777 (string-match "\*Org .*Export"
17778 (buffer-name b)))))))))
17779 (delq nil
17780 (mapcar
17781 (lambda(b)
17782 (if (and (funcall filter b)
17783 (or (not exclude-tmp)
17784 (not (string-match "tmp" (buffer-name b)))))
17786 nil))
17787 (buffer-list)))))
17789 (defun org-agenda-files (&optional unrestricted archives)
17790 "Get the list of agenda files.
17791 Optional UNRESTRICTED means return the full list even if a restriction
17792 is currently in place.
17793 When ARCHIVES is t, include all archive files that are really being
17794 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17795 `org-agenda-archives-mode' is t."
17796 (let ((files
17797 (cond
17798 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17799 ((stringp org-agenda-files) (org-read-agenda-file-list))
17800 ((listp org-agenda-files) org-agenda-files)
17801 (t (error "Invalid value of `org-agenda-files'")))))
17802 (setq files (apply 'append
17803 (mapcar (lambda (f)
17804 (if (file-directory-p f)
17805 (directory-files
17806 f t org-agenda-file-regexp)
17807 (list f)))
17808 files)))
17809 (when org-agenda-skip-unavailable-files
17810 (setq files (delq nil
17811 (mapcar (function
17812 (lambda (file)
17813 (and (file-readable-p file) file)))
17814 files))))
17815 (when (or (eq archives t)
17816 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17817 (setq files (org-add-archive-files files)))
17818 files))
17820 (defun org-agenda-file-p (&optional file)
17821 "Return non-nil, if FILE is an agenda file.
17822 If FILE is omitted, use the file associated with the current
17823 buffer."
17824 (member (or file (buffer-file-name))
17825 (org-agenda-files t)))
17827 (defun org-edit-agenda-file-list ()
17828 "Edit the list of agenda files.
17829 Depending on setup, this either uses customize to edit the variable
17830 `org-agenda-files', or it visits the file that is holding the list. In the
17831 latter case, the buffer is set up in a way that saving it automatically kills
17832 the buffer and restores the previous window configuration."
17833 (interactive)
17834 (if (stringp org-agenda-files)
17835 (let ((cw (current-window-configuration)))
17836 (find-file org-agenda-files)
17837 (org-set-local 'org-window-configuration cw)
17838 (org-add-hook 'after-save-hook
17839 (lambda ()
17840 (set-window-configuration
17841 (prog1 org-window-configuration
17842 (kill-buffer (current-buffer))))
17843 (org-install-agenda-files-menu)
17844 (message "New agenda file list installed"))
17845 nil 'local)
17846 (message "%s" (substitute-command-keys
17847 "Edit list and finish with \\[save-buffer]")))
17848 (customize-variable 'org-agenda-files)))
17850 (defun org-store-new-agenda-file-list (list)
17851 "Set new value for the agenda file list and save it correctly."
17852 (if (stringp org-agenda-files)
17853 (let ((fe (org-read-agenda-file-list t)) b u)
17854 (while (setq b (find-buffer-visiting org-agenda-files))
17855 (kill-buffer b))
17856 (with-temp-file org-agenda-files
17857 (insert
17858 (mapconcat
17859 (lambda (f) ;; Keep un-expanded entries.
17860 (if (setq u (assoc f fe))
17861 (cdr u)
17863 list "\n")
17864 "\n")))
17865 (let ((org-mode-hook nil) (org-inhibit-startup t)
17866 (org-insert-mode-line-in-empty-file nil))
17867 (setq org-agenda-files list)
17868 (customize-save-variable 'org-agenda-files org-agenda-files))))
17870 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17871 "Read the list of agenda files from a file.
17872 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17873 filenames, used by `org-store-new-agenda-file-list' to write back
17874 un-expanded file names."
17875 (when (file-directory-p org-agenda-files)
17876 (error "`org-agenda-files' cannot be a single directory"))
17877 (when (stringp org-agenda-files)
17878 (with-temp-buffer
17879 (insert-file-contents org-agenda-files)
17880 (mapcar
17881 (lambda (f)
17882 (let ((e (expand-file-name (substitute-in-file-name f)
17883 org-directory)))
17884 (if pair-with-expansion
17885 (cons e f)
17886 e)))
17887 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17889 ;;;###autoload
17890 (defun org-cycle-agenda-files ()
17891 "Cycle through the files in `org-agenda-files'.
17892 If the current buffer visits an agenda file, find the next one in the list.
17893 If the current buffer does not, find the first agenda file."
17894 (interactive)
17895 (let* ((fs (org-agenda-files t))
17896 (files (append fs (list (car fs))))
17897 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17898 file)
17899 (unless files (user-error "No agenda files"))
17900 (catch 'exit
17901 (while (setq file (pop files))
17902 (if (equal (file-truename file) tcf)
17903 (when (car files)
17904 (find-file (car files))
17905 (throw 'exit t))))
17906 (find-file (car fs)))
17907 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17909 (defun org-agenda-file-to-front (&optional to-end)
17910 "Move/add the current file to the top of the agenda file list.
17911 If the file is not present in the list, it is added to the front. If it is
17912 present, it is moved there. With optional argument TO-END, add/move to the
17913 end of the list."
17914 (interactive "P")
17915 (let ((org-agenda-skip-unavailable-files nil)
17916 (file-alist (mapcar (lambda (x)
17917 (cons (file-truename x) x))
17918 (org-agenda-files t)))
17919 (ctf (file-truename
17920 (or buffer-file-name
17921 (user-error "Please save the current buffer to a file"))))
17922 x had)
17923 (setq x (assoc ctf file-alist) had x)
17925 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17926 (if to-end
17927 (setq file-alist (append (delq x file-alist) (list x)))
17928 (setq file-alist (cons x (delq x file-alist))))
17929 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17930 (org-install-agenda-files-menu)
17931 (message "File %s to %s of agenda file list"
17932 (if had "moved" "added") (if to-end "end" "front"))))
17934 (defun org-remove-file (&optional file)
17935 "Remove current file from the list of files in variable `org-agenda-files'.
17936 These are the files which are being checked for agenda entries.
17937 Optional argument FILE means use this file instead of the current."
17938 (interactive)
17939 (let* ((org-agenda-skip-unavailable-files nil)
17940 (file (or file buffer-file-name
17941 (user-error "Current buffer does not visit a file")))
17942 (true-file (file-truename file))
17943 (afile (abbreviate-file-name file))
17944 (files (delq nil (mapcar
17945 (lambda (x)
17946 (if (equal true-file
17947 (file-truename x))
17948 nil x))
17949 (org-agenda-files t)))))
17950 (if (not (= (length files) (length (org-agenda-files t))))
17951 (progn
17952 (org-store-new-agenda-file-list files)
17953 (org-install-agenda-files-menu)
17954 (message "Removed file: %s" afile))
17955 (message "File was not in list: %s (not removed)" afile))))
17957 (defun org-file-menu-entry (file)
17958 (vector file (list 'find-file file) t))
17960 (defun org-check-agenda-file (file)
17961 "Make sure FILE exists. If not, ask user what to do."
17962 (when (not (file-exists-p file))
17963 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17964 (abbreviate-file-name file))
17965 (let ((r (downcase (read-char-exclusive))))
17966 (cond
17967 ((equal r ?r)
17968 (org-remove-file file)
17969 (throw 'nextfile t))
17970 (t (error "Abort"))))))
17972 (defun org-get-agenda-file-buffer (file)
17973 "Get a buffer visiting FILE. If the buffer needs to be created, add
17974 it to the list of buffers which might be released later."
17975 (let ((buf (org-find-base-buffer-visiting file)))
17976 (if buf
17977 buf ; just return it
17978 ;; Make a new buffer and remember it
17979 (setq buf (find-file-noselect file))
17980 (if buf (push buf org-agenda-new-buffers))
17981 buf)))
17983 (defun org-release-buffers (blist)
17984 "Release all buffers in list, asking the user for confirmation when needed.
17985 When a buffer is unmodified, it is just killed. When modified, it is saved
17986 \(if the user agrees) and then killed."
17987 (let (buf file)
17988 (while (setq buf (pop blist))
17989 (setq file (buffer-file-name buf))
17990 (when (and (buffer-modified-p buf)
17991 file
17992 (y-or-n-p (format "Save file %s? " file)))
17993 (with-current-buffer buf (save-buffer)))
17994 (kill-buffer buf))))
17996 (defun org-agenda-prepare-buffers (files)
17997 "Create buffers for all agenda files, protect archived trees and comments."
17998 (interactive)
17999 (let ((pa '(:org-archived t))
18000 (pc '(:org-comment t))
18001 (pall '(:org-archived t :org-comment t))
18002 (inhibit-read-only t)
18003 (org-inhibit-startup org-agenda-inhibit-startup)
18004 (rea (concat ":" org-archive-tag ":"))
18005 file re)
18006 (setq org-tag-alist-for-agenda nil
18007 org-tag-groups-alist-for-agenda nil)
18008 (save-excursion
18009 (save-restriction
18010 (while (setq file (pop files))
18011 (catch 'nextfile
18012 (if (bufferp file)
18013 (set-buffer file)
18014 (org-check-agenda-file file)
18015 (set-buffer (org-get-agenda-file-buffer file)))
18016 (widen)
18017 (org-set-regexps-and-options-for-tags)
18018 (goto-char (point-min))
18019 (let ((case-fold-search t))
18020 (when (search-forward "#+setupfile" nil t)
18021 ;; Don't set all regexps and options systematically as
18022 ;; this is only run for setting agenda tags from setup
18023 ;; file
18024 (org-set-regexps-and-options)))
18025 (org-refresh-category-properties)
18026 (org-refresh-properties org-effort-property 'org-effort)
18027 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18028 (setq org-todo-keywords-for-agenda
18029 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18030 (setq org-done-keywords-for-agenda
18031 (append org-done-keywords-for-agenda org-done-keywords))
18032 (setq org-todo-keyword-alist-for-agenda
18033 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18034 (setq org-drawers-for-agenda
18035 (append org-drawers-for-agenda org-drawers))
18036 (setq org-tag-alist-for-agenda
18037 (org-uniquify
18038 (append org-tag-alist-for-agenda
18039 org-tag-alist
18040 org-tag-persistent-alist)))
18041 (if org-group-tags
18042 (setq org-tag-groups-alist-for-agenda
18043 (org-uniquify-alist
18044 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18045 (org-with-silent-modifications
18046 (save-excursion
18047 (remove-text-properties (point-min) (point-max) pall)
18048 (when org-agenda-skip-archived-trees
18049 (goto-char (point-min))
18050 (while (re-search-forward rea nil t)
18051 (if (org-at-heading-p t)
18052 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18053 (goto-char (point-min))
18054 (setq re (format org-heading-keyword-regexp-format
18055 org-comment-string))
18056 (while (re-search-forward re nil t)
18057 (add-text-properties
18058 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18059 (setq org-todo-keywords-for-agenda
18060 (org-uniquify org-todo-keywords-for-agenda))
18061 (setq org-todo-keyword-alist-for-agenda
18062 (org-uniquify org-todo-keyword-alist-for-agenda))))
18065 ;;;; CDLaTeX minor mode
18067 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18068 "Keymap for the minor `org-cdlatex-mode'.")
18070 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18071 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18072 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18073 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18074 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18076 (defvar org-cdlatex-texmathp-advice-is-done nil
18077 "Flag remembering if we have applied the advice to texmathp already.")
18079 (define-minor-mode org-cdlatex-mode
18080 "Toggle the minor `org-cdlatex-mode'.
18081 This mode supports entering LaTeX environment and math in LaTeX fragments
18082 in Org-mode.
18083 \\{org-cdlatex-mode-map}"
18084 nil " OCDL" nil
18085 (when org-cdlatex-mode
18086 (require 'cdlatex)
18087 (run-hooks 'cdlatex-mode-hook)
18088 (cdlatex-compute-tables))
18089 (unless org-cdlatex-texmathp-advice-is-done
18090 (setq org-cdlatex-texmathp-advice-is-done t)
18091 (defadvice texmathp (around org-math-always-on activate)
18092 "Always return t in org-mode buffers.
18093 This is because we want to insert math symbols without dollars even outside
18094 the LaTeX math segments. If Orgmode thinks that point is actually inside
18095 an embedded LaTeX fragment, let texmathp do its job.
18096 \\[org-cdlatex-mode-map]"
18097 (interactive)
18098 (let (p)
18099 (cond
18100 ((not (derived-mode-p 'org-mode)) ad-do-it)
18101 ((eq this-command 'cdlatex-math-symbol)
18102 (setq ad-return-value t
18103 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18105 (let ((p (org-inside-LaTeX-fragment-p)))
18106 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18107 (setq ad-return-value t
18108 texmathp-why '("Org-mode embedded math" . 0))
18109 (if p ad-do-it)))))))))
18111 (defun turn-on-org-cdlatex ()
18112 "Unconditionally turn on `org-cdlatex-mode'."
18113 (org-cdlatex-mode 1))
18115 (defun org-try-cdlatex-tab ()
18116 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18117 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18118 - inside a LaTeX fragment, or
18119 - after the first word in a line, where an abbreviation expansion could
18120 insert a LaTeX environment."
18121 (when org-cdlatex-mode
18122 (cond
18123 ;; Before any word on the line: No expansion possible.
18124 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18125 ;; Just after first word on the line: Expand it. Make sure it
18126 ;; cannot happen on headlines, though.
18127 ((save-excursion
18128 (skip-chars-backward "a-zA-Z0-9*")
18129 (skip-chars-backward " \t")
18130 (and (bolp) (not (org-at-heading-p))))
18131 (cdlatex-tab) t)
18132 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18134 (defun org-cdlatex-underscore-caret (&optional arg)
18135 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18136 Revert to the normal definition outside of these fragments."
18137 (interactive "P")
18138 (if (org-inside-LaTeX-fragment-p)
18139 (call-interactively 'cdlatex-sub-superscript)
18140 (let (org-cdlatex-mode)
18141 (call-interactively (key-binding (vector last-input-event))))))
18143 (defun org-cdlatex-math-modify (&optional arg)
18144 "Execute `cdlatex-math-modify' in LaTeX fragments.
18145 Revert to the normal definition outside of these fragments."
18146 (interactive "P")
18147 (if (org-inside-LaTeX-fragment-p)
18148 (call-interactively 'cdlatex-math-modify)
18149 (let (org-cdlatex-mode)
18150 (call-interactively (key-binding (vector last-input-event))))))
18154 ;;;; LaTeX fragments
18156 (defvar org-latex-regexps
18157 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18158 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18159 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18160 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18161 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18162 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18163 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18164 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18165 "Regular expressions for matching embedded LaTeX.")
18167 (defun org-inside-LaTeX-fragment-p ()
18168 "Test if point is inside a LaTeX fragment.
18169 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18170 sequence appearing also before point.
18171 Even though the matchers for math are configurable, this function assumes
18172 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18173 delimiters are skipped when they have been removed by customization.
18174 The return value is nil, or a cons cell with the delimiter and the
18175 position of this delimiter.
18177 This function does a reasonably good job, but can locally be fooled by
18178 for example currency specifications. For example it will assume being in
18179 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18180 fragments that are properly closed, but during editing, we have to live
18181 with the uncertainty caused by missing closing delimiters. This function
18182 looks only before point, not after."
18183 (catch 'exit
18184 (let ((pos (point))
18185 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18186 (lim (progn
18187 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18188 (point)))
18189 dd-on str (start 0) m re)
18190 (goto-char pos)
18191 (when dodollar
18192 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18193 re (nth 1 (assoc "$" org-latex-regexps)))
18194 (while (string-match re str start)
18195 (cond
18196 ((= (match-end 0) (length str))
18197 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18198 ((= (match-end 0) (- (length str) 5))
18199 (throw 'exit nil))
18200 (t (setq start (match-end 0))))))
18201 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18202 (goto-char pos)
18203 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18204 (and (match-beginning 2) (throw 'exit nil))
18205 ;; count $$
18206 (while (re-search-backward "\\$\\$" lim t)
18207 (setq dd-on (not dd-on)))
18208 (goto-char pos)
18209 (if dd-on (cons "$$" m))))))
18211 (defun org-inside-latex-macro-p ()
18212 "Is point inside a LaTeX macro or its arguments?"
18213 (save-match-data
18214 (org-in-regexp
18215 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18217 (defvar org-latex-fragment-image-overlays nil
18218 "List of overlays carrying the images of latex fragments.")
18219 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18221 (defun org-remove-latex-fragment-image-overlays ()
18222 "Remove all overlays with LaTeX fragment images in current buffer."
18223 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18224 (setq org-latex-fragment-image-overlays nil))
18226 (defun org-preview-latex-fragment (&optional subtree)
18227 "Preview the LaTeX fragment at point, or all locally or globally.
18228 If the cursor is in a LaTeX fragment, create the image and overlay
18229 it over the source code. If there is no fragment at point, display
18230 all fragments in the current text, from one headline to the next. With
18231 prefix SUBTREE, display all fragments in the current subtree. With a
18232 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18233 the cursor is before the first headline,
18234 display all fragments in the buffer.
18235 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18236 (interactive "P")
18237 (unless buffer-file-name
18238 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18239 (when (display-graphic-p)
18240 (org-remove-latex-fragment-image-overlays)
18241 (save-excursion
18242 (save-restriction
18243 (let (beg end at msg)
18244 (cond
18245 ((or (equal subtree '(16))
18246 (not (save-excursion
18247 (re-search-backward org-outline-regexp-bol nil t))))
18248 (setq beg (point-min) end (point-max)
18249 msg "Creating images for buffer...%s"))
18250 ((equal subtree '(4))
18251 (org-back-to-heading)
18252 (setq beg (point) end (org-end-of-subtree t)
18253 msg "Creating images for subtree...%s"))
18255 (if (setq at (org-inside-LaTeX-fragment-p))
18256 (goto-char (max (point-min) (- (cdr at) 2)))
18257 (org-back-to-heading))
18258 (setq beg (point) end (progn (outline-next-heading) (point))
18259 msg (if at "Creating image...%s"
18260 "Creating images for entry...%s"))))
18261 (message msg "")
18262 (narrow-to-region beg end)
18263 (goto-char beg)
18264 (org-format-latex
18265 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18266 (file-name-nondirectory
18267 buffer-file-name)))
18268 default-directory 'overlays msg at 'forbuffer
18269 org-latex-create-formula-image-program)
18270 (message msg "done. Use `C-c C-c' to remove images."))))))
18272 (defun org-format-latex (prefix &optional dir overlays msg at
18273 forbuffer processing-type)
18274 "Replace LaTeX fragments with links to an image, and produce images.
18275 Some of the options can be changed using the variable
18276 `org-format-latex-options'."
18277 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18278 (let* ((prefixnodir (file-name-nondirectory prefix))
18279 (absprefix (expand-file-name prefix dir))
18280 (todir (file-name-directory absprefix))
18281 (opt org-format-latex-options)
18282 (optnew org-format-latex-options)
18283 (matchers (plist-get opt :matchers))
18284 (re-list org-latex-regexps)
18285 (cnt 0) txt hash link beg end re e checkdir
18286 string
18287 m n block-type block linkfile movefile ov)
18288 ;; Check the different regular expressions
18289 (while (setq e (pop re-list))
18290 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18291 block (if block-type "\n\n" ""))
18292 (when (member m matchers)
18293 (goto-char (point-min))
18294 (while (re-search-forward re nil t)
18295 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18296 (or (not overlays)
18297 (not (eq (get-char-property (match-beginning n)
18298 'org-overlay-type)
18299 'org-latex-overlay))))
18300 (cond
18301 ((eq processing-type 'verbatim))
18302 ((eq processing-type 'mathjax)
18303 ;; Prepare for MathJax processing.
18304 (setq string (match-string n))
18305 (when (member m '("$" "$1"))
18306 (save-excursion
18307 (delete-region (match-beginning n) (match-end n))
18308 (goto-char (match-beginning n))
18309 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18310 ((or (eq processing-type 'dvipng)
18311 (eq processing-type 'imagemagick))
18312 ;; Process to an image.
18313 (setq txt (match-string n)
18314 beg (match-beginning n) end (match-end n)
18315 cnt (1+ cnt))
18316 (let ((face (face-at-point))
18317 (fg (plist-get opt :foreground))
18318 (bg (plist-get opt :background))
18319 ;; Ensure full list is printed.
18320 print-length print-level)
18321 (when forbuffer
18322 ;; Get the colors from the face at point.
18323 (goto-char beg)
18324 (when (eq fg 'auto)
18325 (setq fg (face-attribute face :foreground nil 'default)))
18326 (when (eq bg 'auto)
18327 (setq bg (face-attribute face :background nil 'default)))
18328 (setq optnew (copy-sequence opt))
18329 (plist-put optnew :foreground fg)
18330 (plist-put optnew :background bg))
18331 (setq hash (sha1 (prin1-to-string
18332 (list org-format-latex-header
18333 org-latex-default-packages-alist
18334 org-latex-packages-alist
18335 org-format-latex-options
18336 forbuffer txt fg bg)))
18337 linkfile (format "%s_%s.png" prefix hash)
18338 movefile (format "%s_%s.png" absprefix hash)))
18339 (setq link (concat block "[[file:" linkfile "]]" block))
18340 (if msg (message msg cnt))
18341 (goto-char beg)
18342 (unless checkdir ; Ensure the directory exists.
18343 (setq checkdir t)
18344 (or (file-directory-p todir) (make-directory todir t)))
18345 (unless (file-exists-p movefile)
18346 (org-create-formula-image
18347 txt movefile optnew forbuffer processing-type))
18348 (if overlays
18349 (progn
18350 (mapc (lambda (o)
18351 (if (eq (overlay-get o 'org-overlay-type)
18352 'org-latex-overlay)
18353 (delete-overlay o)))
18354 (overlays-in beg end))
18355 (setq ov (make-overlay beg end))
18356 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18357 (if (featurep 'xemacs)
18358 (progn
18359 (overlay-put ov 'invisible t)
18360 (overlay-put
18361 ov 'end-glyph
18362 (make-glyph (vector 'png :file movefile))))
18363 (overlay-put
18364 ov 'display
18365 (list 'image :type 'png :file movefile :ascent 'center)))
18366 (push ov org-latex-fragment-image-overlays)
18367 (goto-char end))
18368 (delete-region beg end)
18369 (insert (org-add-props link
18370 (list 'org-latex-src
18371 (replace-regexp-in-string
18372 "\"" "" txt)
18373 'org-latex-src-embed-type
18374 (if block-type 'paragraph 'character))))))
18375 ((eq processing-type 'mathml)
18376 ;; Process to MathML
18377 (unless (save-match-data (org-format-latex-mathml-available-p))
18378 (user-error "LaTeX to MathML converter not configured"))
18379 (setq txt (match-string n)
18380 beg (match-beginning n) end (match-end n)
18381 cnt (1+ cnt))
18382 (if msg (message msg cnt))
18383 (goto-char beg)
18384 (delete-region beg end)
18385 (insert (org-format-latex-as-mathml
18386 txt block-type prefix dir)))
18388 (error "Unknown conversion type %s for LaTeX fragments"
18389 processing-type)))))))))
18391 (defun org-create-math-formula (latex-frag &optional mathml-file)
18392 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18393 Use `org-latex-to-mathml-convert-command'. If the conversion is
18394 sucessful, return the portion between \"<math...> </math>\"
18395 elements otherwise return nil. When MATHML-FILE is specified,
18396 write the results in to that file. When invoked as an
18397 interactive command, prompt for LATEX-FRAG, with initial value
18398 set to the current active region and echo the results for user
18399 inspection."
18400 (interactive (list (let ((frag (when (org-region-active-p)
18401 (buffer-substring-no-properties
18402 (region-beginning) (region-end)))))
18403 (read-string "LaTeX Fragment: " frag nil frag))))
18404 (unless latex-frag (error "Invalid LaTeX fragment"))
18405 (let* ((tmp-in-file (file-relative-name
18406 (make-temp-name (expand-file-name "ltxmathml-in"))))
18407 (ignore (write-region latex-frag nil tmp-in-file))
18408 (tmp-out-file (file-relative-name
18409 (make-temp-name (expand-file-name "ltxmathml-out"))))
18410 (cmd (format-spec
18411 org-latex-to-mathml-convert-command
18412 `((?j . ,(shell-quote-argument
18413 (expand-file-name org-latex-to-mathml-jar-file)))
18414 (?I . ,(shell-quote-argument tmp-in-file))
18415 (?o . ,(shell-quote-argument tmp-out-file)))))
18416 mathml shell-command-output)
18417 (when (org-called-interactively-p 'any)
18418 (unless (org-format-latex-mathml-available-p)
18419 (user-error "LaTeX to MathML converter not configured")))
18420 (message "Running %s" cmd)
18421 (setq shell-command-output (shell-command-to-string cmd))
18422 (setq mathml
18423 (when (file-readable-p tmp-out-file)
18424 (with-current-buffer (find-file-noselect tmp-out-file t)
18425 (goto-char (point-min))
18426 (when (re-search-forward
18427 (concat
18428 (regexp-quote
18429 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18430 "\\(.\\|\n\\)*"
18431 (regexp-quote "</math>")) nil t)
18432 (prog1 (match-string 0) (kill-buffer))))))
18433 (cond
18434 (mathml
18435 (setq mathml
18436 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18437 (when mathml-file
18438 (write-region mathml nil mathml-file))
18439 (when (org-called-interactively-p 'any)
18440 (message mathml)))
18441 ((message "LaTeX to MathML conversion failed")
18442 (message shell-command-output)))
18443 (delete-file tmp-in-file)
18444 (when (file-exists-p tmp-out-file)
18445 (delete-file tmp-out-file))
18446 mathml))
18448 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18449 prefix &optional dir)
18450 "Use `org-create-math-formula' but check local cache first."
18451 (let* ((absprefix (expand-file-name prefix dir))
18452 (print-length nil) (print-level nil)
18453 (formula-id (concat
18454 "formula-"
18455 (sha1
18456 (prin1-to-string
18457 (list latex-frag
18458 org-latex-to-mathml-convert-command)))))
18459 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18460 (formula-cache-dir (file-name-directory formula-cache)))
18462 (unless (file-directory-p formula-cache-dir)
18463 (make-directory formula-cache-dir t))
18465 (unless (file-exists-p formula-cache)
18466 (org-create-math-formula latex-frag formula-cache))
18468 (if (file-exists-p formula-cache)
18469 ;; Successful conversion. Return the link to MathML file.
18470 (org-add-props
18471 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18472 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18473 'org-latex-src-embed-type (if latex-frag-type
18474 'paragraph 'character)))
18475 ;; Failed conversion. Return the LaTeX fragment verbatim
18476 latex-frag)))
18478 (defun org-create-formula-image (string tofile options buffer &optional type)
18479 "Create an image from LaTeX source using dvipng or convert.
18480 This function calls either `org-create-formula-image-with-dvipng'
18481 or `org-create-formula-image-with-imagemagick' depending on the
18482 value of `org-latex-create-formula-image-program' or on the value
18483 of the optional TYPE variable.
18485 Note: ultimately these two function should be combined as they
18486 share a good deal of logic."
18487 (org-check-external-command
18488 "latex" "needed to convert LaTeX fragments to images")
18489 (funcall
18490 (case (or type org-latex-create-formula-image-program)
18491 ('dvipng
18492 (org-check-external-command
18493 "dvipng" "needed to convert LaTeX fragments to images")
18494 #'org-create-formula-image-with-dvipng)
18495 ('imagemagick
18496 (org-check-external-command
18497 "convert" "you need to install imagemagick")
18498 #'org-create-formula-image-with-imagemagick)
18499 (t (error
18500 "Invalid value of `org-latex-create-formula-image-program'")))
18501 string tofile options buffer))
18503 (declare-function org-export--get-global-options "ox" (&optional backend))
18504 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18505 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18506 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18507 (defun org-create-formula--latex-header ()
18508 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18509 (let ((info (org-combine-plists (org-export--get-global-options 'latex)
18510 (org-export--get-inbuffer-options 'latex))))
18511 (org-latex-guess-babel-language
18512 (org-latex-guess-inputenc
18513 (org-splice-latex-header
18514 org-format-latex-header
18515 org-latex-default-packages-alist
18516 org-latex-packages-alist t
18517 (plist-get info :latex-header)))
18518 info)))
18520 ;; This function borrows from Ganesh Swami's latex2png.el
18521 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18522 "This calls dvipng."
18523 (require 'ox-latex)
18524 (let* ((tmpdir (if (featurep 'xemacs)
18525 (temp-directory)
18526 temporary-file-directory))
18527 (texfilebase (make-temp-name
18528 (expand-file-name "orgtex" tmpdir)))
18529 (texfile (concat texfilebase ".tex"))
18530 (dvifile (concat texfilebase ".dvi"))
18531 (pngfile (concat texfilebase ".png"))
18532 (fnh (if (featurep 'xemacs)
18533 (font-height (face-font 'default))
18534 (face-attribute 'default :height nil)))
18535 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18536 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18537 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18538 "Black"))
18539 (bg (or (plist-get options (if buffer :background :html-background))
18540 "Transparent")))
18541 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18542 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18543 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18544 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18545 (let ((latex-header (org-create-formula--latex-header)))
18546 (with-temp-file texfile
18547 (insert latex-header)
18548 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18549 (let ((dir default-directory))
18550 (condition-case nil
18551 (progn
18552 (cd tmpdir)
18553 (call-process "latex" nil nil nil texfile))
18554 (error nil))
18555 (cd dir))
18556 (if (not (file-exists-p dvifile))
18557 (progn (message "Failed to create dvi file from %s" texfile) nil)
18558 (condition-case nil
18559 (if (featurep 'xemacs)
18560 (call-process "dvipng" nil nil nil
18561 "-fg" fg "-bg" bg
18562 "-T" "tight"
18563 "-o" pngfile
18564 dvifile)
18565 (call-process "dvipng" nil nil nil
18566 "-fg" fg "-bg" bg
18567 "-D" dpi
18568 ;;"-x" scale "-y" scale
18569 "-T" "tight"
18570 "-o" pngfile
18571 dvifile))
18572 (error nil))
18573 (if (not (file-exists-p pngfile))
18574 (if org-format-latex-signal-error
18575 (error "Failed to create png file from %s" texfile)
18576 (message "Failed to create png file from %s" texfile)
18577 nil)
18578 ;; Use the requested file name and clean up
18579 (copy-file pngfile tofile 'replace)
18580 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18581 (if (file-exists-p (concat texfilebase e))
18582 (delete-file (concat texfilebase e))))
18583 pngfile))))
18585 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18586 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18587 "This calls convert, which is included into imagemagick."
18588 (require 'ox-latex)
18589 (let* ((tmpdir (if (featurep 'xemacs)
18590 (temp-directory)
18591 temporary-file-directory))
18592 (texfilebase (make-temp-name
18593 (expand-file-name "orgtex" tmpdir)))
18594 (texfile (concat texfilebase ".tex"))
18595 (pdffile (concat texfilebase ".pdf"))
18596 (pngfile (concat texfilebase ".png"))
18597 (fnh (if (featurep 'xemacs)
18598 (font-height (face-font 'default))
18599 (face-attribute 'default :height nil)))
18600 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18601 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18602 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18603 "black"))
18604 (bg (or (plist-get options (if buffer :background :html-background))
18605 "white")))
18606 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18607 (setq fg (org-latex-color-format fg)))
18608 (if (eq bg 'default) (setq bg (org-latex-color :background))
18609 (setq bg (org-latex-color-format
18610 (if (string= bg "Transparent") "white" bg))))
18611 (let ((latex-header (org-create-formula--latex-header)))
18612 (with-temp-file texfile
18613 (insert latex-header)
18614 (insert "\n\\begin{document}\n"
18615 "\\definecolor{fg}{rgb}{" fg "}\n"
18616 "\\definecolor{bg}{rgb}{" bg "}\n"
18617 "\n\\pagecolor{bg}\n"
18618 "\n{\\color{fg}\n"
18619 string
18620 "\n}\n"
18621 "\n\\end{document}\n")))
18622 (org-latex-compile texfile t)
18623 (if (not (file-exists-p pdffile))
18624 (progn (message "Failed to create pdf file from %s" texfile) nil)
18625 (condition-case nil
18626 (if (featurep 'xemacs)
18627 (call-process "convert" nil nil nil
18628 "-density" "96"
18629 "-trim"
18630 "-antialias"
18631 pdffile
18632 "-quality" "100"
18633 ;; "-sharpen" "0x1.0"
18634 pngfile)
18635 (call-process "convert" nil nil nil
18636 "-density" dpi
18637 "-trim"
18638 "-antialias"
18639 pdffile
18640 "-quality" "100"
18641 ;; "-sharpen" "0x1.0"
18642 pngfile))
18643 (error nil))
18644 (if (not (file-exists-p pngfile))
18645 (if org-format-latex-signal-error
18646 (error "Failed to create png file from %s" texfile)
18647 (message "Failed to create png file from %s" texfile)
18648 nil)
18649 ;; Use the requested file name and clean up
18650 (copy-file pngfile tofile 'replace)
18651 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18652 (if (file-exists-p (concat texfilebase e))
18653 (delete-file (concat texfilebase e))))
18654 pngfile))))
18656 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18657 "Fill a LaTeX header template TPL.
18658 In the template, the following place holders will be recognized:
18660 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18661 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18662 [PACKAGES] \\usepackage statements for PKG
18663 [NO-PACKAGES] do not include PKG
18664 [EXTRA] the string EXTRA
18665 [NO-EXTRA] do not include EXTRA
18667 For backward compatibility, if both the positive and the negative place
18668 holder is missing, the positive one (without the \"NO-\") will be
18669 assumed to be present at the end of the template.
18670 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18671 EXTRA is a string.
18672 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18673 (let (rpl (end ""))
18674 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18675 (setq rpl (if (or (match-end 1) (not def-pkg))
18676 "" (org-latex-packages-to-string def-pkg snippets-p t))
18677 tpl (replace-match rpl t t tpl))
18678 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18680 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18681 (setq rpl (if (or (match-end 1) (not pkg))
18682 "" (org-latex-packages-to-string pkg snippets-p t))
18683 tpl (replace-match rpl t t tpl))
18684 (if pkg (setq end
18685 (concat end "\n"
18686 (org-latex-packages-to-string pkg snippets-p)))))
18688 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18689 (setq rpl (if (or (match-end 1) (not extra))
18690 "" (concat extra "\n"))
18691 tpl (replace-match rpl t t tpl))
18692 (if (and extra (string-match "\\S-" extra))
18693 (setq end (concat end "\n" extra))))
18695 (if (string-match "\\S-" end)
18696 (concat tpl "\n" end)
18697 tpl)))
18699 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18700 "Turn an alist of packages into a string with the \\usepackage macros."
18701 (setq pkg (mapconcat (lambda(p)
18702 (cond
18703 ((stringp p) p)
18704 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18705 (format "%% Package %s omitted" (cadr p)))
18706 ((equal "" (car p))
18707 (format "\\usepackage{%s}" (cadr p)))
18709 (format "\\usepackage[%s]{%s}"
18710 (car p) (cadr p)))))
18712 "\n"))
18713 (if newline (concat pkg "\n") pkg))
18715 (defun org-dvipng-color (attr)
18716 "Return a RGB color specification for dvipng."
18717 (apply 'format "rgb %s %s %s"
18718 (mapcar 'org-normalize-color
18719 (if (featurep 'xemacs)
18720 (color-rgb-components
18721 (face-property 'default
18722 (cond ((eq attr :foreground) 'foreground)
18723 ((eq attr :background) 'background))))
18724 (color-values (face-attribute 'default attr nil))))))
18726 (defun org-dvipng-color-format (color-name)
18727 "Convert COLOR-NAME to a RGB color value for dvipng."
18728 (apply 'format "rgb %s %s %s"
18729 (mapcar 'org-normalize-color
18730 (color-values color-name))))
18732 (defun org-latex-color (attr)
18733 "Return a RGB color for the LaTeX color package."
18734 (apply 'format "%s,%s,%s"
18735 (mapcar 'org-normalize-color
18736 (if (featurep 'xemacs)
18737 (color-rgb-components
18738 (face-property 'default
18739 (cond ((eq attr :foreground) 'foreground)
18740 ((eq attr :background) 'background))))
18741 (color-values (face-attribute 'default attr nil))))))
18743 (defun org-latex-color-format (color-name)
18744 "Convert COLOR-NAME to a RGB color value."
18745 (apply 'format "%s,%s,%s"
18746 (mapcar 'org-normalize-color
18747 (color-values color-name))))
18749 (defun org-normalize-color (value)
18750 "Return string to be used as color value for an RGB component."
18751 (format "%g" (/ value 65535.0)))
18755 ;; Image display
18757 (defvar org-inline-image-overlays nil)
18758 (make-variable-buffer-local 'org-inline-image-overlays)
18760 (defun org-toggle-inline-images (&optional include-linked)
18761 "Toggle the display of inline images.
18762 INCLUDE-LINKED is passed to `org-display-inline-images'."
18763 (interactive "P")
18764 (if org-inline-image-overlays
18765 (progn
18766 (org-remove-inline-images)
18767 (message "Inline image display turned off"))
18768 (org-display-inline-images include-linked)
18769 (if (and (org-called-interactively-p)
18770 org-inline-image-overlays)
18771 (message "%d images displayed inline"
18772 (length org-inline-image-overlays))
18773 (message "No images to display inline"))))
18775 (defun org-redisplay-inline-images ()
18776 "Refresh the display of inline images."
18777 (interactive)
18778 (if (not org-inline-image-overlays)
18779 (org-toggle-inline-images)
18780 (org-toggle-inline-images)
18781 (org-toggle-inline-images)))
18783 (defun org-display-inline-images (&optional include-linked refresh beg end)
18784 "Display inline images.
18785 Normally only links without a description part are inlined, because this
18786 is how it will work for export. When INCLUDE-LINKED is set, also links
18787 with a description part will be inlined. This can be nice for a quick
18788 look at those images, but it does not reflect what exported files will look
18789 like.
18790 When REFRESH is set, refresh existing images between BEG and END.
18791 This will create new image displays only if necessary.
18792 BEG and END default to the buffer boundaries."
18793 (interactive "P")
18794 (when (display-graphic-p)
18795 (unless refresh
18796 (org-remove-inline-images)
18797 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18798 (save-excursion
18799 (save-restriction
18800 (widen)
18801 (setq beg (or beg (point-min)) end (or end (point-max)))
18802 (goto-char beg)
18803 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18804 (substring (org-image-file-name-regexp) 0 -2)
18805 "\\)\\]" (if include-linked "" "\\]")))
18806 (case-fold-search t)
18807 old file ov img type attrwidth width)
18808 (while (re-search-forward re end t)
18809 (setq old (get-char-property-and-overlay (match-beginning 1)
18810 'org-image-overlay)
18811 file (expand-file-name
18812 (concat (or (match-string 3) "") (match-string 4))))
18813 (when (image-type-available-p 'imagemagick)
18814 (setq attrwidth (if (or (listp org-image-actual-width)
18815 (null org-image-actual-width))
18816 (save-excursion
18817 (save-match-data
18818 (when (re-search-backward
18819 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18820 (save-excursion
18821 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18822 (string-to-number (match-string 1))))))
18823 width (cond ((eq org-image-actual-width t) nil)
18824 ((null org-image-actual-width) attrwidth)
18825 ((numberp org-image-actual-width)
18826 org-image-actual-width)
18827 ((listp org-image-actual-width)
18828 (or attrwidth (car org-image-actual-width))))
18829 type (if width 'imagemagick)))
18830 (when (file-exists-p file)
18831 (if (and (car-safe old) refresh)
18832 (image-refresh (overlay-get (cdr old) 'display))
18833 (setq img (save-match-data (create-image file type nil :width width)))
18834 (when img
18835 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18836 (overlay-put ov 'display img)
18837 (overlay-put ov 'face 'default)
18838 (overlay-put ov 'org-image-overlay t)
18839 (overlay-put ov 'modification-hooks
18840 (list 'org-display-inline-remove-overlay))
18841 (push ov org-inline-image-overlays))))))))))
18843 (define-obsolete-function-alias
18844 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18846 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18847 "Remove inline-display overlay if a corresponding region is modified."
18848 (let ((inhibit-modification-hooks t))
18849 (when (and ov after)
18850 (delete ov org-inline-image-overlays)
18851 (delete-overlay ov))))
18853 (defun org-remove-inline-images ()
18854 "Remove inline display of images."
18855 (interactive)
18856 (mapc 'delete-overlay org-inline-image-overlays)
18857 (setq org-inline-image-overlays nil))
18859 ;;;; Key bindings
18861 ;; Outline functions from `outline-mode-prefix-map'
18862 ;; that can be remapped in Org:
18863 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18864 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18865 (define-key org-mode-map [remap outline-forward-same-level]
18866 'org-forward-heading-same-level)
18867 (define-key org-mode-map [remap outline-backward-same-level]
18868 'org-backward-heading-same-level)
18869 (define-key org-mode-map [remap show-branches]
18870 'org-kill-note-or-show-branches)
18871 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18872 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18873 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18875 ;; Outline functions from `outline-mode-prefix-map' that can not
18876 ;; be remapped in Org:
18878 ;; - the column "key binding" shows whether the Outline function is still
18879 ;; available in Org mode on the same key that it has been bound to in
18880 ;; Outline mode:
18881 ;; - "overridden": key used for a different functionality in Org mode
18882 ;; - else: key still bound to the same Outline function in Org mode
18884 ;; | Outline function | key binding | Org replacement |
18885 ;; |------------------------------------+-------------+-----------------------|
18886 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18887 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18888 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18889 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18890 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18891 ;; | `show-entry' | overridden | no replacement |
18892 ;; | `show-children' | `C-c C-i' | visibility cycling |
18893 ;; | `show-branches' | `C-c C-k' | still same function |
18894 ;; | `show-subtree' | overridden | visibility cycling |
18895 ;; | `show-all' | overridden | no replacement |
18896 ;; | `hide-subtree' | overridden | visibility cycling |
18897 ;; | `hide-body' | overridden | no replacement |
18898 ;; | `hide-entry' | overridden | visibility cycling |
18899 ;; | `hide-leaves' | overridden | no replacement |
18900 ;; | `hide-sublevels' | overridden | no replacement |
18901 ;; | `hide-other' | overridden | no replacement |
18903 ;; Make `C-c C-x' a prefix key
18904 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18906 ;; TAB key with modifiers
18907 (org-defkey org-mode-map "\C-i" 'org-cycle)
18908 (org-defkey org-mode-map [(tab)] 'org-cycle)
18909 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18910 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18911 ;; The following line is necessary under Suse GNU/Linux
18912 (unless (featurep 'xemacs)
18913 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18914 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18915 (define-key org-mode-map [backtab] 'org-shifttab)
18917 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18918 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18919 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18921 ;; Cursor keys with modifiers
18922 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18923 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18924 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18925 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18927 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18928 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18929 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18930 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18932 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18933 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18934 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18935 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18937 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18938 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18939 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18940 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18942 ;; Babel keys
18943 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18944 (mapc (lambda (pair)
18945 (define-key org-babel-map (car pair) (cdr pair)))
18946 org-babel-key-bindings)
18948 ;;; Extra keys for tty access.
18949 ;; We only set them when really needed because otherwise the
18950 ;; menus don't show the simple keys
18952 (when (or org-use-extra-keys
18953 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18954 (not window-system))
18955 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18956 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18957 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18958 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18959 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18960 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18961 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18962 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18963 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18964 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18965 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18966 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18967 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18968 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18969 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18970 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18971 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18972 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18973 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18974 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18975 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18976 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18977 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18978 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18979 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18980 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18981 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18982 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18984 ;; All the other keys
18986 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18987 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18988 (if (boundp 'narrow-map)
18989 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18990 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18991 (if (boundp 'narrow-map)
18992 (org-defkey narrow-map "b" 'org-narrow-to-block)
18993 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18994 (if (boundp 'narrow-map)
18995 (org-defkey narrow-map "e" 'org-narrow-to-element)
18996 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18997 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18998 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18999 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19000 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19001 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19002 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19003 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19004 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19005 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19006 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19007 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19008 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19009 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19010 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19011 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19012 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19013 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19014 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19015 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19016 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19017 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19018 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19019 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19020 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19021 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19022 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19023 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19024 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19025 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19026 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19027 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19028 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19029 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19030 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19031 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19032 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19033 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19034 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19035 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19036 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19037 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19038 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19039 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19040 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19041 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19042 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19043 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19044 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19045 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19046 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19047 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19048 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19049 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19050 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19051 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19052 (org-defkey org-mode-map "\C-c^" 'org-sort)
19053 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19054 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19055 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19056 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19057 (org-defkey org-mode-map "\C-m" 'org-return)
19058 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19059 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19060 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19061 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19062 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19063 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19064 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19065 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19066 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19067 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19068 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19069 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19070 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19071 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19072 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19073 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19074 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19075 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19076 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19077 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19078 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19079 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19080 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19082 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19083 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19084 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19086 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19087 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19088 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19089 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19090 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19091 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19092 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19093 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19094 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19095 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19096 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19097 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19098 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19099 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19100 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19101 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19102 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19103 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19104 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19105 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19106 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19107 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19108 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19110 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19111 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19112 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19113 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19114 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19116 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19118 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19120 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19121 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19123 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19126 (when (featurep 'xemacs)
19127 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19130 (defconst org-speed-commands-default
19132 ("Outline Navigation")
19133 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19134 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19135 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19136 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19137 ("F" . org-next-block)
19138 ("B" . org-previous-block)
19139 ("u" . (org-speed-move-safe 'outline-up-heading))
19140 ("j" . org-goto)
19141 ("g" . (org-refile t))
19142 ("Outline Visibility")
19143 ("c" . org-cycle)
19144 ("C" . org-shifttab)
19145 (" " . org-display-outline-path)
19146 ("s" . org-narrow-to-subtree)
19147 ("=" . org-columns)
19148 ("Outline Structure Editing")
19149 ("U" . org-shiftmetaup)
19150 ("D" . org-shiftmetadown)
19151 ("r" . org-metaright)
19152 ("l" . org-metaleft)
19153 ("R" . org-shiftmetaright)
19154 ("L" . org-shiftmetaleft)
19155 ("i" . (progn (forward-char 1) (call-interactively
19156 'org-insert-heading-respect-content)))
19157 ("^" . org-sort)
19158 ("w" . org-refile)
19159 ("a" . org-archive-subtree-default-with-confirmation)
19160 ("@" . org-mark-subtree)
19161 ("#" . org-toggle-comment)
19162 ("Clock Commands")
19163 ("I" . org-clock-in)
19164 ("O" . org-clock-out)
19165 ("Meta Data Editing")
19166 ("t" . org-todo)
19167 ("," . (org-priority))
19168 ("0" . (org-priority ?\ ))
19169 ("1" . (org-priority ?A))
19170 ("2" . (org-priority ?B))
19171 ("3" . (org-priority ?C))
19172 (":" . org-set-tags-command)
19173 ("e" . org-set-effort)
19174 ("E" . org-inc-effort)
19175 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19176 (org-entry-put (point) "APPT_WARNTIME" m)))
19177 ("Agenda Views etc")
19178 ("v" . org-agenda)
19179 ("/" . org-sparse-tree)
19180 ("Misc")
19181 ("o" . org-open-at-point)
19182 ("?" . org-speed-command-help)
19183 ("<" . (org-agenda-set-restriction-lock 'subtree))
19184 (">" . (org-agenda-remove-restriction-lock))
19186 "The default speed commands.")
19188 (defun org-print-speed-command (e)
19189 (if (> (length (car e)) 1)
19190 (progn
19191 (princ "\n")
19192 (princ (car e))
19193 (princ "\n")
19194 (princ (make-string (length (car e)) ?-))
19195 (princ "\n"))
19196 (princ (car e))
19197 (princ " ")
19198 (if (symbolp (cdr e))
19199 (princ (symbol-name (cdr e)))
19200 (prin1 (cdr e)))
19201 (princ "\n")))
19203 (defun org-speed-command-help ()
19204 "Show the available speed commands."
19205 (interactive)
19206 (if (not org-use-speed-commands)
19207 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19208 (with-output-to-temp-buffer "*Help*"
19209 (princ "User-defined Speed commands\n===========================\n")
19210 (mapc 'org-print-speed-command org-speed-commands-user)
19211 (princ "\n")
19212 (princ "Built-in Speed commands\n=======================\n")
19213 (mapc 'org-print-speed-command org-speed-commands-default))
19214 (with-current-buffer "*Help*"
19215 (setq truncate-lines t))))
19217 (defun org-speed-move-safe (cmd)
19218 "Execute CMD, but make sure that the cursor always ends up in a headline.
19219 If not, return to the original position and throw an error."
19220 (interactive)
19221 (let ((pos (point)))
19222 (call-interactively cmd)
19223 (unless (and (bolp) (org-at-heading-p))
19224 (goto-char pos)
19225 (error "Boundary reached while executing %s" cmd))))
19227 (defvar org-self-insert-command-undo-counter 0)
19229 (defvar org-table-auto-blank-field) ; defined in org-table.el
19230 (defvar org-speed-command nil)
19232 (define-obsolete-function-alias
19233 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19235 (defun org-speed-command-activate (keys)
19236 "Hook for activating single-letter speed commands.
19237 `org-speed-commands-default' specifies a minimal command set.
19238 Use `org-speed-commands-user' for further customization."
19239 (when (or (and (bolp) (looking-at org-outline-regexp))
19240 (and (functionp org-use-speed-commands)
19241 (funcall org-use-speed-commands)))
19242 (cdr (assoc keys (append org-speed-commands-user
19243 org-speed-commands-default)))))
19245 (define-obsolete-function-alias
19246 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19248 (defun org-babel-speed-command-activate (keys)
19249 "Hook for activating single-letter code block commands."
19250 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19251 (cdr (assoc keys org-babel-key-bindings))))
19253 (defcustom org-speed-command-hook
19254 '(org-speed-command-default-hook org-babel-speed-command-hook)
19255 "Hook for activating speed commands at strategic locations.
19256 Hook functions are called in sequence until a valid handler is
19257 found.
19259 Each hook takes a single argument, a user-pressed command key
19260 which is also a `self-insert-command' from the global map.
19262 Within the hook, examine the cursor position and the command key
19263 and return nil or a valid handler as appropriate. Handler could
19264 be one of an interactive command, a function, or a form.
19266 Set `org-use-speed-commands' to non-nil value to enable this
19267 hook. The default setting is `org-speed-command-activate'."
19268 :group 'org-structure
19269 :version "24.1"
19270 :type 'hook)
19272 (defun org-self-insert-command (N)
19273 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19274 If the cursor is in a table looking at whitespace, the whitespace is
19275 overwritten, and the table is not marked as requiring realignment."
19276 (interactive "p")
19277 (org-check-before-invisible-edit 'insert)
19278 (cond
19279 ((and org-use-speed-commands
19280 (setq org-speed-command
19281 (run-hook-with-args-until-success
19282 'org-speed-command-hook (this-command-keys))))
19283 (cond
19284 ((commandp org-speed-command)
19285 (setq this-command org-speed-command)
19286 (call-interactively org-speed-command))
19287 ((functionp org-speed-command)
19288 (funcall org-speed-command))
19289 ((and org-speed-command (listp org-speed-command))
19290 (eval org-speed-command))
19291 (t (let (org-use-speed-commands)
19292 (call-interactively 'org-self-insert-command)))))
19293 ((and
19294 (org-table-p)
19295 (progn
19296 ;; check if we blank the field, and if that triggers align
19297 (and (featurep 'org-table) org-table-auto-blank-field
19298 (member last-command
19299 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19300 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19301 ;; got extra space, this field does not determine column width
19302 (let (org-table-may-need-update) (org-table-blank-field))
19303 ;; no extra space, this field may determine column width
19304 (org-table-blank-field)))
19306 (eq N 1)
19307 (looking-at "[^|\n]* |"))
19308 (let (org-table-may-need-update)
19309 (goto-char (1- (match-end 0)))
19310 (backward-delete-char 1)
19311 (goto-char (match-beginning 0))
19312 (self-insert-command N)))
19314 (setq org-table-may-need-update t)
19315 (self-insert-command N)
19316 (org-fix-tags-on-the-fly)
19317 (if org-self-insert-cluster-for-undo
19318 (if (not (eq last-command 'org-self-insert-command))
19319 (setq org-self-insert-command-undo-counter 1)
19320 (if (>= org-self-insert-command-undo-counter 20)
19321 (setq org-self-insert-command-undo-counter 1)
19322 (and (> org-self-insert-command-undo-counter 0)
19323 buffer-undo-list (listp buffer-undo-list)
19324 (not (cadr buffer-undo-list)) ; remove nil entry
19325 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19326 (setq org-self-insert-command-undo-counter
19327 (1+ org-self-insert-command-undo-counter))))))))
19329 (defun org-check-before-invisible-edit (kind)
19330 "Check is editing if kind KIND would be dangerous with invisible text around.
19331 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19332 ;; First, try to get out of here as quickly as possible, to reduce overhead
19333 (if (and org-catch-invisible-edits
19334 (or (not (boundp 'visible-mode)) (not visible-mode))
19335 (or (get-char-property (point) 'invisible)
19336 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19337 ;; OK, we need to take a closer look
19338 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19339 (invisible-before-point (if (bobp) nil (get-char-property
19340 (1- (point)) 'invisible)))
19341 (border-and-ok-direction
19343 ;; Check if we are acting predictably before invisible text
19344 (and invisible-at-point (not invisible-before-point)
19345 (memq kind '(insert delete-backward)))
19346 ;; Check if we are acting predictably after invisible text
19347 ;; This works not well, and I have turned it off. It seems
19348 ;; better to always show and stop after invisible text.
19349 ;; (and (not invisible-at-point) invisible-before-point
19350 ;; (memq kind '(insert delete)))
19352 (when (or (memq invisible-at-point '(outline org-hide-block t))
19353 (memq invisible-before-point '(outline org-hide-block t)))
19354 (if (eq org-catch-invisible-edits 'error)
19355 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19356 (if (and org-custom-properties-overlays
19357 (y-or-n-p "Display invisible properties in this buffer? "))
19358 (org-toggle-custom-properties-visibility)
19359 ;; Make the area visible
19360 (save-excursion
19361 (if invisible-before-point
19362 (goto-char (previous-single-char-property-change
19363 (point) 'invisible)))
19364 (org-cycle))
19365 (cond
19366 ((eq org-catch-invisible-edits 'show)
19367 ;; That's it, we do the edit after showing
19368 (message
19369 "Unfolding invisible region around point before editing")
19370 (sit-for 1))
19371 ((and (eq org-catch-invisible-edits 'smart)
19372 border-and-ok-direction)
19373 (message "Unfolding invisible region around point before editing"))
19375 ;; Don't do the edit, make the user repeat it in full visibility
19376 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19378 (defun org-fix-tags-on-the-fly ()
19379 (when (and (equal (char-after (point-at-bol)) ?*)
19380 (org-at-heading-p))
19381 (org-align-tags-here org-tags-column)))
19383 (defun org-delete-backward-char (N)
19384 "Like `delete-backward-char', insert whitespace at field end in tables.
19385 When deleting backwards, in tables this function will insert whitespace in
19386 front of the next \"|\" separator, to keep the table aligned. The table will
19387 still be marked for re-alignment if the field did fill the entire column,
19388 because, in this case the deletion might narrow the column."
19389 (interactive "p")
19390 (save-match-data
19391 (org-check-before-invisible-edit 'delete-backward)
19392 (if (and (org-table-p)
19393 (eq N 1)
19394 (string-match "|" (buffer-substring (point-at-bol) (point)))
19395 (looking-at ".*?|"))
19396 (let ((pos (point))
19397 (noalign (looking-at "[^|\n\r]* |"))
19398 (c org-table-may-need-update))
19399 (backward-delete-char N)
19400 (if (not overwrite-mode)
19401 (progn
19402 (skip-chars-forward "^|")
19403 (insert " ")
19404 (goto-char (1- pos))))
19405 ;; noalign: if there were two spaces at the end, this field
19406 ;; does not determine the width of the column.
19407 (if noalign (setq org-table-may-need-update c)))
19408 (backward-delete-char N)
19409 (org-fix-tags-on-the-fly))))
19411 (defun org-delete-char (N)
19412 "Like `delete-char', but insert whitespace at field end in tables.
19413 When deleting characters, in tables this function will insert whitespace in
19414 front of the next \"|\" separator, to keep the table aligned. The table will
19415 still be marked for re-alignment if the field did fill the entire column,
19416 because, in this case the deletion might narrow the column."
19417 (interactive "p")
19418 (save-match-data
19419 (org-check-before-invisible-edit 'delete)
19420 (if (and (org-table-p)
19421 (not (bolp))
19422 (not (= (char-after) ?|))
19423 (eq N 1))
19424 (if (looking-at ".*?|")
19425 (let ((pos (point))
19426 (noalign (looking-at "[^|\n\r]* |"))
19427 (c org-table-may-need-update))
19428 (replace-match
19429 (concat (substring (match-string 0) 1 -1) " |") nil t)
19430 (goto-char pos)
19431 ;; noalign: if there were two spaces at the end, this field
19432 ;; does not determine the width of the column.
19433 (if noalign (setq org-table-may-need-update c)))
19434 (delete-char N))
19435 (delete-char N)
19436 (org-fix-tags-on-the-fly))))
19438 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19439 (put 'org-self-insert-command 'delete-selection t)
19440 (put 'orgtbl-self-insert-command 'delete-selection t)
19441 (put 'org-delete-char 'delete-selection 'supersede)
19442 (put 'org-delete-backward-char 'delete-selection 'supersede)
19443 (put 'org-yank 'delete-selection 'yank)
19445 ;; Make `flyspell-mode' delay after some commands
19446 (put 'org-self-insert-command 'flyspell-delayed t)
19447 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19448 (put 'org-delete-char 'flyspell-delayed t)
19449 (put 'org-delete-backward-char 'flyspell-delayed t)
19451 ;; Make pabbrev-mode expand after org-mode commands
19452 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19453 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19455 ;; How to do this: Measure non-white length of current string
19456 ;; If equal to column width, we should realign.
19458 (defun org-remap (map &rest commands)
19459 "In MAP, remap the functions given in COMMANDS.
19460 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19461 (let (new old)
19462 (while commands
19463 (setq old (pop commands) new (pop commands))
19464 (if (fboundp 'command-remapping)
19465 (org-defkey map (vector 'remap old) new)
19466 (substitute-key-definition old new map global-map)))))
19468 (defun org-transpose-words ()
19469 "Transpose words for Org.
19470 This uses the `org-mode-transpose-word-syntax-table' syntax
19471 table, which interprets characters in `org-emphasis-alist' as
19472 word constituants."
19473 (interactive)
19474 (with-syntax-table org-mode-transpose-word-syntax-table
19475 (call-interactively 'transpose-words)))
19476 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19478 (when (eq org-enable-table-editor 'optimized)
19479 ;; If the user wants maximum table support, we need to hijack
19480 ;; some standard editing functions
19481 (org-remap org-mode-map
19482 'self-insert-command 'org-self-insert-command
19483 'delete-char 'org-delete-char
19484 'delete-backward-char 'org-delete-backward-char)
19485 (org-defkey org-mode-map "|" 'org-force-self-insert))
19487 (defvar org-ctrl-c-ctrl-c-hook nil
19488 "Hook for functions attaching themselves to `C-c C-c'.
19490 This can be used to add additional functionality to the C-c C-c
19491 key which executes context-dependent commands. This hook is run
19492 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19493 run after the last test.
19495 Each function will be called with no arguments. The function
19496 must check if the context is appropriate for it to act. If yes,
19497 it should do its thing and then return a non-nil value. If the
19498 context is wrong, just do nothing and return nil.")
19500 (defvar org-ctrl-c-ctrl-c-final-hook nil
19501 "Hook for functions attaching themselves to `C-c C-c'.
19503 This can be used to add additional functionality to the C-c C-c
19504 key which executes context-dependent commands. This hook is run
19505 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19506 before the first test.
19508 Each function will be called with no arguments. The function
19509 must check if the context is appropriate for it to act. If yes,
19510 it should do its thing and then return a non-nil value. If the
19511 context is wrong, just do nothing and return nil.")
19513 (defvar org-tab-first-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 as the first action when TAB is pressed, even before
19517 `org-cycle' messes around with the `outline-regexp' to cater for
19518 inline tasks and plain list item folding.
19519 If any function in this hook returns t, any other actions that
19520 would have been caused by TAB (such as table field motion or visibility
19521 cycling) will not occur.")
19523 (defvar org-tab-after-check-for-table-hook nil
19524 "Hook for functions to attach themselves to TAB.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.
19526 This hook runs after it has been established that the cursor is not in a
19527 table, but before checking if the cursor is in a headline or if global cycling
19528 should be done.
19529 If any function in this hook returns t, not other actions like visibility
19530 cycling will be done.")
19532 (defvar org-tab-after-check-for-cycling-hook nil
19533 "Hook for functions to attach themselves to TAB.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.
19535 This hook runs after it has been established that not table field motion and
19536 not visibility should be done because of current context. This is probably
19537 the place where a package like yasnippets can hook in.")
19539 (defvar org-tab-before-tab-emulation-hook nil
19540 "Hook for functions to attach themselves to TAB.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.
19542 This hook runs after every other options for TAB have been exhausted, but
19543 before indentation and \t insertion takes place.")
19545 (defvar org-metaleft-hook nil
19546 "Hook for functions attaching themselves to `M-left'.
19547 See `org-ctrl-c-ctrl-c-hook' for more information.")
19548 (defvar org-metaright-hook nil
19549 "Hook for functions attaching themselves to `M-right'.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-metaup-hook nil
19552 "Hook for functions attaching themselves to `M-up'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-metadown-hook nil
19555 "Hook for functions attaching themselves to `M-down'.
19556 See `org-ctrl-c-ctrl-c-hook' for more information.")
19557 (defvar org-shiftmetaleft-hook nil
19558 "Hook for functions attaching themselves to `M-S-left'.
19559 See `org-ctrl-c-ctrl-c-hook' for more information.")
19560 (defvar org-shiftmetaright-hook nil
19561 "Hook for functions attaching themselves to `M-S-right'.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19563 (defvar org-shiftmetaup-hook nil
19564 "Hook for functions attaching themselves to `M-S-up'.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-shiftmetadown-hook nil
19567 "Hook for functions attaching themselves to `M-S-down'.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-metareturn-hook nil
19570 "Hook for functions attaching themselves to `M-RET'.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-shiftup-hook nil
19573 "Hook for functions attaching themselves to `S-up'.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.")
19575 (defvar org-shiftup-final-hook nil
19576 "Hook for functions attaching themselves to `S-up'.
19577 This one runs after all other options except shift-select have been excluded.
19578 See `org-ctrl-c-ctrl-c-hook' for more information.")
19579 (defvar org-shiftdown-hook nil
19580 "Hook for functions attaching themselves to `S-down'.
19581 See `org-ctrl-c-ctrl-c-hook' for more information.")
19582 (defvar org-shiftdown-final-hook nil
19583 "Hook for functions attaching themselves to `S-down'.
19584 This one runs after all other options except shift-select have been excluded.
19585 See `org-ctrl-c-ctrl-c-hook' for more information.")
19586 (defvar org-shiftleft-hook nil
19587 "Hook for functions attaching themselves to `S-left'.
19588 See `org-ctrl-c-ctrl-c-hook' for more information.")
19589 (defvar org-shiftleft-final-hook nil
19590 "Hook for functions attaching themselves to `S-left'.
19591 This one runs after all other options except shift-select have been excluded.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.")
19593 (defvar org-shiftright-hook nil
19594 "Hook for functions attaching themselves to `S-right'.
19595 See `org-ctrl-c-ctrl-c-hook' for more information.")
19596 (defvar org-shiftright-final-hook nil
19597 "Hook for functions attaching themselves to `S-right'.
19598 This one runs after all other options except shift-select have been excluded.
19599 See `org-ctrl-c-ctrl-c-hook' for more information.")
19601 (defun org-modifier-cursor-error ()
19602 "Throw an error, a modified cursor command was applied in wrong context."
19603 (user-error "This command is active in special context like tables, headlines or items"))
19605 (defun org-shiftselect-error ()
19606 "Throw an error because Shift-Cursor command was applied in wrong context."
19607 (if (and (boundp 'shift-select-mode) shift-select-mode)
19608 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19609 (user-error "This command works only in special context like headlines or timestamps")))
19611 (defun org-call-for-shift-select (cmd)
19612 (let ((this-command-keys-shift-translated t))
19613 (call-interactively cmd)))
19615 (defun org-shifttab (&optional arg)
19616 "Global visibility cycling or move to previous table field.
19617 Call `org-table-previous-field' within a table.
19618 When ARG is nil, cycle globally through visibility states.
19619 When ARG is a numeric prefix, show contents of this level."
19620 (interactive "P")
19621 (cond
19622 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19623 ((integerp arg)
19624 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19625 (message "Content view to level: %d" arg)
19626 (org-content (prefix-numeric-value arg2))
19627 (org-cycle-show-empty-lines t)
19628 (setq org-cycle-global-status 'overview)))
19629 (t (call-interactively 'org-global-cycle))))
19631 (defun org-shiftmetaleft ()
19632 "Promote subtree or delete table column.
19633 Calls `org-promote-subtree', `org-outdent-item-tree', or
19634 `org-table-delete-column', depending on context. See the
19635 individual commands for more information."
19636 (interactive)
19637 (cond
19638 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19639 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19640 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19641 ((if (not (org-region-active-p)) (org-at-item-p)
19642 (save-excursion (goto-char (region-beginning))
19643 (org-at-item-p)))
19644 (call-interactively 'org-outdent-item-tree))
19645 (t (org-modifier-cursor-error))))
19647 (defun org-shiftmetaright ()
19648 "Demote subtree or insert table column.
19649 Calls `org-demote-subtree', `org-indent-item-tree', or
19650 `org-table-insert-column', depending on context. See the
19651 individual commands for more information."
19652 (interactive)
19653 (cond
19654 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19655 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19656 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19657 ((if (not (org-region-active-p)) (org-at-item-p)
19658 (save-excursion (goto-char (region-beginning))
19659 (org-at-item-p)))
19660 (call-interactively 'org-indent-item-tree))
19661 (t (org-modifier-cursor-error))))
19663 (defun org-shiftmetaup (&optional arg)
19664 "Move subtree up or kill table row.
19665 Calls `org-move-subtree-up' or `org-table-kill-row' or
19666 `org-move-item-up' or `org-timestamp-up', depending on context.
19667 See the individual commands for more information."
19668 (interactive "P")
19669 (cond
19670 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19671 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19672 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19673 ((org-at-item-p) (call-interactively 'org-move-item-up))
19674 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19675 (call-interactively 'org-timestamp-up)))
19676 (t (call-interactively 'org-drag-line-backward))))
19678 (defun org-shiftmetadown (&optional arg)
19679 "Move subtree down or insert table row.
19680 Calls `org-move-subtree-down' or `org-table-insert-row' or
19681 `org-move-item-down' or `org-timestamp-up', depending on context.
19682 See the individual commands for more information."
19683 (interactive "P")
19684 (cond
19685 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19686 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19687 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19688 ((org-at-item-p) (call-interactively 'org-move-item-down))
19689 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19690 (call-interactively 'org-timestamp-down)))
19691 (t (call-interactively 'org-drag-line-forward))))
19693 (defsubst org-hidden-tree-error ()
19694 (user-error
19695 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19697 (defun org-metaleft (&optional arg)
19698 "Promote heading or move table column to left.
19699 Calls `org-do-promote' or `org-table-move-column', depending on context.
19700 With no specific context, calls the Emacs default `backward-word'.
19701 See the individual commands for more information."
19702 (interactive "P")
19703 (cond
19704 ((run-hook-with-args-until-success 'org-metaleft-hook))
19705 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19706 ((org-with-limited-levels
19707 (or (org-at-heading-p)
19708 (and (org-region-active-p)
19709 (save-excursion
19710 (goto-char (region-beginning))
19711 (org-at-heading-p)))))
19712 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19713 (call-interactively 'org-do-promote))
19714 ;; At an inline task.
19715 ((org-at-heading-p)
19716 (call-interactively 'org-inlinetask-promote))
19717 ((or (org-at-item-p)
19718 (and (org-region-active-p)
19719 (save-excursion
19720 (goto-char (region-beginning))
19721 (org-at-item-p))))
19722 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19723 (call-interactively 'org-outdent-item))
19724 (t (call-interactively 'backward-word))))
19726 (defun org-metaright (&optional arg)
19727 "Demote a subtree, a list item or move table column to right.
19728 In front of a drawer or a block keyword, indent it correctly.
19729 With no specific context, calls the Emacs default `forward-word'.
19730 See the individual commands for more information."
19731 (interactive "P")
19732 (cond
19733 ((run-hook-with-args-until-success 'org-metaright-hook))
19734 ((org-at-table-p) (call-interactively 'org-table-move-column))
19735 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19736 ((org-at-block-p) (call-interactively 'org-indent-block))
19737 ((org-with-limited-levels
19738 (or (org-at-heading-p)
19739 (and (org-region-active-p)
19740 (save-excursion
19741 (goto-char (region-beginning))
19742 (org-at-heading-p)))))
19743 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19744 (call-interactively 'org-do-demote))
19745 ;; At an inline task.
19746 ((org-at-heading-p)
19747 (call-interactively 'org-inlinetask-demote))
19748 ((or (org-at-item-p)
19749 (and (org-region-active-p)
19750 (save-excursion
19751 (goto-char (region-beginning))
19752 (org-at-item-p))))
19753 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19754 (call-interactively 'org-indent-item))
19755 (t (call-interactively 'forward-word))))
19757 (defun org-check-for-hidden (what)
19758 "Check if there are hidden headlines/items in the current visual line.
19759 WHAT can be either `headlines' or `items'. If the current line is
19760 an outline or item heading and it has a folded subtree below it,
19761 this function returns t, nil otherwise."
19762 (let ((re (cond
19763 ((eq what 'headlines) org-outline-regexp-bol)
19764 ((eq what 'items) (org-item-beginning-re))
19765 (t (error "This should not happen"))))
19766 beg end)
19767 (save-excursion
19768 (catch 'exit
19769 (unless (org-region-active-p)
19770 (setq beg (point-at-bol))
19771 (beginning-of-line 2)
19772 (while (and (not (eobp)) ;; this is like `next-line'
19773 (get-char-property (1- (point)) 'invisible))
19774 (beginning-of-line 2))
19775 (setq end (point))
19776 (goto-char beg)
19777 (goto-char (point-at-eol))
19778 (setq end (max end (point)))
19779 (while (re-search-forward re end t)
19780 (if (get-char-property (match-beginning 0) 'invisible)
19781 (throw 'exit t))))
19782 nil))))
19784 (defun org-metaup (&optional arg)
19785 "Move subtree up or move table row up.
19786 Calls `org-move-subtree-up' or `org-table-move-row' or
19787 `org-move-item-up', depending on context. See the individual commands
19788 for more information."
19789 (interactive "P")
19790 (cond
19791 ((run-hook-with-args-until-success 'org-metaup-hook))
19792 ((org-region-active-p)
19793 (let* ((a (min (region-beginning) (region-end)))
19794 (b (1- (max (region-beginning) (region-end))))
19795 (c (save-excursion (goto-char a)
19796 (move-beginning-of-line 0)))
19797 (d (save-excursion (goto-char a)
19798 (move-end-of-line 0) (point))))
19799 (transpose-regions a b c d)
19800 (goto-char c)))
19801 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19802 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19803 ((org-at-item-p) (call-interactively 'org-move-item-up))
19804 (t (org-drag-element-backward))))
19806 (defun org-metadown (&optional arg)
19807 "Move subtree down or move table row down.
19808 Calls `org-move-subtree-down' or `org-table-move-row' or
19809 `org-move-item-down', depending on context. See the individual
19810 commands for more information."
19811 (interactive "P")
19812 (cond
19813 ((run-hook-with-args-until-success 'org-metadown-hook))
19814 ((org-region-active-p)
19815 (let* ((a (min (region-beginning) (region-end)))
19816 (b (max (region-beginning) (region-end)))
19817 (c (save-excursion (goto-char b)
19818 (move-beginning-of-line 1)))
19819 (d (save-excursion (goto-char b)
19820 (move-end-of-line 1) (1+ (point)))))
19821 (transpose-regions a b c d)
19822 (goto-char d)))
19823 ((org-at-table-p) (call-interactively 'org-table-move-row))
19824 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19825 ((org-at-item-p) (call-interactively 'org-move-item-down))
19826 (t (org-drag-element-forward))))
19828 (defun org-shiftup (&optional arg)
19829 "Increase item in timestamp or increase priority of current headline.
19830 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19831 depending on context. See the individual commands for more information."
19832 (interactive "P")
19833 (cond
19834 ((run-hook-with-args-until-success 'org-shiftup-hook))
19835 ((and org-support-shift-select (org-region-active-p))
19836 (org-call-for-shift-select 'previous-line))
19837 ((org-at-timestamp-p t)
19838 (call-interactively (if org-edit-timestamp-down-means-later
19839 'org-timestamp-down 'org-timestamp-up)))
19840 ((and (not (eq org-support-shift-select 'always))
19841 org-enable-priority-commands
19842 (org-at-heading-p))
19843 (call-interactively 'org-priority-up))
19844 ((and (not org-support-shift-select) (org-at-item-p))
19845 (call-interactively 'org-previous-item))
19846 ((org-clocktable-try-shift 'up arg))
19847 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19848 (org-support-shift-select
19849 (org-call-for-shift-select 'previous-line))
19850 (t (org-shiftselect-error))))
19852 (defun org-shiftdown (&optional arg)
19853 "Decrease item in timestamp or decrease priority of current headline.
19854 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19855 depending on context. See the individual commands for more information."
19856 (interactive "P")
19857 (cond
19858 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19859 ((and org-support-shift-select (org-region-active-p))
19860 (org-call-for-shift-select 'next-line))
19861 ((org-at-timestamp-p t)
19862 (call-interactively (if org-edit-timestamp-down-means-later
19863 'org-timestamp-up 'org-timestamp-down)))
19864 ((and (not (eq org-support-shift-select 'always))
19865 org-enable-priority-commands
19866 (org-at-heading-p))
19867 (call-interactively 'org-priority-down))
19868 ((and (not org-support-shift-select) (org-at-item-p))
19869 (call-interactively 'org-next-item))
19870 ((org-clocktable-try-shift 'down arg))
19871 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19872 (org-support-shift-select
19873 (org-call-for-shift-select 'next-line))
19874 (t (org-shiftselect-error))))
19876 (defun org-shiftright (&optional arg)
19877 "Cycle the thing at point or in the current line, depending on context.
19878 Depending on context, this does one of the following:
19880 - switch a timestamp at point one day into the future
19881 - on a headline, switch to the next TODO keyword.
19882 - on an item, switch entire list to the next bullet type
19883 - on a property line, switch to the next allowed value
19884 - on a clocktable definition line, move time block into the future"
19885 (interactive "P")
19886 (cond
19887 ((run-hook-with-args-until-success 'org-shiftright-hook))
19888 ((and org-support-shift-select (org-region-active-p))
19889 (org-call-for-shift-select 'forward-char))
19890 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19891 ((and (not (eq org-support-shift-select 'always))
19892 (org-at-heading-p))
19893 (let ((org-inhibit-logging
19894 (not org-treat-S-cursor-todo-selection-as-state-change))
19895 (org-inhibit-blocking
19896 (not org-treat-S-cursor-todo-selection-as-state-change)))
19897 (org-call-with-arg 'org-todo 'right)))
19898 ((or (and org-support-shift-select
19899 (not (eq org-support-shift-select 'always))
19900 (org-at-item-bullet-p))
19901 (and (not org-support-shift-select) (org-at-item-p)))
19902 (org-call-with-arg 'org-cycle-list-bullet nil))
19903 ((and (not (eq org-support-shift-select 'always))
19904 (org-at-property-p))
19905 (call-interactively 'org-property-next-allowed-value))
19906 ((org-clocktable-try-shift 'right arg))
19907 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19908 (org-support-shift-select
19909 (org-call-for-shift-select 'forward-char))
19910 (t (org-shiftselect-error))))
19912 (defun org-shiftleft (&optional arg)
19913 "Cycle the thing at point or in the current line, depending on context.
19914 Depending on context, this does one of the following:
19916 - switch a timestamp at point one day into the past
19917 - on a headline, switch to the previous TODO keyword.
19918 - on an item, switch entire list to the previous bullet type
19919 - on a property line, switch to the previous allowed value
19920 - on a clocktable definition line, move time block into the past"
19921 (interactive "P")
19922 (cond
19923 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19924 ((and org-support-shift-select (org-region-active-p))
19925 (org-call-for-shift-select 'backward-char))
19926 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19927 ((and (not (eq org-support-shift-select 'always))
19928 (org-at-heading-p))
19929 (let ((org-inhibit-logging
19930 (not org-treat-S-cursor-todo-selection-as-state-change))
19931 (org-inhibit-blocking
19932 (not org-treat-S-cursor-todo-selection-as-state-change)))
19933 (org-call-with-arg 'org-todo 'left)))
19934 ((or (and org-support-shift-select
19935 (not (eq org-support-shift-select 'always))
19936 (org-at-item-bullet-p))
19937 (and (not org-support-shift-select) (org-at-item-p)))
19938 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19939 ((and (not (eq org-support-shift-select 'always))
19940 (org-at-property-p))
19941 (call-interactively 'org-property-previous-allowed-value))
19942 ((org-clocktable-try-shift 'left arg))
19943 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19944 (org-support-shift-select
19945 (org-call-for-shift-select 'backward-char))
19946 (t (org-shiftselect-error))))
19948 (defun org-shiftcontrolright ()
19949 "Switch to next TODO set."
19950 (interactive)
19951 (cond
19952 ((and org-support-shift-select (org-region-active-p))
19953 (org-call-for-shift-select 'forward-word))
19954 ((and (not (eq org-support-shift-select 'always))
19955 (org-at-heading-p))
19956 (org-call-with-arg 'org-todo 'nextset))
19957 (org-support-shift-select
19958 (org-call-for-shift-select 'forward-word))
19959 (t (org-shiftselect-error))))
19961 (defun org-shiftcontrolleft ()
19962 "Switch to previous TODO set."
19963 (interactive)
19964 (cond
19965 ((and org-support-shift-select (org-region-active-p))
19966 (org-call-for-shift-select 'backward-word))
19967 ((and (not (eq org-support-shift-select 'always))
19968 (org-at-heading-p))
19969 (org-call-with-arg 'org-todo 'previousset))
19970 (org-support-shift-select
19971 (org-call-for-shift-select 'backward-word))
19972 (t (org-shiftselect-error))))
19974 (defun org-shiftcontrolup (&optional n)
19975 "Change timestamps synchronously up in CLOCK log lines.
19976 Optional argument N tells to change by that many units."
19977 (interactive "P")
19978 (cond ((and (not org-support-shift-select)
19979 (org-at-clock-log-p)
19980 (org-at-timestamp-p t))
19981 (org-clock-timestamps-up n))
19982 (t (org-shiftselect-error))))
19984 (defun org-shiftcontroldown (&optional n)
19985 "Change timestamps synchronously down in CLOCK log lines.
19986 Optional argument N tells to change by that many units."
19987 (interactive "P")
19988 (cond ((and (not org-support-shift-select)
19989 (org-at-clock-log-p)
19990 (org-at-timestamp-p t))
19991 (org-clock-timestamps-down n))
19992 (t (org-shiftselect-error))))
19994 (defun org-ctrl-c-ret ()
19995 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19996 (interactive)
19997 (cond
19998 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19999 (t (call-interactively 'org-insert-heading))))
20001 (defun org-find-visible ()
20002 (let ((s (point)))
20003 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20004 (get-char-property s 'invisible)))
20006 (defun org-find-invisible ()
20007 (let ((s (point)))
20008 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20009 (not (get-char-property s 'invisible))))
20012 (defun org-copy-visible (beg end)
20013 "Copy the visible parts of the region."
20014 (interactive "r")
20015 (let (snippets s)
20016 (save-excursion
20017 (save-restriction
20018 (narrow-to-region beg end)
20019 (setq s (goto-char (point-min)))
20020 (while (not (= (point) (point-max)))
20021 (goto-char (org-find-invisible))
20022 (push (buffer-substring s (point)) snippets)
20023 (setq s (goto-char (org-find-visible))))))
20024 (kill-new (apply 'concat (nreverse snippets)))))
20026 (defun org-copy-special ()
20027 "Copy region in table or copy current subtree.
20028 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20029 See the individual commands for more information."
20030 (interactive)
20031 (call-interactively
20032 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20034 (defun org-cut-special ()
20035 "Cut region in table or cut current subtree.
20036 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20037 See the individual commands for more information."
20038 (interactive)
20039 (call-interactively
20040 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20042 (defun org-paste-special (arg)
20043 "Paste rectangular region into table, or past subtree relative to level.
20044 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20045 See the individual commands for more information."
20046 (interactive "P")
20047 (if (org-at-table-p)
20048 (org-table-paste-rectangle)
20049 (org-paste-subtree arg)))
20051 (defsubst org-in-fixed-width-region-p ()
20052 "Is point in a fixed-width region?"
20053 (save-match-data
20054 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20056 (defun org-edit-special (&optional arg)
20057 "Call a special editor for the element at point.
20058 When at a table, call the formula editor with `org-table-edit-formulas'.
20059 When in a source code block, call `org-edit-src-code'.
20060 When in a fixed-width region, call `org-edit-fixed-width-region'.
20061 When at an #+INCLUDE keyword, visit the included file.
20062 On a link, call `ffap' to visit the link at point.
20063 Otherwise, return a user error."
20064 (interactive "P")
20065 (let ((element (org-element-at-point)))
20066 (assert (not buffer-read-only) nil
20067 "Buffer is read-only: %s" (buffer-name))
20068 (case (org-element-type element)
20069 (src-block
20070 (if (not arg) (org-edit-src-code)
20071 (let* ((info (org-babel-get-src-block-info))
20072 (lang (nth 0 info))
20073 (params (nth 2 info))
20074 (session (cdr (assq :session params))))
20075 (if (not session) (org-edit-src-code)
20076 ;; At a src-block with a session and function called with
20077 ;; an ARG: switch to the buffer related to the inferior
20078 ;; process.
20079 (switch-to-buffer
20080 (funcall (intern (concat "org-babel-prep-session:" lang))
20081 session params))))))
20082 (keyword
20083 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20084 (find-file
20085 (org-remove-double-quotes
20086 (car (org-split-string (org-element-property :value element)))))
20087 (user-error "No special environment to edit here")))
20088 (table
20089 (if (eq (org-element-property :type element) 'table.el)
20090 (org-edit-src-code)
20091 (call-interactively 'org-table-edit-formulas)))
20092 ;; Only Org tables contain `table-row' type elements.
20093 (table-row (call-interactively 'org-table-edit-formulas))
20094 ((example-block export-block) (org-edit-src-code))
20095 (fixed-width (org-edit-fixed-width-region))
20096 (otherwise
20097 ;; No notable element at point. Though, we may be at a link,
20098 ;; which is an object. Thus, scan deeper.
20099 (if (eq (org-element-type (org-element-context element)) 'link)
20100 (call-interactively 'ffap)
20101 (user-error "No special environment to edit here"))))))
20103 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20104 (defun org-ctrl-c-ctrl-c (&optional arg)
20105 "Set tags in headline, or update according to changed information at point.
20107 This command does many different things, depending on context:
20109 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20110 this is what we do.
20112 - If the cursor is on a statistics cookie, update it.
20114 - If the cursor is in a headline, prompt for tags and insert them
20115 into the current line, aligned to `org-tags-column'. When called
20116 with prefix arg, realign all tags in the current buffer.
20118 - If the cursor is in one of the special #+KEYWORD lines, this
20119 triggers scanning the buffer for these lines and updating the
20120 information.
20122 - If the cursor is inside a table, realign the table. This command
20123 works even if the automatic table editor has been turned off.
20125 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20126 the entire table.
20128 - If the cursor is at a footnote reference or definition, jump to
20129 the corresponding definition or references, respectively.
20131 - If the cursor is a the beginning of a dynamic block, update it.
20133 - If the current buffer is a capture buffer, close note and file it.
20135 - If the cursor is on a <<<target>>>, update radio targets and
20136 corresponding links in this buffer.
20138 - If the cursor is on a numbered item in a plain list, renumber the
20139 ordered list.
20141 - If the cursor is on a checkbox, toggle it.
20143 - If the cursor is on a code block, evaluate it. The variable
20144 `org-confirm-babel-evaluate' can be used to control prompting
20145 before code block evaluation, by default every code block
20146 evaluation requires confirmation. Code block evaluation can be
20147 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20148 (interactive "P")
20149 (cond
20150 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20151 org-occur-highlights
20152 org-latex-fragment-image-overlays)
20153 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20154 (org-remove-occur-highlights)
20155 (org-remove-latex-fragment-image-overlays)
20156 (message "Temporary highlights/overlays removed from current buffer"))
20157 ((and (local-variable-p 'org-finish-function (current-buffer))
20158 (fboundp org-finish-function))
20159 (funcall org-finish-function))
20160 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20162 (let* ((context (org-element-context)) (type (org-element-type context)))
20163 ;; Test if point is within a blank line.
20164 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20165 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20166 (user-error "C-c C-c can do nothing useful at this location"))
20167 ;; For convenience: at the first line of a paragraph on the
20168 ;; same line as an item, apply function on that item instead.
20169 (when (eq type 'paragraph)
20170 (let ((parent (org-element-property :parent context)))
20171 (when (and (eq (org-element-type parent) 'item)
20172 (= (point-at-bol) (org-element-property :begin parent)))
20173 (setq context parent type 'item))))
20174 ;; Act according to type of element or object at point.
20175 (case type
20176 (clock (org-clock-update-time-maybe))
20177 (dynamic-block
20178 (save-excursion
20179 (goto-char (org-element-property :post-affiliated context))
20180 (org-update-dblock)))
20181 (footnote-definition
20182 (goto-char (org-element-property :post-affiliated context))
20183 (call-interactively 'org-footnote-action))
20184 (footnote-reference (call-interactively 'org-footnote-action))
20185 ((headline inlinetask)
20186 (save-excursion (goto-char (org-element-property :begin context))
20187 (call-interactively 'org-set-tags)))
20188 (item
20189 ;; At an item: a double C-u set checkbox to "[-]"
20190 ;; unconditionally, whereas a single one will toggle its
20191 ;; presence. Without an universal argument, if the item
20192 ;; has a checkbox, toggle it. Otherwise repair the list.
20193 (let* ((box (org-element-property :checkbox context))
20194 (struct (org-element-property :structure context))
20195 (old-struct (copy-tree struct))
20196 (parents (org-list-parents-alist struct))
20197 (prevs (org-list-prevs-alist struct))
20198 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20199 (org-list-set-checkbox
20200 (org-element-property :begin context) struct
20201 (cond ((equal arg '(16)) "[-]")
20202 ((and (not box) (equal arg '(4))) "[ ]")
20203 ((or (not box) (equal arg '(4))) nil)
20204 ((eq box 'on) "[ ]")
20205 (t "[X]")))
20206 ;; Mimic `org-list-write-struct' but with grabbing
20207 ;; a return value from `org-list-struct-fix-box'.
20208 (org-list-struct-fix-ind struct parents 2)
20209 (org-list-struct-fix-item-end struct)
20210 (org-list-struct-fix-bul struct prevs)
20211 (org-list-struct-fix-ind struct parents)
20212 (let ((block-item
20213 (org-list-struct-fix-box struct parents prevs orderedp)))
20214 (if (and box (equal struct old-struct))
20215 (if (equal arg '(16))
20216 (message "Checkboxes already reset")
20217 (user-error "Cannot toggle this checkbox: %s"
20218 (if (eq box 'on)
20219 "all subitems checked"
20220 "unchecked subitems")))
20221 (org-list-struct-apply-struct struct old-struct)
20222 (org-update-checkbox-count-maybe))
20223 (when block-item
20224 (message "Checkboxes were removed due to empty box at line %d"
20225 (org-current-line block-item))))))
20226 (keyword
20227 (let ((org-inhibit-startup-visibility-stuff t)
20228 (org-startup-align-all-tables nil))
20229 (when (boundp 'org-table-coordinate-overlays)
20230 (mapc 'delete-overlay org-table-coordinate-overlays)
20231 (setq org-table-coordinate-overlays nil))
20232 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20233 (message "Local setup has been refreshed"))
20234 (plain-list
20235 ;; At a plain list, with a double C-u argument, set
20236 ;; checkboxes of each item to "[-]", whereas a single one
20237 ;; will toggle their presence according to the state of the
20238 ;; first item in the list. Without an argument, repair the
20239 ;; list.
20240 (let* ((begin (org-element-property :contents-begin context))
20241 (beginm (move-marker (make-marker) begin))
20242 (struct (org-element-property :structure context))
20243 (old-struct (copy-tree struct))
20244 (first-box (save-excursion
20245 (goto-char begin)
20246 (looking-at org-list-full-item-re)
20247 (match-string-no-properties 3)))
20248 (new-box (cond ((equal arg '(16)) "[-]")
20249 ((equal arg '(4)) (unless first-box "[ ]"))
20250 ((equal first-box "[X]") "[ ]")
20251 (t "[X]"))))
20252 (cond
20253 (arg
20254 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20255 (org-list-get-all-items
20256 begin struct (org-list-prevs-alist struct))))
20257 ((and first-box (eq (point) begin))
20258 ;; For convenience, when point is at bol on the first
20259 ;; item of the list and no argument is provided, simply
20260 ;; toggle checkbox of that item, if any.
20261 (org-list-set-checkbox begin struct new-box)))
20262 (org-list-write-struct
20263 struct (org-list-parents-alist struct) old-struct)
20264 (org-update-checkbox-count-maybe)
20265 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20266 ((property-drawer node-property)
20267 (call-interactively 'org-property-action))
20268 ((radio-target target)
20269 (call-interactively 'org-update-radio-target-regexp))
20270 (statistics-cookie
20271 (call-interactively 'org-update-statistics-cookies))
20272 ((table table-cell table-row)
20273 ;; At a table, recalculate every field and align it. Also
20274 ;; send the table if necessary. If the table has
20275 ;; a `table.el' type, just give up. At a table row or
20276 ;; cell, maybe recalculate line but always align table.
20277 (if (eq (org-element-property :type context) 'table.el)
20278 (message "Use C-c ' to edit table.el tables")
20279 (let ((org-enable-table-editor t))
20280 (if (or (eq type 'table)
20281 ;; Check if point is at a TBLFM line.
20282 (and (eq type 'table-row)
20283 (= (point) (org-element-property :end context))))
20284 (save-excursion
20285 (if (org-at-TBLFM-p)
20286 (progn (require 'org-table)
20287 (org-table-calc-current-TBLFM))
20288 (goto-char (org-element-property :contents-begin context))
20289 (org-call-with-arg 'org-table-recalculate (or arg t))
20290 (orgtbl-send-table 'maybe)))
20291 (org-table-maybe-eval-formula)
20292 (cond (arg (call-interactively 'org-table-recalculate))
20293 ((org-table-maybe-recalculate-line))
20294 (t (org-table-align)))))))
20295 (timestamp (org-timestamp-change 0 'day))
20296 (otherwise
20297 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20298 (user-error
20299 "C-c C-c can do nothing useful at this location")))))))))
20301 (defun org-mode-restart ()
20302 "Restart Org-mode, to scan again for special lines.
20303 Also updates the keyword regular expressions."
20304 (interactive)
20305 (org-mode)
20306 (message "Org-mode restarted"))
20308 (defun org-kill-note-or-show-branches ()
20309 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20310 (interactive)
20311 (if (not org-finish-function)
20312 (progn
20313 (hide-subtree)
20314 (call-interactively 'show-branches))
20315 (let ((org-note-abort t))
20316 (funcall org-finish-function))))
20318 (defun org-open-line (n)
20319 "Insert a new row in tables, call `open-line' elsewhere."
20320 (interactive "*p")
20321 (if (org-at-table-p)
20322 (org-table-insert-row)
20323 (open-line n)))
20325 (defun org-return (&optional indent)
20326 "Goto next table row or insert a newline.
20327 Calls `org-table-next-row' or `newline', depending on context.
20328 See the individual commands for more information."
20329 (interactive)
20330 (let (org-ts-what)
20331 (cond
20332 ((or (bobp) (org-in-src-block-p))
20333 (if indent (newline-and-indent) (newline)))
20334 ((org-at-table-p)
20335 (org-table-justify-field-maybe)
20336 (call-interactively 'org-table-next-row))
20337 ;; when `newline-and-indent' is called within a list, make sure
20338 ;; text moved stays inside the item.
20339 ((and (org-in-item-p) indent)
20340 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20341 (progn
20342 (save-match-data (newline))
20343 (org-indent-line-to (length (match-string 0))))
20344 (let ((ind (org-get-indentation)))
20345 (newline)
20346 (if (org-looking-back org-list-end-re)
20347 (org-indent-line)
20348 (org-indent-line-to ind)))))
20349 ((and org-return-follows-link
20350 (org-at-timestamp-p t)
20351 (not (eq org-ts-what 'after)))
20352 (org-follow-timestamp-link))
20353 ((and org-return-follows-link
20354 (let ((tprop (get-text-property (point) 'face)))
20355 (or (eq tprop 'org-link)
20356 (and (listp tprop) (memq 'org-link tprop)))))
20357 (call-interactively 'org-open-at-point))
20358 ((and (org-at-heading-p)
20359 (looking-at
20360 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20361 (org-show-entry)
20362 (end-of-line 1)
20363 (newline))
20364 (t (if indent (newline-and-indent) (newline))))))
20366 (defun org-return-indent ()
20367 "Goto next table row or insert a newline and indent.
20368 Calls `org-table-next-row' or `newline-and-indent', depending on
20369 context. See the individual commands for more information."
20370 (interactive)
20371 (org-return t))
20373 (defun org-ctrl-c-star ()
20374 "Compute table, or change heading status of lines.
20375 Calls `org-table-recalculate' or `org-toggle-heading',
20376 depending on context."
20377 (interactive)
20378 (cond
20379 ((org-at-table-p)
20380 (call-interactively 'org-table-recalculate))
20382 ;; Convert all lines in region to list items
20383 (call-interactively 'org-toggle-heading))))
20385 (defun org-ctrl-c-minus ()
20386 "Insert separator line in table or modify bullet status of line.
20387 Also turns a plain line or a region of lines into list items.
20388 Calls `org-table-insert-hline', `org-toggle-item', or
20389 `org-cycle-list-bullet', depending on context."
20390 (interactive)
20391 (cond
20392 ((org-at-table-p)
20393 (call-interactively 'org-table-insert-hline))
20394 ((org-region-active-p)
20395 (call-interactively 'org-toggle-item))
20396 ((org-in-item-p)
20397 (call-interactively 'org-cycle-list-bullet))
20399 (call-interactively 'org-toggle-item))))
20401 (defun org-toggle-item (arg)
20402 "Convert headings or normal lines to items, items to normal lines.
20403 If there is no active region, only the current line is considered.
20405 If the first non blank line in the region is a headline, convert
20406 all headlines to items, shifting text accordingly.
20408 If it is an item, convert all items to normal lines.
20410 If it is normal text, change region into a list of items.
20411 With a prefix argument ARG, change the region in a single item."
20412 (interactive "P")
20413 (let ((shift-text
20414 (function
20415 ;; Shift text in current section to IND, from point to END.
20416 ;; The function leaves point to END line.
20417 (lambda (ind end)
20418 (let ((min-i 1000) (end (copy-marker end)))
20419 ;; First determine the minimum indentation (MIN-I) of
20420 ;; the text.
20421 (save-excursion
20422 (catch 'exit
20423 (while (< (point) end)
20424 (let ((i (org-get-indentation)))
20425 (cond
20426 ;; Skip blank lines and inline tasks.
20427 ((looking-at "^[ \t]*$"))
20428 ((looking-at org-outline-regexp-bol))
20429 ;; We can't find less than 0 indentation.
20430 ((zerop i) (throw 'exit (setq min-i 0)))
20431 ((< i min-i) (setq min-i i))))
20432 (forward-line))))
20433 ;; Then indent each line so that a line indented to
20434 ;; MIN-I becomes indented to IND. Ignore blank lines
20435 ;; and inline tasks in the process.
20436 (let ((delta (- ind min-i)))
20437 (while (< (point) end)
20438 (unless (or (looking-at "^[ \t]*$")
20439 (looking-at org-outline-regexp-bol))
20440 (org-indent-line-to (+ (org-get-indentation) delta)))
20441 (forward-line)))))))
20442 (skip-blanks
20443 (function
20444 ;; Return beginning of first non-blank line, starting from
20445 ;; line at POS.
20446 (lambda (pos)
20447 (save-excursion
20448 (goto-char pos)
20449 (skip-chars-forward " \r\t\n")
20450 (point-at-bol)))))
20451 beg end)
20452 ;; Determine boundaries of changes.
20453 (if (org-region-active-p)
20454 (setq beg (funcall skip-blanks (region-beginning))
20455 end (copy-marker (region-end)))
20456 (setq beg (funcall skip-blanks (point-at-bol))
20457 end (copy-marker (point-at-eol))))
20458 ;; Depending on the starting line, choose an action on the text
20459 ;; between BEG and END.
20460 (org-with-limited-levels
20461 (save-excursion
20462 (goto-char beg)
20463 (cond
20464 ;; Case 1. Start at an item: de-itemize. Note that it only
20465 ;; happens when a region is active: `org-ctrl-c-minus'
20466 ;; would call `org-cycle-list-bullet' otherwise.
20467 ((org-at-item-p)
20468 (while (< (point) end)
20469 (when (org-at-item-p)
20470 (skip-chars-forward " \t")
20471 (delete-region (point) (match-end 0)))
20472 (forward-line)))
20473 ;; Case 2. Start at an heading: convert to items.
20474 ((org-at-heading-p)
20475 (let* ((bul (org-list-bullet-string "-"))
20476 (bul-len (length bul))
20477 ;; Indentation of the first heading. It should be
20478 ;; relative to the indentation of its parent, if any.
20479 (start-ind (save-excursion
20480 (cond
20481 ((not org-adapt-indentation) 0)
20482 ((not (outline-previous-heading)) 0)
20483 (t (length (match-string 0))))))
20484 ;; Level of first heading. Further headings will be
20485 ;; compared to it to determine hierarchy in the list.
20486 (ref-level (org-reduced-level (org-outline-level))))
20487 (while (< (point) end)
20488 (let* ((level (org-reduced-level (org-outline-level)))
20489 (delta (max 0 (- level ref-level))))
20490 ;; If current headline is less indented than the first
20491 ;; one, set it as reference, in order to preserve
20492 ;; subtrees.
20493 (when (< level ref-level) (setq ref-level level))
20494 (replace-match bul t t)
20495 (org-indent-line-to (+ start-ind (* delta bul-len)))
20496 ;; Ensure all text down to END (or SECTION-END) belongs
20497 ;; to the newly created item.
20498 (let ((section-end (save-excursion
20499 (or (outline-next-heading) (point)))))
20500 (forward-line)
20501 (funcall shift-text
20502 (+ start-ind (* (1+ delta) bul-len))
20503 (min end section-end)))))))
20504 ;; Case 3. Normal line with ARG: make the first line of region
20505 ;; an item, and shift indentation of others lines to
20506 ;; set them as item's body.
20507 (arg (let* ((bul (org-list-bullet-string "-"))
20508 (bul-len (length bul))
20509 (ref-ind (org-get-indentation)))
20510 (skip-chars-forward " \t")
20511 (insert bul)
20512 (forward-line)
20513 (while (< (point) end)
20514 ;; Ensure that lines less indented than first one
20515 ;; still get included in item body.
20516 (funcall shift-text
20517 (+ ref-ind bul-len)
20518 (min end (save-excursion (or (outline-next-heading)
20519 (point)))))
20520 (forward-line))))
20521 ;; Case 4. Normal line without ARG: turn each non-item line
20522 ;; into an item.
20524 (while (< (point) end)
20525 (unless (or (org-at-heading-p) (org-at-item-p))
20526 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20527 (replace-match
20528 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20529 (forward-line))))))))
20531 (defun org-toggle-heading (&optional nstars)
20532 "Convert headings to normal text, or items or text to headings.
20533 If there is no active region, only convert the current line.
20535 With a \\[universal-argument] prefix, convert the whole list at
20536 point into heading.
20538 In a region:
20540 - If the first non blank line is a headline, remove the stars
20541 from all headlines in the region.
20543 - If it is a normal line, turn each and every normal line (i.e.,
20544 not an heading or an item) in the region into headings. If you
20545 want to convert only the first line of this region, use one
20546 universal prefix argument.
20548 - If it is a plain list item, turn all plain list items into headings.
20550 When converting a line into a heading, the number of stars is chosen
20551 such that the lines become children of the current entry. However,
20552 when a numeric prefix argument is given, its value determines the
20553 number of stars to add."
20554 (interactive "P")
20555 (let ((skip-blanks
20556 (function
20557 ;; Return beginning of first non-blank line, starting from
20558 ;; line at POS.
20559 (lambda (pos)
20560 (save-excursion
20561 (goto-char pos)
20562 (while (org-at-comment-p) (forward-line))
20563 (skip-chars-forward " \r\t\n")
20564 (point-at-bol)))))
20565 beg end toggled)
20566 ;; Determine boundaries of changes. If a universal prefix has
20567 ;; been given, put the list in a region. If region ends at a bol,
20568 ;; do not consider the last line to be in the region.
20570 (when (and current-prefix-arg (org-at-item-p))
20571 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20572 (org-mark-element))
20574 (if (org-region-active-p)
20575 (setq beg (funcall skip-blanks (region-beginning))
20576 end (copy-marker (save-excursion
20577 (goto-char (region-end))
20578 (if (bolp) (point) (point-at-eol)))))
20579 (setq beg (funcall skip-blanks (point-at-bol))
20580 end (copy-marker (point-at-eol))))
20581 ;; Ensure inline tasks don't count as headings.
20582 (org-with-limited-levels
20583 (save-excursion
20584 (goto-char beg)
20585 (cond
20586 ;; Case 1. Started at an heading: de-star headings.
20587 ((org-at-heading-p)
20588 (while (< (point) end)
20589 (when (org-at-heading-p t)
20590 (looking-at org-outline-regexp) (replace-match "")
20591 (setq toggled t))
20592 (forward-line)))
20593 ;; Case 2. Started at an item: change items into headlines.
20594 ;; One star will be added by `org-list-to-subtree'.
20595 ((org-at-item-p)
20596 (let* ((stars (make-string
20597 ;; subtract the star that will be added again by
20598 ;; `org-list-to-subtree'
20599 (if (numberp nstars) (1- nstars)
20600 (or (org-current-level) 0))
20601 ?*))
20602 (add-stars
20603 (cond (nstars "") ; stars from prefix only
20604 ((equal stars "") "") ; before first heading
20605 (org-odd-levels-only "*") ; inside heading, odd
20606 (t "")))) ; inside heading, oddeven
20607 (while (< (point) end)
20608 (when (org-at-item-p)
20609 ;; Pay attention to cases when region ends before list.
20610 (let* ((struct (org-list-struct))
20611 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20612 (save-restriction
20613 (narrow-to-region (point) list-end)
20614 (insert
20615 (org-list-to-subtree
20616 (org-list-parse-list t)
20617 '(:istart (concat stars add-stars (funcall get-stars depth))
20618 :icount (concat stars add-stars (funcall get-stars depth)))))))
20619 (setq toggled t))
20620 (forward-line))))
20621 ;; Case 3. Started at normal text: make every line an heading,
20622 ;; skipping headlines and items.
20623 (t (let* ((stars
20624 (make-string
20625 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20626 (add-stars
20627 (cond (nstars "") ; stars from prefix only
20628 ((equal stars "") "*") ; before first heading
20629 (org-odd-levels-only "**") ; inside heading, odd
20630 (t "*"))) ; inside heading, oddeven
20631 (rpl (concat stars add-stars " "))
20632 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20633 (while (< (point) (if (equal nstars '(4)) lend end))
20634 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20635 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20636 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20637 (forward-line)))))))
20638 (unless toggled (message "Cannot toggle heading from here"))))
20640 (defun org-meta-return (&optional arg)
20641 "Insert a new heading or wrap a region in a table.
20642 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20643 See the individual commands for more information."
20644 (interactive "P")
20645 (org-check-before-invisible-edit 'insert)
20646 (cond
20647 ((run-hook-with-args-until-success 'org-metareturn-hook))
20648 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20649 (newline-and-indent))
20650 ((org-at-table-p)
20651 (call-interactively 'org-table-wrap-region))
20652 (t (call-interactively 'org-insert-heading))))
20654 ;;; Menu entries
20656 (defsubst org-in-subtree-not-table-p ()
20657 "Are we in a subtree and not in a table?"
20658 (and (not (org-before-first-heading-p))
20659 (not (org-at-table-p))))
20661 ;; Define the Org-mode menus
20662 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20663 '("Tbl"
20664 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20665 ["Next Field" org-cycle (org-at-table-p)]
20666 ["Previous Field" org-shifttab (org-at-table-p)]
20667 ["Next Row" org-return (org-at-table-p)]
20668 "--"
20669 ["Blank Field" org-table-blank-field (org-at-table-p)]
20670 ["Edit Field" org-table-edit-field (org-at-table-p)]
20671 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20672 "--"
20673 ("Column"
20674 ["Move Column Left" org-metaleft (org-at-table-p)]
20675 ["Move Column Right" org-metaright (org-at-table-p)]
20676 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20677 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20678 ("Row"
20679 ["Move Row Up" org-metaup (org-at-table-p)]
20680 ["Move Row Down" org-metadown (org-at-table-p)]
20681 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20682 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20683 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20684 "--"
20685 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20686 ("Rectangle"
20687 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20688 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20689 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20690 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20691 "--"
20692 ("Calculate"
20693 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20694 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20695 ["Edit Formulas" org-edit-special (org-at-table-p)]
20696 "--"
20697 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20698 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20699 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20700 "--"
20701 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20702 "--"
20703 ["Sum Column/Rectangle" org-table-sum
20704 (or (org-at-table-p) (org-region-active-p))]
20705 ["Which Column?" org-table-current-column (org-at-table-p)])
20706 ["Debug Formulas"
20707 org-table-toggle-formula-debugger
20708 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20709 ["Show Col/Row Numbers"
20710 org-table-toggle-coordinate-overlays
20711 :style toggle
20712 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20713 "--"
20714 ["Create" org-table-create (and (not (org-at-table-p))
20715 org-enable-table-editor)]
20716 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20717 ["Import from File" org-table-import (not (org-at-table-p))]
20718 ["Export to File" org-table-export (org-at-table-p)]
20719 "--"
20720 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20722 (easy-menu-define org-org-menu org-mode-map "Org menu"
20723 '("Org"
20724 ("Show/Hide"
20725 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20726 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20727 ["Sparse Tree..." org-sparse-tree t]
20728 ["Reveal Context" org-reveal t]
20729 ["Show All" show-all t]
20730 "--"
20731 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20732 "--"
20733 ["New Heading" org-insert-heading t]
20734 ("Navigate Headings"
20735 ["Up" outline-up-heading t]
20736 ["Next" outline-next-visible-heading t]
20737 ["Previous" outline-previous-visible-heading t]
20738 ["Next Same Level" outline-forward-same-level t]
20739 ["Previous Same Level" outline-backward-same-level t]
20740 "--"
20741 ["Jump" org-goto t])
20742 ("Edit Structure"
20743 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20744 "--"
20745 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20746 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20747 "--"
20748 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20749 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20750 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20751 "--"
20752 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20753 "--"
20754 ["Copy visible text" org-copy-visible t]
20755 "--"
20756 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20757 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20758 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20759 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20760 "--"
20761 ["Sort Region/Children" org-sort t]
20762 "--"
20763 ["Convert to odd levels" org-convert-to-odd-levels t]
20764 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20765 ("Editing"
20766 ["Emphasis..." org-emphasize t]
20767 ["Edit Source Example" org-edit-special t]
20768 "--"
20769 ["Footnote new/jump" org-footnote-action t]
20770 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20771 ("Archive"
20772 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20773 "--"
20774 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20775 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20776 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20778 "--"
20779 ("Hyperlinks"
20780 ["Store Link (Global)" org-store-link t]
20781 ["Find existing link to here" org-occur-link-in-agenda-files t]
20782 ["Insert Link" org-insert-link t]
20783 ["Follow Link" org-open-at-point t]
20784 "--"
20785 ["Next link" org-next-link t]
20786 ["Previous link" org-previous-link t]
20787 "--"
20788 ["Descriptive Links"
20789 org-toggle-link-display
20790 :style radio
20791 :selected org-descriptive-links
20793 ["Literal Links"
20794 org-toggle-link-display
20795 :style radio
20796 :selected (not org-descriptive-links)])
20797 "--"
20798 ("TODO Lists"
20799 ["TODO/DONE/-" org-todo t]
20800 ("Select keyword"
20801 ["Next keyword" org-shiftright (org-at-heading-p)]
20802 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20803 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20804 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20805 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20806 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20807 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20808 "--"
20809 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20810 :selected org-enforce-todo-dependencies :style toggle :active t]
20811 "Settings for tree at point"
20812 ["Do Children sequentially" org-toggle-ordered-property :style radio
20813 :selected (org-entry-get nil "ORDERED")
20814 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20815 ["Do Children parallel" org-toggle-ordered-property :style radio
20816 :selected (not (org-entry-get nil "ORDERED"))
20817 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20818 "--"
20819 ["Set Priority" org-priority t]
20820 ["Priority Up" org-shiftup t]
20821 ["Priority Down" org-shiftdown t]
20822 "--"
20823 ["Get news from all feeds" org-feed-update-all t]
20824 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20825 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20826 ("TAGS and Properties"
20827 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20828 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20829 "--"
20830 ["Set property" org-set-property (not (org-before-first-heading-p))]
20831 ["Column view of properties" org-columns t]
20832 ["Insert Column View DBlock" org-insert-columns-dblock t])
20833 ("Dates and Scheduling"
20834 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20835 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20836 ("Change Date"
20837 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20838 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20839 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20840 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20841 ["Compute Time Range" org-evaluate-time-range t]
20842 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20843 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20844 "--"
20845 ["Custom time format" org-toggle-time-stamp-overlays
20846 :style radio :selected org-display-custom-times]
20847 "--"
20848 ["Goto Calendar" org-goto-calendar t]
20849 ["Date from Calendar" org-date-from-calendar t]
20850 "--"
20851 ["Start/Restart Timer" org-timer-start t]
20852 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20853 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20854 ["Insert Timer String" org-timer t]
20855 ["Insert Timer Item" org-timer-item t])
20856 ("Logging work"
20857 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20858 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20859 ["Clock out" org-clock-out t]
20860 ["Clock cancel" org-clock-cancel t]
20861 "--"
20862 ["Mark as default task" org-clock-mark-default-task t]
20863 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20864 ["Goto running clock" org-clock-goto t]
20865 "--"
20866 ["Display times" org-clock-display t]
20867 ["Create clock table" org-clock-report t]
20868 "--"
20869 ["Record DONE time"
20870 (progn (setq org-log-done (not org-log-done))
20871 (message "Switching to %s will %s record a timestamp"
20872 (car org-done-keywords)
20873 (if org-log-done "automatically" "not")))
20874 :style toggle :selected org-log-done])
20875 "--"
20876 ["Agenda Command..." org-agenda t]
20877 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20878 ("File List for Agenda")
20879 ("Special views current file"
20880 ["TODO Tree" org-show-todo-tree t]
20881 ["Check Deadlines" org-check-deadlines t]
20882 ["Timeline" org-timeline t]
20883 ["Tags/Property tree" org-match-sparse-tree t])
20884 "--"
20885 ["Export/Publish..." org-export-dispatch t]
20886 ("LaTeX"
20887 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20888 :selected org-cdlatex-mode]
20889 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20890 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20891 ["Modify math symbol" org-cdlatex-math-modify
20892 (org-inside-LaTeX-fragment-p)]
20893 ["Insert citation" org-reftex-citation t]
20894 "--"
20895 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20896 "--"
20897 ("MobileOrg"
20898 ["Push Files and Views" org-mobile-push t]
20899 ["Get Captured and Flagged" org-mobile-pull t]
20900 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20901 "--"
20902 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20903 "--"
20904 ("Documentation"
20905 ["Show Version" org-version t]
20906 ["Info Documentation" org-info t])
20907 ("Customize"
20908 ["Browse Org Group" org-customize t]
20909 "--"
20910 ["Expand This Menu" org-create-customize-menu
20911 (fboundp 'customize-menu-create)])
20912 ["Send bug report" org-submit-bug-report t]
20913 "--"
20914 ("Refresh/Reload"
20915 ["Refresh setup current buffer" org-mode-restart t]
20916 ["Reload Org (after update)" org-reload t]
20917 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20920 (defun org-info (&optional node)
20921 "Read documentation for Org-mode in the info system.
20922 With optional NODE, go directly to that node."
20923 (interactive)
20924 (info (format "(org)%s" (or node ""))))
20926 ;;;###autoload
20927 (defun org-submit-bug-report ()
20928 "Submit a bug report on Org-mode via mail.
20930 Don't hesitate to report any problems or inaccurate documentation.
20932 If you don't have setup sending mail from (X)Emacs, please copy the
20933 output buffer into your mail program, as it gives us important
20934 information about your Org-mode version and configuration."
20935 (interactive)
20936 (require 'reporter)
20937 (org-load-modules-maybe)
20938 (org-require-autoloaded-modules)
20939 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20940 (reporter-submit-bug-report
20941 "emacs-orgmode@gnu.org"
20942 (org-version nil 'full)
20943 (let (list)
20944 (save-window-excursion
20945 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20946 (delete-other-windows)
20947 (erase-buffer)
20948 (insert "You are about to submit a bug report to the Org-mode mailing list.
20950 We would like to add your full Org-mode and Outline configuration to the
20951 bug report. This greatly simplifies the work of the maintainer and
20952 other experts on the mailing list.
20954 HOWEVER, some variables you have customized may contain private
20955 information. The names of customers, colleagues, or friends, might
20956 appear in the form of file names, tags, todo states, or search strings.
20957 If you answer yes to the prompt, you might want to check and remove
20958 such private information before sending the email.")
20959 (add-text-properties (point-min) (point-max) '(face org-warning))
20960 (when (yes-or-no-p "Include your Org-mode configuration ")
20961 (mapatoms
20962 (lambda (v)
20963 (and (boundp v)
20964 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20965 (or (and (symbol-value v)
20966 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20967 (and
20968 (get v 'custom-type) (get v 'standard-value)
20969 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20970 (push v list)))))
20971 (kill-buffer (get-buffer "*Warn about privacy*"))
20972 list))
20973 nil nil
20974 "Remember to cover the basics, that is, what you expected to happen and
20975 what in fact did happen. You don't know how to make a good report? See
20977 http://orgmode.org/manual/Feedback.html#Feedback
20979 Your bug report will be posted to the Org-mode mailing list.
20980 ------------------------------------------------------------------------")
20981 (save-excursion
20982 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20983 (replace-match "\\1Bug: \\3 [\\2]")))))
20986 (defun org-install-agenda-files-menu ()
20987 (let ((bl (buffer-list)))
20988 (save-excursion
20989 (while bl
20990 (set-buffer (pop bl))
20991 (if (derived-mode-p 'org-mode) (setq bl nil)))
20992 (when (derived-mode-p 'org-mode)
20993 (easy-menu-change
20994 '("Org") "File List for Agenda"
20995 (append
20996 (list
20997 ["Edit File List" (org-edit-agenda-file-list) t]
20998 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20999 ["Remove Current File from List" org-remove-file t]
21000 ["Cycle through agenda files" org-cycle-agenda-files t]
21001 ["Occur in all agenda files" org-occur-in-agenda-files t]
21002 "--")
21003 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21005 ;;;; Documentation
21007 (defun org-require-autoloaded-modules ()
21008 (interactive)
21009 (mapc 'require
21010 '(org-agenda org-archive org-attach org-clock org-colview org-id
21011 org-remember org-table org-timer)))
21013 ;;;###autoload
21014 (defun org-reload (&optional uncompiled)
21015 "Reload all org lisp files.
21016 With prefix arg UNCOMPILED, load the uncompiled versions."
21017 (interactive "P")
21018 (require 'loadhist)
21019 (let* ((org-dir (org-find-library-dir "org"))
21020 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21021 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21022 (remove-re (mapconcat 'identity
21023 (mapcar (lambda (f) (concat "^" f "$"))
21024 (list (if (featurep 'xemacs)
21025 "org-colview"
21026 "org-colview-xemacs")
21027 "org" "org-loaddefs" "org-version"))
21028 "\\|"))
21029 (feats (delete-dups
21030 (mapcar 'file-name-sans-extension
21031 (mapcar 'file-name-nondirectory
21032 (delq nil
21033 (mapcar 'feature-file
21034 features))))))
21035 (lfeat (append
21036 (sort
21037 (setq feats
21038 (delq nil (mapcar
21039 (lambda (f)
21040 (if (and (string-match feature-re f)
21041 (not (string-match remove-re f)))
21042 f nil))
21043 feats)))
21044 'string-lessp)
21045 (list "org-version" "org")))
21046 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21047 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21048 load-uncore load-misses)
21049 (setq load-misses
21050 (delq 't
21051 (mapcar (lambda (f)
21052 (or (org-load-noerror-mustsuffix (concat org-dir f))
21053 (and (string= org-dir contrib-dir)
21054 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21055 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21056 (add-to-list 'load-uncore f 'append)
21059 lfeat)))
21060 (if load-uncore
21061 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21062 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21063 (if load-misses
21064 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21065 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21066 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21068 ;;;###autoload
21069 (defun org-customize ()
21070 "Call the customize function with org as argument."
21071 (interactive)
21072 (org-load-modules-maybe)
21073 (org-require-autoloaded-modules)
21074 (customize-browse 'org))
21076 (defun org-create-customize-menu ()
21077 "Create a full customization menu for Org-mode, insert it into the menu."
21078 (interactive)
21079 (org-load-modules-maybe)
21080 (org-require-autoloaded-modules)
21081 (if (fboundp 'customize-menu-create)
21082 (progn
21083 (easy-menu-change
21084 '("Org") "Customize"
21085 `(["Browse Org group" org-customize t]
21086 "--"
21087 ,(customize-menu-create 'org)
21088 ["Set" Custom-set t]
21089 ["Save" Custom-save t]
21090 ["Reset to Current" Custom-reset-current t]
21091 ["Reset to Saved" Custom-reset-saved t]
21092 ["Reset to Standard Settings" Custom-reset-standard t]))
21093 (message "\"Org\"-menu now contains full customization menu"))
21094 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21096 ;;;; Miscellaneous stuff
21098 ;;; Generally useful functions
21100 (defun org-get-at-bol (property)
21101 "Get text property PROPERTY at beginning of line."
21102 (get-text-property (point-at-bol) property))
21104 (defun org-find-text-property-in-string (prop s)
21105 "Return the first non-nil value of property PROP in string S."
21106 (or (get-text-property 0 prop s)
21107 (get-text-property (or (next-single-property-change 0 prop s) 0)
21108 prop s)))
21110 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21111 "Display the given MESSAGE as a warning."
21112 (if (fboundp 'display-warning)
21113 (display-warning 'org message
21114 (if (featurep 'xemacs) 'warning :warning))
21115 (let ((buf (get-buffer-create "*Org warnings*")))
21116 (with-current-buffer buf
21117 (goto-char (point-max))
21118 (insert "Warning (Org): " message)
21119 (unless (bolp)
21120 (newline)))
21121 (display-buffer buf)
21122 (sit-for 0))))
21124 (defun org-eval (form)
21125 "Eval FORM and return result."
21126 (condition-case error
21127 (eval form)
21128 (error (format "%%![Error: %s]" error))))
21130 (defun org-in-clocktable-p ()
21131 "Check if the cursor is in a clocktable."
21132 (let ((pos (point)) start)
21133 (save-excursion
21134 (end-of-line 1)
21135 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21136 (setq start (match-beginning 0))
21137 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21138 (>= (match-end 0) pos)
21139 start))))
21141 (defun org-in-commented-line ()
21142 "Is point in a line starting with `#'?"
21143 (equal (char-after (point-at-bol)) ?#))
21145 (defun org-in-indented-comment-line ()
21146 "Is point in a line starting with `#' after some white space?"
21147 (save-excursion
21148 (save-match-data
21149 (goto-char (point-at-bol))
21150 (looking-at "[ \t]*#"))))
21152 (defun org-in-verbatim-emphasis ()
21153 (save-match-data
21154 (and (org-in-regexp org-emph-re 2)
21155 (>= (point) (match-beginning 3))
21156 (<= (point) (match-end 4))
21157 (member (match-string 3) '("=" "~")))))
21159 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21160 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21161 (if (and marker (marker-buffer marker)
21162 (buffer-live-p (marker-buffer marker)))
21163 (progn
21164 (org-pop-to-buffer-same-window (marker-buffer marker))
21165 (if (or (> marker (point-max)) (< marker (point-min)))
21166 (widen))
21167 (goto-char marker)
21168 (org-show-context 'org-goto))
21169 (if bookmark
21170 (bookmark-jump bookmark)
21171 (error "Cannot find location"))))
21173 (defun org-quote-csv-field (s)
21174 "Quote field for inclusion in CSV material."
21175 (if (string-match "[\",]" s)
21176 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21179 (defun org-force-self-insert (N)
21180 "Needed to enforce self-insert under remapping."
21181 (interactive "p")
21182 (self-insert-command N))
21184 (defun org-string-width (s)
21185 "Compute width of string, ignoring invisible characters.
21186 This ignores character with invisibility property `org-link', and also
21187 characters with property `org-cwidth', because these will become invisible
21188 upon the next fontification round."
21189 (let (b l)
21190 (when (or (eq t buffer-invisibility-spec)
21191 (assq 'org-link buffer-invisibility-spec))
21192 (while (setq b (text-property-any 0 (length s)
21193 'invisible 'org-link s))
21194 (setq s (concat (substring s 0 b)
21195 (substring s (or (next-single-property-change
21196 b 'invisible s) (length s)))))))
21197 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21198 (setq s (concat (substring s 0 b)
21199 (substring s (or (next-single-property-change
21200 b 'org-cwidth s) (length s))))))
21201 (setq l (string-width s) b -1)
21202 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21203 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21206 (defun org-shorten-string (s maxlength)
21207 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21208 If the string is shorter or has length MAXLENGTH, just return the
21209 original string. If it is longer, the functions finds a space in the
21210 string, breaks this string off at that locations and adds three dots
21211 as ellipsis. Including the ellipsis, the string will not be longer
21212 than MAXLENGTH. If finding a good breaking point in the string does
21213 not work, the string is just chopped off in the middle of a word
21214 if necessary."
21215 (if (<= (length s) maxlength)
21217 (let* ((n (max (- maxlength 4) 1))
21218 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21219 (if (string-match re s)
21220 (concat (match-string 1 s) "...")
21221 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21223 (defun org-get-indentation (&optional line)
21224 "Get the indentation of the current line, interpreting tabs.
21225 When LINE is given, assume it represents a line and compute its indentation."
21226 (if line
21227 (if (string-match "^ *" (org-remove-tabs line))
21228 (match-end 0))
21229 (save-excursion
21230 (beginning-of-line 1)
21231 (skip-chars-forward " \t")
21232 (current-column))))
21234 (defun org-get-string-indentation (s)
21235 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21236 (let ((n -1) (i 0) (w tab-width) c)
21237 (catch 'exit
21238 (while (< (setq n (1+ n)) (length s))
21239 (setq c (aref s n))
21240 (cond ((= c ?\ ) (setq i (1+ i)))
21241 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21242 (t (throw 'exit t)))))
21245 (defun org-remove-tabs (s &optional width)
21246 "Replace tabulators in S with spaces.
21247 Assumes that s is a single line, starting in column 0."
21248 (setq width (or width tab-width))
21249 (while (string-match "\t" s)
21250 (setq s (replace-match
21251 (make-string
21252 (- (* width (/ (+ (match-beginning 0) width) width))
21253 (match-beginning 0)) ?\ )
21254 t t s)))
21257 (defun org-fix-indentation (line ind)
21258 "Fix indentation in LINE.
21259 IND is a cons cell with target and minimum indentation.
21260 If the current indentation in LINE is smaller than the minimum,
21261 leave it alone. If it is larger than ind, set it to the target."
21262 (let* ((l (org-remove-tabs line))
21263 (i (org-get-indentation l))
21264 (i1 (car ind)) (i2 (cdr ind)))
21265 (if (>= i i2) (setq l (substring line i2)))
21266 (if (> i1 0)
21267 (concat (make-string i1 ?\ ) l)
21268 l)))
21270 (defun org-remove-indentation (code &optional n)
21271 "Remove the maximum common indentation from the lines in CODE.
21272 N may optionally be the number of spaces to remove."
21273 (with-temp-buffer
21274 (insert code)
21275 (org-do-remove-indentation n)
21276 (buffer-string)))
21278 (defun org-do-remove-indentation (&optional n)
21279 "Remove the maximum common indentation from the buffer."
21280 (untabify (point-min) (point-max))
21281 (let ((min 10000) re)
21282 (if n
21283 (setq min n)
21284 (goto-char (point-min))
21285 (while (re-search-forward "^ *[^ \n]" nil t)
21286 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21287 (unless (or (= min 0) (= min 10000))
21288 (setq re (format "^ \\{%d\\}" min))
21289 (goto-char (point-min))
21290 (while (re-search-forward re nil t)
21291 (replace-match "")
21292 (end-of-line 1))
21293 min)))
21295 (defun org-fill-template (template alist)
21296 "Find each %key of ALIST in TEMPLATE and replace it."
21297 (let ((case-fold-search nil)
21298 entry key value)
21299 (setq alist (sort (copy-sequence alist)
21300 (lambda (a b) (< (length (car a)) (length (car b))))))
21301 (while (setq entry (pop alist))
21302 (setq template
21303 (replace-regexp-in-string
21304 (concat "%" (regexp-quote (car entry)))
21305 (or (cdr entry) "") template t t)))
21306 template))
21308 (defun org-base-buffer (buffer)
21309 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21310 (if (not buffer)
21311 buffer
21312 (or (buffer-base-buffer buffer)
21313 buffer)))
21315 (defun org-trim (s)
21316 "Remove whitespace at beginning and end of string."
21317 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21318 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21321 (defun org-wrap (string &optional width lines)
21322 "Wrap string to either a number of lines, or a width in characters.
21323 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21324 that costs. If there is a word longer than WIDTH, the text is actually
21325 wrapped to the length of that word.
21326 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21327 many lines, whatever width that takes.
21328 The return value is a list of lines, without newlines at the end."
21329 (let* ((words (org-split-string string "[ \t\n]+"))
21330 (maxword (apply 'max (mapcar 'org-string-width words)))
21331 w ll)
21332 (cond (width
21333 (org-do-wrap words (max maxword width)))
21334 (lines
21335 (setq w maxword)
21336 (setq ll (org-do-wrap words maxword))
21337 (if (<= (length ll) lines)
21339 (setq ll words)
21340 (while (> (length ll) lines)
21341 (setq w (1+ w))
21342 (setq ll (org-do-wrap words w)))
21343 ll))
21344 (t (error "Cannot wrap this")))))
21346 (defun org-do-wrap (words width)
21347 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21348 (let (lines line)
21349 (while words
21350 (setq line (pop words))
21351 (while (and words (< (+ (length line) (length (car words))) width))
21352 (setq line (concat line " " (pop words))))
21353 (setq lines (push line lines)))
21354 (nreverse lines)))
21356 (defun org-split-string (string &optional separators)
21357 "Splits STRING into substrings at SEPARATORS.
21358 No empty strings are returned if there are matches at the beginning
21359 and end of string."
21360 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21361 (start 0)
21362 notfirst
21363 (list nil))
21364 (while (and (string-match rexp string
21365 (if (and notfirst
21366 (= start (match-beginning 0))
21367 (< start (length string)))
21368 (1+ start) start))
21369 (< (match-beginning 0) (length string)))
21370 (setq notfirst t)
21371 (or (eq (match-beginning 0) 0)
21372 (and (eq (match-beginning 0) (match-end 0))
21373 (eq (match-beginning 0) start))
21374 (setq list
21375 (cons (substring string start (match-beginning 0))
21376 list)))
21377 (setq start (match-end 0)))
21378 (or (eq start (length string))
21379 (setq list
21380 (cons (substring string start)
21381 list)))
21382 (nreverse list)))
21384 (defun org-quote-vert (s)
21385 "Replace \"|\" with \"\\vert\"."
21386 (while (string-match "|" s)
21387 (setq s (replace-match "\\vert" t t s)))
21390 (defun org-uuidgen-p (s)
21391 "Is S an ID created by UUIDGEN?"
21392 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21394 (defun org-in-src-block-p (&optional inside)
21395 "Whether point is in a code source block.
21396 When INSIDE is non-nil, don't consider we are within a src block
21397 when point is at #+BEGIN_SRC or #+END_SRC."
21398 (let ((case-fold-search t) ov)
21399 (or (and (setq ov (overlays-at (point)))
21400 (memq 'org-block-background
21401 (overlay-properties (car ov))))
21402 (and (not inside)
21403 (save-match-data
21404 (save-excursion
21405 (beginning-of-line)
21406 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21408 (defun org-context ()
21409 "Return a list of contexts of the current cursor position.
21410 If several contexts apply, all are returned.
21411 Each context entry is a list with a symbol naming the context, and
21412 two positions indicating start and end of the context. Possible
21413 contexts are:
21415 :headline anywhere in a headline
21416 :headline-stars on the leading stars in a headline
21417 :todo-keyword on a TODO keyword (including DONE) in a headline
21418 :tags on the TAGS in a headline
21419 :priority on the priority cookie in a headline
21420 :item on the first line of a plain list item
21421 :item-bullet on the bullet/number of a plain list item
21422 :checkbox on the checkbox in a plain list item
21423 :table in an org-mode table
21424 :table-special on a special filed in a table
21425 :table-table in a table.el table
21426 :clocktable in a clocktable
21427 :src-block in a source block
21428 :link on a hyperlink
21429 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21430 :target on a <<target>>
21431 :radio-target on a <<<radio-target>>>
21432 :latex-fragment on a LaTeX fragment
21433 :latex-preview on a LaTeX fragment with overlaid preview image
21435 This function expects the position to be visible because it uses font-lock
21436 faces as a help to recognize the following contexts: :table-special, :link,
21437 and :keyword."
21438 (let* ((f (get-text-property (point) 'face))
21439 (faces (if (listp f) f (list f)))
21440 (case-fold-search t)
21441 (p (point)) clist o)
21442 ;; First the large context
21443 (cond
21444 ((org-at-heading-p t)
21445 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21446 (when (progn
21447 (beginning-of-line 1)
21448 (looking-at org-todo-line-tags-regexp))
21449 (push (org-point-in-group p 1 :headline-stars) clist)
21450 (push (org-point-in-group p 2 :todo-keyword) clist)
21451 (push (org-point-in-group p 4 :tags) clist))
21452 (goto-char p)
21453 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21454 (if (looking-at "\\[#[A-Z0-9]\\]")
21455 (push (org-point-in-group p 0 :priority) clist)))
21457 ((org-at-item-p)
21458 (push (org-point-in-group p 2 :item-bullet) clist)
21459 (push (list :item (point-at-bol)
21460 (save-excursion (org-end-of-item) (point)))
21461 clist)
21462 (and (org-at-item-checkbox-p)
21463 (push (org-point-in-group p 0 :checkbox) clist)))
21465 ((org-at-table-p)
21466 (push (list :table (org-table-begin) (org-table-end)) clist)
21467 (if (memq 'org-formula faces)
21468 (push (list :table-special
21469 (previous-single-property-change p 'face)
21470 (next-single-property-change p 'face)) clist)))
21471 ((org-at-table-p 'any)
21472 (push (list :table-table) clist)))
21473 (goto-char p)
21475 (let ((case-fold-search t))
21476 ;; New the "medium" contexts: clocktables, source blocks
21477 (cond ((org-in-clocktable-p)
21478 (push (list :clocktable
21479 (and (or (looking-at "#\\+BEGIN: clocktable")
21480 (search-backward "#+BEGIN: clocktable" nil t))
21481 (match-beginning 0))
21482 (and (re-search-forward "#\\+END:?" nil t)
21483 (match-end 0))) clist))
21484 ((org-in-src-block-p)
21485 (push (list :src-block
21486 (and (or (looking-at "#\\+BEGIN_SRC")
21487 (search-backward "#+BEGIN_SRC" nil t))
21488 (match-beginning 0))
21489 (and (search-forward "#+END_SRC" nil t)
21490 (match-beginning 0))) clist))))
21491 (goto-char p)
21493 ;; Now the small context
21494 (cond
21495 ((org-at-timestamp-p)
21496 (push (org-point-in-group p 0 :timestamp) clist))
21497 ((memq 'org-link faces)
21498 (push (list :link
21499 (previous-single-property-change p 'face)
21500 (next-single-property-change p 'face)) clist))
21501 ((memq 'org-special-keyword faces)
21502 (push (list :keyword
21503 (previous-single-property-change p 'face)
21504 (next-single-property-change p 'face)) clist))
21505 ((org-at-target-p)
21506 (push (org-point-in-group p 0 :target) clist)
21507 (goto-char (1- (match-beginning 0)))
21508 (if (looking-at org-radio-target-regexp)
21509 (push (org-point-in-group p 0 :radio-target) clist))
21510 (goto-char p))
21511 ((setq o (car (delq nil
21512 (mapcar
21513 (lambda (x)
21514 (if (memq x org-latex-fragment-image-overlays) x))
21515 (overlays-at (point))))))
21516 (push (list :latex-fragment
21517 (overlay-start o) (overlay-end o)) clist)
21518 (push (list :latex-preview
21519 (overlay-start o) (overlay-end o)) clist))
21520 ((org-inside-LaTeX-fragment-p)
21521 ;; FIXME: positions wrong.
21522 (push (list :latex-fragment (point) (point)) clist)))
21524 (setq clist (nreverse (delq nil clist)))
21525 clist))
21527 ;; FIXME: Compare with at-regexp-p Do we need both?
21528 (defun org-in-regexp (re &optional nlines visually)
21529 "Check if point is inside a match of regexp.
21530 Normally only the current line is checked, but you can include NLINES extra
21531 lines both before and after point into the search.
21532 If VISUALLY is set, require that the cursor is not after the match but
21533 really on, so that the block visually is on the match."
21534 (catch 'exit
21535 (let ((pos (point))
21536 (eol (point-at-eol (+ 1 (or nlines 0))))
21537 (inc (if visually 1 0)))
21538 (save-excursion
21539 (beginning-of-line (- 1 (or nlines 0)))
21540 (while (re-search-forward re eol t)
21541 (if (and (<= (match-beginning 0) pos)
21542 (>= (+ inc (match-end 0)) pos))
21543 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21545 (defun org-at-regexp-p (regexp)
21546 "Is point inside a match of REGEXP in the current line?"
21547 (catch 'exit
21548 (save-excursion
21549 (let ((pos (point)) (end (point-at-eol)))
21550 (beginning-of-line 1)
21551 (while (re-search-forward regexp end t)
21552 (if (and (<= (match-beginning 0) pos)
21553 (>= (match-end 0) pos))
21554 (throw 'exit t)))
21555 nil))))
21557 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21558 "Non-nil when point is between matches of START-RE and END-RE.
21560 Also return a non-nil value when point is on one of the matches.
21562 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21563 buffer positions. Default values are the positions of headlines
21564 surrounding the point.
21566 The functions returns a cons cell whose car (resp. cdr) is the
21567 position before START-RE (resp. after END-RE)."
21568 (save-match-data
21569 (let ((pos (point))
21570 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21571 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21572 beg end)
21573 (save-excursion
21574 ;; Point is on a block when on START-RE or if START-RE can be
21575 ;; found before it...
21576 (and (or (org-at-regexp-p start-re)
21577 (re-search-backward start-re limit-up t))
21578 (setq beg (match-beginning 0))
21579 ;; ... and END-RE after it...
21580 (goto-char (match-end 0))
21581 (re-search-forward end-re limit-down t)
21582 (> (setq end (match-end 0)) pos)
21583 ;; ... without another START-RE in-between.
21584 (goto-char (match-beginning 0))
21585 (not (re-search-backward start-re (1+ beg) t))
21586 ;; Return value.
21587 (cons beg end))))))
21589 (defun org-in-block-p (names)
21590 "Non-nil when point belongs to a block whose name belongs to NAMES.
21592 NAMES is a list of strings containing names of blocks.
21594 Return first block name matched, or nil. Beware that in case of
21595 nested blocks, the returned name may not belong to the closest
21596 block from point."
21597 (save-match-data
21598 (catch 'exit
21599 (let ((case-fold-search t)
21600 (lim-up (save-excursion (outline-previous-heading)))
21601 (lim-down (save-excursion (outline-next-heading))))
21602 (mapc (lambda (name)
21603 (let ((n (regexp-quote name)))
21604 (when (org-between-regexps-p
21605 (concat "^[ \t]*#\\+begin_" n)
21606 (concat "^[ \t]*#\\+end_" n)
21607 lim-up lim-down)
21608 (throw 'exit n))))
21609 names))
21610 nil)))
21612 (defun org-in-drawer-p ()
21613 "Is point within a drawer?"
21614 (save-match-data
21615 (let ((case-fold-search t)
21616 (lim-up (save-excursion (outline-previous-heading)))
21617 (lim-down (save-excursion (outline-next-heading))))
21618 (org-between-regexps-p
21619 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21620 "^[ \t]*:end:.*$"
21621 lim-up lim-down))))
21623 (defun org-occur-in-agenda-files (regexp &optional nlines)
21624 "Call `multi-occur' with buffers for all agenda files."
21625 (interactive "sOrg-files matching: \np")
21626 (let* ((files (org-agenda-files))
21627 (tnames (mapcar 'file-truename files))
21628 (extra org-agenda-text-search-extra-files)
21630 (when (eq (car extra) 'agenda-archives)
21631 (setq extra (cdr extra))
21632 (setq files (org-add-archive-files files)))
21633 (while (setq f (pop extra))
21634 (unless (member (file-truename f) tnames)
21635 (add-to-list 'files f 'append)
21636 (add-to-list 'tnames (file-truename f) 'append)))
21637 (multi-occur
21638 (mapcar (lambda (x)
21639 (with-current-buffer
21640 (or (get-file-buffer x) (find-file-noselect x))
21641 (widen)
21642 (current-buffer)))
21643 files)
21644 regexp)))
21646 (if (boundp 'occur-mode-find-occurrence-hook)
21647 ;; Emacs 23
21648 (add-hook 'occur-mode-find-occurrence-hook
21649 (lambda ()
21650 (when (derived-mode-p 'org-mode)
21651 (org-reveal))))
21652 ;; Emacs 22
21653 (defadvice occur-mode-goto-occurrence
21654 (after org-occur-reveal activate)
21655 (and (derived-mode-p 'org-mode) (org-reveal)))
21656 (defadvice occur-mode-goto-occurrence-other-window
21657 (after org-occur-reveal activate)
21658 (and (derived-mode-p 'org-mode) (org-reveal)))
21659 (defadvice occur-mode-display-occurrence
21660 (after org-occur-reveal activate)
21661 (when (derived-mode-p 'org-mode)
21662 (let ((pos (occur-mode-find-occurrence)))
21663 (with-current-buffer (marker-buffer pos)
21664 (save-excursion
21665 (goto-char pos)
21666 (org-reveal)))))))
21668 (defun org-occur-link-in-agenda-files ()
21669 "Create a link and search for it in the agendas.
21670 The link is not stored in `org-stored-links', it is just created
21671 for the search purpose."
21672 (interactive)
21673 (let ((link (condition-case nil
21674 (org-store-link nil)
21675 (error "Unable to create a link to here"))))
21676 (org-occur-in-agenda-files (regexp-quote link))))
21678 (defun org-reverse-string (string)
21679 "Return the reverse of STRING."
21680 (apply 'string (reverse (string-to-list string))))
21682 (defsubst org-uniquify (list)
21683 "Non-destructively remove duplicate elements from LIST."
21684 (let ((res (copy-sequence list))) (delete-dups res)))
21686 (defun org-uniquify-alist (alist)
21687 "Merge elements of ALIST with the same key.
21689 For example, in this alist:
21691 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21692 => '((a 1 3) (b 2))
21694 merge (a 1) and (a 3) into (a 1 3).
21696 The function returns the new ALIST."
21697 (let (rtn)
21698 (mapc
21699 (lambda (e)
21700 (let (n)
21701 (if (not (assoc (car e) rtn))
21702 (push e rtn)
21703 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21704 (setq rtn (assq-delete-all (car e) rtn))
21705 (push n rtn))))
21706 alist)
21707 rtn))
21709 (defun org-delete-all (elts list)
21710 "Remove all elements in ELTS from LIST."
21711 (while elts
21712 (setq list (delete (pop elts) list)))
21713 list)
21715 (defun org-count (cl-item cl-seq)
21716 "Count the number of occurrences of ITEM in SEQ.
21717 Taken from `count' in cl-seq.el with all keyword arguments removed."
21718 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21719 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21720 (while (< cl-start cl-end)
21721 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21722 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21723 (setq cl-start (1+ cl-start)))
21724 cl-count))
21726 (defun org-remove-if (predicate seq)
21727 "Remove everything from SEQ that fulfills PREDICATE."
21728 (let (res e)
21729 (while seq
21730 (setq e (pop seq))
21731 (if (not (funcall predicate e)) (push e res)))
21732 (nreverse res)))
21734 (defun org-remove-if-not (predicate seq)
21735 "Remove everything from SEQ that does not fulfill PREDICATE."
21736 (let (res e)
21737 (while seq
21738 (setq e (pop seq))
21739 (if (funcall predicate e) (push e res)))
21740 (nreverse res)))
21742 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21743 "Reduce two-argument FUNCTION across SEQ.
21744 Taken from `reduce' in cl-seq.el with all keyword arguments but
21745 \":initial-value\" removed."
21746 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21747 (cadr (memq :initial-value cl-keys)))
21748 (cl-seq (pop cl-seq))
21749 (t (funcall cl-func)))))
21750 (while cl-seq
21751 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21752 cl-accum))
21754 (defun org-every (pred seq)
21755 "Return true if PREDICATE is true of every element of SEQ.
21756 Adapted from `every' in cl.el."
21757 (catch 'org-every
21758 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21761 (defun org-some (pred seq)
21762 "Return true if PREDICATE is true of any element of SEQ.
21763 Adapted from `some' in cl.el."
21764 (catch 'org-some
21765 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21766 nil))
21768 (defun org-back-over-empty-lines ()
21769 "Move backwards over whitespace, to the beginning of the first empty line.
21770 Returns the number of empty lines passed."
21771 (let ((pos (point)))
21772 (if (cdr (assoc 'heading org-blank-before-new-entry))
21773 (skip-chars-backward " \t\n\r")
21774 (unless (eobp)
21775 (forward-line -1)))
21776 (beginning-of-line 2)
21777 (goto-char (min (point) pos))
21778 (count-lines (point) pos)))
21780 (defun org-skip-whitespace ()
21781 (skip-chars-forward " \t\n\r"))
21783 (defun org-point-in-group (point group &optional context)
21784 "Check if POINT is in match-group GROUP.
21785 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21786 match. If the match group does not exist or point is not inside it,
21787 return nil."
21788 (and (match-beginning group)
21789 (>= point (match-beginning group))
21790 (<= point (match-end group))
21791 (if context
21792 (list context (match-beginning group) (match-end group))
21793 t)))
21795 (defun org-switch-to-buffer-other-window (&rest args)
21796 "Switch to buffer in a second window on the current frame.
21797 In particular, do not allow pop-up frames.
21798 Returns the newly created buffer."
21799 (org-no-popups
21800 (apply 'switch-to-buffer-other-window args)))
21802 (defun org-combine-plists (&rest plists)
21803 "Create a single property list from all plists in PLISTS.
21804 The process starts by copying the first list, and then setting properties
21805 from the other lists. Settings in the last list are the most significant
21806 ones and overrule settings in the other lists."
21807 (let ((rtn (copy-sequence (pop plists)))
21808 p v ls)
21809 (while plists
21810 (setq ls (pop plists))
21811 (while ls
21812 (setq p (pop ls) v (pop ls))
21813 (setq rtn (plist-put rtn p v))))
21814 rtn))
21816 (defun org-replace-escapes (string table)
21817 "Replace %-escapes in STRING with values in TABLE.
21818 TABLE is an association list with keys like \"%a\" and string values.
21819 The sequences in STRING may contain normal field width and padding information,
21820 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21821 so values can contain further %-escapes if they are define later in TABLE."
21822 (let ((tbl (copy-alist table))
21823 (case-fold-search nil)
21824 (pchg 0)
21825 e re rpl)
21826 (while (setq e (pop tbl))
21827 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21828 (when (and (cdr e) (string-match re (cdr e)))
21829 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21830 (safe "SREF"))
21831 (add-text-properties 0 3 (list 'sref sref) safe)
21832 (setcdr e (replace-match safe t t (cdr e)))))
21833 (while (string-match re string)
21834 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21835 (cdr e)))
21836 (setq string (replace-match rpl t t string))))
21837 (while (setq pchg (next-property-change pchg string))
21838 (let ((sref (get-text-property pchg 'sref string)))
21839 (when (and sref (string-match "SREF" string pchg))
21840 (setq string (replace-match sref t t string)))))
21841 string))
21843 (defun org-sublist (list start end)
21844 "Return a section of LIST, from START to END.
21845 Counting starts at 1."
21846 (let (rtn (c start))
21847 (setq list (nthcdr (1- start) list))
21848 (while (and list (<= c end))
21849 (push (pop list) rtn)
21850 (setq c (1+ c)))
21851 (nreverse rtn)))
21853 (defun org-find-base-buffer-visiting (file)
21854 "Like `find-buffer-visiting' but always return the base buffer and
21855 not an indirect buffer."
21856 (let ((buf (or (get-file-buffer file)
21857 (find-buffer-visiting file))))
21858 (if buf
21859 (or (buffer-base-buffer buf) buf)
21860 nil)))
21862 (defun org-image-file-name-regexp (&optional extensions)
21863 "Return regexp matching the file names of images.
21864 If EXTENSIONS is given, only match these."
21865 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21866 (image-file-name-regexp)
21867 (let ((image-file-name-extensions
21868 (or extensions
21869 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21870 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21871 (concat "\\."
21872 (regexp-opt (nconc (mapcar 'upcase
21873 image-file-name-extensions)
21874 image-file-name-extensions)
21876 "\\'"))))
21878 (defun org-file-image-p (file &optional extensions)
21879 "Return non-nil if FILE is an image."
21880 (save-match-data
21881 (string-match (org-image-file-name-regexp extensions) file)))
21883 (defun org-get-cursor-date (&optional with-time)
21884 "Return the date at cursor in as a time.
21885 This works in the calendar and in the agenda, anywhere else it just
21886 returns the current time.
21887 If WITH-TIME is non-nil, returns the time of the event at point (in
21888 the agenda) or the current time of the day."
21889 (let (date day defd tp tm hod mod)
21890 (when with-time
21891 (setq tp (get-text-property (point) 'time))
21892 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21893 (setq hod (string-to-number (match-string 1 tp))
21894 mod (string-to-number (match-string 2 tp))))
21895 (or tp (setq hod (nth 2 (decode-time (current-time)))
21896 mod (nth 1 (decode-time (current-time))))))
21897 (cond
21898 ((eq major-mode 'calendar-mode)
21899 (setq date (calendar-cursor-to-date)
21900 defd (encode-time 0 (or mod 0) (or hod 0)
21901 (nth 1 date) (nth 0 date) (nth 2 date))))
21902 ((eq major-mode 'org-agenda-mode)
21903 (setq day (get-text-property (point) 'day))
21904 (if day
21905 (setq date (calendar-gregorian-from-absolute day)
21906 defd (encode-time 0 (or mod 0) (or hod 0)
21907 (nth 1 date) (nth 0 date) (nth 2 date))))))
21908 (or defd (current-time))))
21910 (defun org-mark-subtree (&optional up)
21911 "Mark the current subtree.
21912 This puts point at the start of the current subtree, and mark at
21913 the end. If a numeric prefix UP is given, move up into the
21914 hierarchy of headlines by UP levels before marking the subtree."
21915 (interactive "P")
21916 (org-with-limited-levels
21917 (cond ((org-at-heading-p) (beginning-of-line))
21918 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21919 (t (outline-previous-visible-heading 1))))
21920 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21921 (if (org-called-interactively-p 'any)
21922 (call-interactively 'org-mark-element)
21923 (org-mark-element)))
21926 ;;; Indentation
21928 (defun org-indent-line ()
21929 "Indent line depending on context."
21930 (interactive)
21931 (let* ((pos (point))
21932 (itemp (org-at-item-p))
21933 (case-fold-search t)
21934 (org-drawer-regexp (or org-drawer-regexp "\000"))
21935 (inline-task-p (and (featurep 'org-inlinetask)
21936 (org-inlinetask-in-task-p)))
21937 (inline-re (and inline-task-p
21938 (org-inlinetask-outline-regexp)))
21939 column)
21940 (if (and orgstruct-is-++ (eq pos (point)))
21941 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21942 (indent-according-to-mode))
21943 (beginning-of-line 1)
21944 (cond
21945 ;; Headings
21946 ((looking-at org-outline-regexp) (setq column 0))
21947 ;; Footnote definition
21948 ((looking-at org-footnote-definition-re) (setq column 0))
21949 ;; Literal examples
21950 ((looking-at "[ \t]*:\\( \\|$\\)")
21951 (setq column (org-get-indentation))) ; do nothing
21952 ;; Lists
21953 ((ignore-errors (goto-char (org-in-item-p)))
21954 (setq column (if itemp
21955 (org-get-indentation)
21956 (org-list-item-body-column (point))))
21957 (goto-char pos))
21958 ;; Drawers
21959 ((and (looking-at "[ \t]*:END:")
21960 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21961 (save-excursion
21962 (goto-char (1- (match-beginning 1)))
21963 (setq column (current-column))))
21964 ;; Special blocks
21965 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21966 (save-excursion
21967 (re-search-backward
21968 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21969 (setq column (org-get-indentation (match-string 0))))
21970 ((and (not (looking-at "[ \t]*#\\+begin_"))
21971 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21972 (save-excursion
21973 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21974 (setq column
21975 (cond ((equal (downcase (match-string 1)) "src")
21976 ;; src blocks: let `org-edit-src-exit' handle them
21977 (org-get-indentation))
21978 ((equal (downcase (match-string 1)) "example")
21979 (max (org-get-indentation)
21980 (org-get-indentation (match-string 0))))
21982 (org-get-indentation (match-string 0))))))
21983 ;; This line has nothing special, look at the previous relevant
21984 ;; line to compute indentation
21986 (beginning-of-line 0)
21987 (while (and (not (bobp))
21988 (not (looking-at org-table-line-regexp))
21989 (not (looking-at org-drawer-regexp))
21990 ;; When point started in an inline task, do not move
21991 ;; above task starting line.
21992 (not (and inline-task-p (looking-at inline-re)))
21993 ;; Skip drawers, blocks, empty lines, verbatim,
21994 ;; comments, tables, footnotes definitions, lists,
21995 ;; inline tasks.
21996 (or (and (looking-at "[ \t]*:END:")
21997 (re-search-backward org-drawer-regexp nil t))
21998 (and (looking-at "[ \t]*#\\+end_")
21999 (re-search-backward "[ \t]*#\\+begin_"nil t))
22000 (looking-at "[ \t]*[\n:#|]")
22001 (looking-at org-footnote-definition-re)
22002 (and (not inline-task-p)
22003 (featurep 'org-inlinetask)
22004 (org-inlinetask-in-task-p)
22005 (or (org-inlinetask-goto-beginning) t))))
22006 (beginning-of-line 0))
22007 (cond
22008 ;; There was a list item above.
22009 ((save-excursion
22010 (and (ignore-errors (goto-char (org-in-item-p)))
22011 (goto-char
22012 (org-list-get-top-point (org-list-struct)))))
22013 (looking-at org-list-full-item-re)
22014 (setq column (length (match-string 0))))
22015 ;; There was an heading above.
22016 ((looking-at "\\*+[ \t]+")
22017 (if (not org-adapt-indentation)
22018 (setq column 0)
22019 (goto-char (match-end 0))
22020 (setq column (current-column))))
22021 ;; A drawer had started and is unfinished
22022 ((looking-at org-drawer-regexp)
22023 (goto-char (1- (match-beginning 1)))
22024 (setq column (current-column)))
22025 ;; Else, nothing noticeable found: get indentation and go on.
22026 (t (setq column (org-get-indentation))))))
22027 ;; Now apply indentation and move cursor accordingly
22028 (goto-char pos)
22029 (if (<= (current-column) (current-indentation))
22030 (org-indent-line-to column)
22031 (save-excursion (org-indent-line-to column)))
22032 ;; Special polishing for properties, see `org-property-format'
22033 (setq column (current-column))
22034 (beginning-of-line 1)
22035 (if (looking-at org-property-re)
22036 (replace-match (concat (match-string 4)
22037 (format org-property-format
22038 (match-string 1) (match-string 3)))
22039 t t))
22040 (org-move-to-column column))))
22042 (defun org-indent-drawer ()
22043 "Indent the drawer at point."
22044 (interactive)
22045 (let ((p (point))
22046 (e (and (save-excursion (re-search-forward ":END:" nil t))
22047 (match-end 0)))
22048 (folded
22049 (save-excursion
22050 (end-of-line)
22051 (when (overlays-at (point))
22052 (member 'invisible (overlay-properties
22053 (car (overlays-at (point)))))))))
22054 (when folded (org-cycle))
22055 (indent-for-tab-command)
22056 (while (and (move-beginning-of-line 2) (< (point) e))
22057 (indent-for-tab-command))
22058 (goto-char p)
22059 (when folded (org-cycle)))
22060 (message "Drawer at point indented"))
22062 (defun org-indent-block ()
22063 "Indent the block at point."
22064 (interactive)
22065 (let ((p (point))
22066 (case-fold-search t)
22067 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22068 (match-end 0)))
22069 (folded
22070 (save-excursion
22071 (end-of-line)
22072 (when (overlays-at (point))
22073 (member 'invisible (overlay-properties
22074 (car (overlays-at (point)))))))))
22075 (when folded (org-cycle))
22076 (indent-for-tab-command)
22077 (while (and (move-beginning-of-line 2) (< (point) e))
22078 (indent-for-tab-command))
22079 (goto-char p)
22080 (when folded (org-cycle)))
22081 (message "Block at point indented"))
22083 (defun org-indent-region (start end)
22084 "Indent region."
22085 (interactive "r")
22086 (save-excursion
22087 (let ((line-end (org-current-line end)))
22088 (goto-char start)
22089 (while (< (org-current-line) line-end)
22090 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22091 (t (call-interactively 'org-indent-line)))
22092 (move-beginning-of-line 2)))))
22095 ;;; Filling
22097 ;; We use our own fill-paragraph and auto-fill functions.
22099 ;; `org-fill-paragraph' relies on adaptive filling and context
22100 ;; checking. Appropriate `fill-prefix' is computed with
22101 ;; `org-adaptive-fill-function'.
22103 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22104 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22105 ;; `org-adaptive-fill-function' value. Internally,
22106 ;; `org-comment-line-break-function' breaks the line.
22108 ;; `org-setup-filling' installs filling and auto-filling related
22109 ;; variables during `org-mode' initialization.
22111 (defun org-setup-filling ()
22112 (interactive)
22113 ;; Prevent auto-fill from inserting unwanted new items.
22114 (when (boundp 'fill-nobreak-predicate)
22115 (org-set-local
22116 'fill-nobreak-predicate
22117 (org-uniquify
22118 (append fill-nobreak-predicate
22119 '(org-fill-paragraph-separate-nobreak-p
22120 org-fill-line-break-nobreak-p
22121 org-fill-paragraph-with-timestamp-nobreak-p)))))
22122 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22123 (org-set-local 'auto-fill-inhibit-regexp nil)
22124 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22125 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22126 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22128 (defvar org-element-paragraph-separate) ; org-element.el
22129 (defun org-fill-paragraph-separate-nobreak-p ()
22130 "Non-nil when a new line at point would end current paragraph."
22131 (looking-at (substring org-element-paragraph-separate 1)))
22133 (defun org-fill-line-break-nobreak-p ()
22134 "Non-nil when a new line at point would create an Org line break."
22135 (save-excursion
22136 (skip-chars-backward "[ \t]")
22137 (skip-chars-backward "\\\\")
22138 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22140 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22141 "Non-nil when a new line at point would split a timestamp."
22142 (and (org-at-timestamp-p t)
22143 (not (looking-at org-ts-regexp-both))))
22145 (declare-function message-in-body-p "message" ())
22146 (defvar orgtbl-line-start-regexp) ; From org-table.el
22147 (defun org-adaptive-fill-function ()
22148 "Compute a fill prefix for the current line.
22149 Return fill prefix, as a string, or nil if current line isn't
22150 meant to be filled."
22151 (let (prefix)
22152 (catch 'exit
22153 (when (derived-mode-p 'message-mode)
22154 (save-excursion
22155 (beginning-of-line)
22156 (cond ((or (not (message-in-body-p))
22157 (looking-at orgtbl-line-start-regexp))
22158 (throw 'exit nil))
22159 ((looking-at message-cite-prefix-regexp)
22160 (throw 'exit (match-string-no-properties 0)))
22161 ((looking-at org-outline-regexp)
22162 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22163 (org-with-wide-buffer
22164 (let* ((p (line-beginning-position))
22165 (element (save-excursion
22166 (beginning-of-line)
22167 (or (ignore-errors (org-element-at-point))
22168 (user-error "An element cannot be parsed line %d"
22169 (line-number-at-pos (point))))))
22170 (type (org-element-type element))
22171 (post-affiliated (org-element-property :post-affiliated element)))
22172 (unless (and post-affiliated (< p post-affiliated))
22173 (case type
22174 (comment (looking-at "[ \t]*# ?") (match-string 0))
22175 (footnote-definition "")
22176 ((item plain-list)
22177 (make-string (org-list-item-body-column
22178 (or post-affiliated
22179 (org-element-property :begin element)))
22180 ? ))
22181 (paragraph
22182 ;; Fill prefix is usually the same as the current line,
22183 ;; except if the paragraph is at the beginning of an item.
22184 (let ((parent (org-element-property :parent element)))
22185 (cond ((eq (org-element-type parent) 'item)
22186 (make-string (org-list-item-body-column
22187 (org-element-property :begin parent))
22188 ? ))
22189 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22190 (match-string 0))
22191 (t ""))))
22192 (comment-block
22193 ;; Only fill contents if P is within block boundaries.
22194 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22195 (forward-line)
22196 (point)))
22197 (cend (save-excursion
22198 (goto-char (org-element-property :end element))
22199 (skip-chars-backward " \r\t\n")
22200 (line-beginning-position))))
22201 (when (and (>= p cbeg) (< p cend))
22202 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22203 (match-string 0)
22204 "")))))))))))
22206 (declare-function message-goto-body "message" ())
22207 (defvar message-cite-prefix-regexp) ; From message.el
22208 (defun org-fill-paragraph (&optional justify)
22209 "Fill element at point, when applicable.
22211 This function only applies to comment blocks, comments, example
22212 blocks and paragraphs. Also, as a special case, re-align table
22213 when point is at one.
22215 If JUSTIFY is non-nil (interactively, with prefix argument),
22216 justify as well. If `sentence-end-double-space' is non-nil, then
22217 period followed by one space does not end a sentence, so don't
22218 break a line there. The variable `fill-column' controls the
22219 width for filling.
22221 For convenience, when point is at a plain list, an item or
22222 a footnote definition, try to fill the first paragraph within."
22223 (interactive)
22224 (if (and (derived-mode-p 'message-mode)
22225 (or (not (message-in-body-p))
22226 (save-excursion (move-beginning-of-line 1)
22227 (looking-at message-cite-prefix-regexp))))
22228 ;; First ensure filling is correct in message-mode.
22229 (let ((fill-paragraph-function
22230 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22231 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22232 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22233 (paragraph-separate
22234 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22235 (fill-paragraph nil))
22236 (with-syntax-table org-mode-transpose-word-syntax-table
22237 ;; Move to end of line in order to get the first paragraph
22238 ;; within a plain list or a footnote definition.
22239 (let ((element (save-excursion
22240 (end-of-line)
22241 (or (ignore-errors (org-element-at-point))
22242 (user-error "An element cannot be parsed line %d"
22243 (line-number-at-pos (point)))))))
22244 ;; First check if point is in a blank line at the beginning of
22245 ;; the buffer. In that case, ignore filling.
22246 (case (org-element-type element)
22247 ;; Use major mode filling function is src blocks.
22248 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22249 ;; Align Org tables, leave table.el tables as-is.
22250 (table-row (org-table-align) t)
22251 (table
22252 (when (eq (org-element-property :type element) 'org)
22253 (save-excursion
22254 (goto-char (org-element-property :post-affiliated element))
22255 (org-table-align)))
22257 (paragraph
22258 ;; Paragraphs may contain `line-break' type objects.
22259 (let ((beg (max (point-min)
22260 (org-element-property :contents-begin element)))
22261 (end (min (point-max)
22262 (org-element-property :contents-end element))))
22263 ;; Do nothing if point is at an affiliated keyword.
22264 (if (< (line-end-position) beg) t
22265 (when (derived-mode-p 'message-mode)
22266 ;; In `message-mode', do not fill following citation
22267 ;; in current paragraph nor text before message body.
22268 (let ((body-start (save-excursion (message-goto-body))))
22269 (when body-start (setq beg (max body-start beg))))
22270 (when (save-excursion
22271 (re-search-forward
22272 (concat "^" message-cite-prefix-regexp) end t))
22273 (setq end (match-beginning 0))))
22274 ;; Fill paragraph, taking line breaks into account.
22275 ;; For that, slice the paragraph using line breaks as
22276 ;; separators, and fill the parts in reverse order to
22277 ;; avoid messing with markers.
22278 (save-excursion
22279 (goto-char end)
22280 (mapc
22281 (lambda (pos)
22282 (fill-region-as-paragraph pos (point) justify)
22283 (goto-char pos))
22284 ;; Find the list of ending positions for line breaks
22285 ;; in the current paragraph. Add paragraph
22286 ;; beginning to include first slice.
22287 (nreverse
22288 (cons beg
22289 (org-element-map
22290 (org-element--parse-objects
22291 beg end nil (org-element-restriction 'paragraph))
22292 'line-break
22293 (lambda (lb) (org-element-property :end lb)))))))
22294 t)))
22295 ;; Contents of `comment-block' type elements should be
22296 ;; filled as plain text, but only if point is within block
22297 ;; markers.
22298 (comment-block
22299 (let* ((case-fold-search t)
22300 (beg (save-excursion
22301 (goto-char (org-element-property :begin element))
22302 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22303 (forward-line)
22304 (point)))
22305 (end (save-excursion
22306 (goto-char (org-element-property :end element))
22307 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22308 (line-beginning-position))))
22309 (when (and (>= (point) beg) (< (point) end))
22310 (fill-region-as-paragraph
22311 (save-excursion
22312 (end-of-line)
22313 (re-search-backward "^[ \t]*$" beg 'move)
22314 (line-beginning-position))
22315 (save-excursion
22316 (beginning-of-line)
22317 (re-search-forward "^[ \t]*$" end 'move)
22318 (line-beginning-position))
22319 justify)))
22321 ;; Fill comments.
22322 (comment (fill-comment-paragraph justify))
22323 ;; Ignore every other element.
22324 (otherwise t))))))
22326 (defun org-auto-fill-function ()
22327 "Auto-fill function."
22328 ;; Check if auto-filling is meaningful.
22329 (let ((fc (current-fill-column)))
22330 (when (and fc (> (current-column) fc))
22331 (let* ((fill-prefix (org-adaptive-fill-function))
22332 ;; Enforce empty fill prefix, if required. Otherwise, it
22333 ;; will be computed again.
22334 (adaptive-fill-mode (not (equal fill-prefix ""))))
22335 (when fill-prefix (do-auto-fill))))))
22337 (defun org-comment-line-break-function (&optional soft)
22338 "Break line at point and indent, continuing comment if within one.
22339 The inserted newline is marked hard if variable
22340 `use-hard-newlines' is true, unless optional argument SOFT is
22341 non-nil."
22342 (if soft (insert-and-inherit ?\n) (newline 1))
22343 (save-excursion (forward-char -1) (delete-horizontal-space))
22344 (delete-horizontal-space)
22345 (indent-to-left-margin)
22346 (insert-before-markers-and-inherit fill-prefix))
22349 ;;; Comments
22351 ;; Org comments syntax is quite complex. It requires the entire line
22352 ;; to be just a comment. Also, even with the right syntax at the
22353 ;; beginning of line, some some elements (i.e. verse-block or
22354 ;; example-block) don't accept comments. Usual Emacs comment commands
22355 ;; cannot cope with those requirements. Therefore, Org replaces them.
22357 ;; Org still relies on `comment-dwim', but cannot trust
22358 ;; `comment-only-p'. So, `comment-region-function' and
22359 ;; `uncomment-region-function' both point
22360 ;; to`org-comment-or-uncomment-region'. Eventually,
22361 ;; `org-insert-comment' takes care of insertion of comments at the
22362 ;; beginning of line.
22364 ;; `org-setup-comments-handling' install comments related variables
22365 ;; during `org-mode' initialization.
22367 (defun org-setup-comments-handling ()
22368 (interactive)
22369 (org-set-local 'comment-use-syntax nil)
22370 (org-set-local 'comment-start "# ")
22371 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22372 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22373 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22374 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22376 (defun org-insert-comment ()
22377 "Insert an empty comment above current line.
22378 If the line is empty, insert comment at its beginning."
22379 (beginning-of-line)
22380 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22381 (org-indent-line)
22382 (insert "# "))
22384 (defvar comment-empty-lines) ; From newcomment.el.
22385 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22386 "Comment or uncomment each non-blank line in the region.
22387 Uncomment each non-blank line between BEG and END if it only
22388 contains commented lines. Otherwise, comment them."
22389 (save-restriction
22390 ;; Restrict region
22391 (narrow-to-region (save-excursion (goto-char beg)
22392 (skip-chars-forward " \r\t\n" end)
22393 (line-beginning-position))
22394 (save-excursion (goto-char end)
22395 (skip-chars-backward " \r\t\n" beg)
22396 (line-end-position)))
22397 (let ((uncommentp
22398 ;; UNCOMMENTP is non-nil when every non blank line between
22399 ;; BEG and END is a comment.
22400 (save-excursion
22401 (goto-char (point-min))
22402 (while (and (not (eobp))
22403 (let ((element (org-element-at-point)))
22404 (and (eq (org-element-type element) 'comment)
22405 (goto-char (min (point-max)
22406 (org-element-property
22407 :end element)))))))
22408 (eobp))))
22409 (if uncommentp
22410 ;; Only blank lines and comments in region: uncomment it.
22411 (save-excursion
22412 (goto-char (point-min))
22413 (while (not (eobp))
22414 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22415 (replace-match "" nil nil nil 1))
22416 (forward-line)))
22417 ;; Comment each line in region.
22418 (let ((min-indent (point-max)))
22419 ;; First find the minimum indentation across all lines.
22420 (save-excursion
22421 (goto-char (point-min))
22422 (while (and (not (eobp)) (not (zerop min-indent)))
22423 (unless (looking-at "[ \t]*$")
22424 (setq min-indent (min min-indent (current-indentation))))
22425 (forward-line)))
22426 ;; Then loop over all lines.
22427 (save-excursion
22428 (goto-char (point-min))
22429 (while (not (eobp))
22430 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22431 ;; Don't get fooled by invisible text (e.g. link path)
22432 ;; when moving to column MIN-INDENT.
22433 (let ((buffer-invisibility-spec nil))
22434 (org-move-to-column min-indent t))
22435 (insert comment-start))
22436 (forward-line))))))))
22439 ;;; Planning
22441 ;; This section contains tools to operate on timestamp objects, as
22442 ;; returned by, e.g. `org-element-context'.
22444 (defun org-timestamp-has-time-p (timestamp)
22445 "Non-nil when TIMESTAMP has a time specified."
22446 (org-element-property :hour-start timestamp))
22448 (defun org-timestamp-format (timestamp format &optional end utc)
22449 "Format a TIMESTAMP element into a string.
22451 FORMAT is a format specifier to be passed to
22452 `format-time-string'.
22454 When optional argument END is non-nil, use end of date-range or
22455 time-range, if possible.
22457 When optional argument UTC is non-nil, time will be expressed as
22458 Universal Time."
22459 (format-time-string
22460 format
22461 (apply 'encode-time
22462 (cons 0
22463 (mapcar
22464 (lambda (prop) (or (org-element-property prop timestamp) 0))
22465 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22466 '(:minute-start :hour-start :day-start :month-start
22467 :year-start)))))
22468 utc))
22470 (defun org-timestamp-split-range (timestamp &optional end)
22471 "Extract a timestamp object from a date or time range.
22473 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22474 the end of the range. Otherwise, extract its start.
22476 Return a new timestamp object sharing the same parent as
22477 TIMESTAMP."
22478 (let ((type (org-element-property :type timestamp)))
22479 (if (memq type '(active inactive diary)) timestamp
22480 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22481 ;; Set new type.
22482 (org-element-put-property
22483 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22484 ;; Copy start properties over end properties if END is
22485 ;; non-nil. Otherwise, copy end properties over `start' ones.
22486 (let ((p-alist '((:minute-start . :minute-end)
22487 (:hour-start . :hour-end)
22488 (:day-start . :day-end)
22489 (:month-start . :month-end)
22490 (:year-start . :year-end))))
22491 (dolist (p-cell p-alist)
22492 (org-element-put-property
22493 split-ts
22494 (funcall (if end 'car 'cdr) p-cell)
22495 (org-element-property
22496 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22497 ;; Eventually refresh `:raw-value'.
22498 (org-element-put-property split-ts :raw-value nil)
22499 (org-element-put-property
22500 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22502 (defun org-timestamp-translate (timestamp &optional boundary)
22503 "Apply `org-translate-time' on a TIMESTAMP object.
22504 When optional argument BOUNDARY is non-nil, it is either the
22505 symbol `start' or `end'. In this case, only translate the
22506 starting or ending part of TIMESTAMP if it is a date or time
22507 range. Otherwise, translate both parts."
22508 (if (and (not boundary)
22509 (memq (org-element-property :type timestamp)
22510 '(active-range inactive-range)))
22511 (concat
22512 (org-translate-time
22513 (org-element-property :raw-value
22514 (org-timestamp-split-range timestamp)))
22515 "--"
22516 (org-translate-time
22517 (org-element-property :raw-value
22518 (org-timestamp-split-range timestamp t))))
22519 (org-translate-time
22520 (org-element-property
22521 :raw-value
22522 (if (not boundary) timestamp
22523 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22527 ;;; Other stuff.
22529 (defun org-toggle-fixed-width-section (arg)
22530 "Toggle the fixed-width export.
22531 If there is no active region, the QUOTE keyword at the current headline is
22532 inserted or removed. When present, it causes the text between this headline
22533 and the next to be exported as fixed-width text, and unmodified.
22534 If there is an active region, this command adds or removes a colon as the
22535 first character of this line. If the first character of a line is a colon,
22536 this line is also exported in fixed-width font."
22537 (interactive "P")
22538 (let* ((cc 0)
22539 (regionp (org-region-active-p))
22540 (beg (if regionp (region-beginning) (point)))
22541 (end (if regionp (region-end)))
22542 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22543 (case-fold-search nil)
22544 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22545 off)
22546 (if regionp
22547 (save-excursion
22548 (goto-char beg)
22549 (setq cc (current-column))
22550 (beginning-of-line 1)
22551 (setq off (looking-at re))
22552 (while (> nlines 0)
22553 (setq nlines (1- nlines))
22554 (beginning-of-line 1)
22555 (cond
22556 (arg
22557 (org-move-to-column cc t)
22558 (insert ": \n")
22559 (forward-line -1))
22560 ((and off (looking-at re))
22561 (replace-match "" t t nil 1))
22562 ((not off) (org-move-to-column cc t) (insert ": ")))
22563 (forward-line 1)))
22564 (save-excursion
22565 (org-back-to-heading)
22566 (cond
22567 ((looking-at (format org-heading-keyword-regexp-format
22568 org-quote-string))
22569 (goto-char (match-end 1))
22570 (looking-at (concat " +" org-quote-string))
22571 (replace-match "" t t)
22572 (when (eolp) (insert " ")))
22573 ((looking-at org-outline-regexp)
22574 (goto-char (match-end 0))
22575 (insert org-quote-string " ")))))))
22577 (defun org-reftex-citation ()
22578 "Use reftex-citation to insert a citation into the buffer.
22579 This looks for a line like
22581 #+BIBLIOGRAPHY: foo plain option:-d
22583 and derives from it that foo.bib is the bibliography file relevant
22584 for this document. It then installs the necessary environment for RefTeX
22585 to work in this buffer and calls `reftex-citation' to insert a citation
22586 into the buffer.
22588 Export of such citations to both LaTeX and HTML is handled by the contributed
22589 package ox-bibtex by Taru Karttunen."
22590 (interactive)
22591 (let ((reftex-docstruct-symbol 'rds)
22592 (reftex-cite-format "\\cite{%l}")
22593 rds bib)
22594 (save-excursion
22595 (save-restriction
22596 (widen)
22597 (let ((case-fold-search t)
22598 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22599 (if (not (save-excursion
22600 (or (re-search-forward re nil t)
22601 (re-search-backward re nil t))))
22602 (error "No bibliography defined in file")
22603 (setq bib (concat (match-string 1) ".bib")
22604 rds (list (list 'bib bib)))))))
22605 (call-interactively 'reftex-citation)))
22607 ;;;; Functions extending outline functionality
22609 (defun org-beginning-of-line (&optional arg)
22610 "Go to the beginning of the current line. If that is invisible, continue
22611 to a visible line beginning. This makes the function of C-a more intuitive.
22612 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22613 first attempt, and only move to after the tags when the cursor is already
22614 beyond the end of the headline."
22615 (interactive "P")
22616 (let ((pos (point))
22617 (special (if (consp org-special-ctrl-a/e)
22618 (car org-special-ctrl-a/e)
22619 org-special-ctrl-a/e))
22620 refpos)
22621 (if (org-bound-and-true-p visual-line-mode)
22622 (beginning-of-visual-line 1)
22623 (beginning-of-line 1))
22624 (if (and arg (fboundp 'move-beginning-of-line))
22625 (call-interactively 'move-beginning-of-line)
22626 (if (bobp)
22628 (backward-char 1)
22629 (if (org-truely-invisible-p)
22630 (while (and (not (bobp)) (org-truely-invisible-p))
22631 (backward-char 1)
22632 (beginning-of-line 1))
22633 (forward-char 1))))
22634 (when special
22635 (cond
22636 ((and (looking-at org-complex-heading-regexp)
22637 (= (char-after (match-end 1)) ?\ ))
22638 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22639 (point-at-eol)))
22640 (goto-char
22641 (if (eq special t)
22642 (cond ((> pos refpos) refpos)
22643 ((= pos (point)) refpos)
22644 (t (point)))
22645 (cond ((> pos (point)) (point))
22646 ((not (eq last-command this-command)) (point))
22647 (t refpos)))))
22648 ((org-at-item-p)
22649 ;; Being at an item and not looking at an the item means point
22650 ;; was previously moved to beginning of a visual line, which
22651 ;; doesn't contain the item. Therefore, do nothing special,
22652 ;; just stay here.
22653 (when (looking-at org-list-full-item-re)
22654 ;; Set special position at first white space character after
22655 ;; bullet, and check-box, if any.
22656 (let ((after-bullet
22657 (let ((box (match-end 3)))
22658 (if (not box) (match-end 1)
22659 (let ((after (char-after box)))
22660 (if (and after (= after ? )) (1+ box) box))))))
22661 ;; Special case: Move point to special position when
22662 ;; currently after it or at beginning of line.
22663 (if (eq special t)
22664 (when (or (> pos after-bullet) (= (point) pos))
22665 (goto-char after-bullet))
22666 ;; Reversed case: Move point to special position when
22667 ;; point was already at beginning of line and command is
22668 ;; repeated.
22669 (when (and (= (point) pos) (eq last-command this-command))
22670 (goto-char after-bullet))))))))
22671 (org-no-warnings
22672 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22673 (setq disable-point-adjustment
22674 (or (not (invisible-p (point)))
22675 (not (invisible-p (max (point-min) (1- (point))))))))
22677 (defun org-end-of-line (&optional arg)
22678 "Go to the end of the line.
22679 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22680 tags on the first attempt, and only move to after the tags when
22681 the cursor is already beyond the end of the headline."
22682 (interactive "P")
22683 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22684 org-special-ctrl-a/e))
22685 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22686 'end-of-visual-line)
22687 ((fboundp 'move-end-of-line) 'move-end-of-line)
22688 (t 'end-of-line))))
22689 (if (or (not special) arg) (call-interactively move-fun)
22690 (let* ((element (save-excursion (beginning-of-line)
22691 (org-element-at-point)))
22692 (type (org-element-type element)))
22693 (cond
22694 ((memq type '(headline inlinetask))
22695 (let ((pos (point)))
22696 (beginning-of-line 1)
22697 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22698 (if (eq special t)
22699 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22700 (goto-char (match-beginning 1))
22701 (goto-char (match-end 0)))
22702 (if (or (< pos (match-end 0))
22703 (not (eq this-command last-command)))
22704 (goto-char (match-end 0))
22705 (goto-char (match-beginning 1))))
22706 (call-interactively move-fun))))
22707 ((org-element-property :hiddenp element)
22708 ;; If element is hidden, `move-end-of-line' would put point
22709 ;; after it. Use `end-of-line' to stay on current line.
22710 (call-interactively 'end-of-line))
22711 (t (call-interactively move-fun)))))
22712 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22713 (setq disable-point-adjustment
22714 (or (not (invisible-p (point)))
22715 (not (invisible-p (max (point-min) (1- (point))))))))
22717 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22718 (define-key org-mode-map "\C-e" 'org-end-of-line)
22720 (defun org-backward-sentence (&optional arg)
22721 "Go to beginning of sentence, or beginning of table field.
22722 This will call `backward-sentence' or `org-table-beginning-of-field',
22723 depending on context."
22724 (interactive "P")
22725 (cond
22726 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22727 (t (call-interactively 'backward-sentence))))
22729 (defun org-forward-sentence (&optional arg)
22730 "Go to end of sentence, or end of table field.
22731 This will call `forward-sentence' or `org-table-end-of-field',
22732 depending on context."
22733 (interactive "P")
22734 (cond
22735 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22736 (t (call-interactively 'forward-sentence))))
22738 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22739 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22741 (defun org-kill-line (&optional arg)
22742 "Kill line, to tags or end of line."
22743 (interactive "P")
22744 (cond
22745 ((or (not org-special-ctrl-k)
22746 (bolp)
22747 (not (org-at-heading-p)))
22748 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22749 org-ctrl-k-protect-subtree)
22750 (if (or (eq org-ctrl-k-protect-subtree 'error)
22751 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22752 (user-error "C-k aborted as it would kill a hidden subtree")))
22753 (call-interactively
22754 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22755 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22756 (kill-region (point) (match-beginning 1))
22757 (org-set-tags nil t))
22758 (t (kill-region (point) (point-at-eol)))))
22760 (define-key org-mode-map "\C-k" 'org-kill-line)
22762 (defun org-yank (&optional arg)
22763 "Yank. If the kill is a subtree, treat it specially.
22764 This command will look at the current kill and check if is a single
22765 subtree, or a series of subtrees[1]. If it passes the test, and if the
22766 cursor is at the beginning of a line or after the stars of a currently
22767 empty headline, then the yank is handled specially. How exactly depends
22768 on the value of the following variables, both set by default.
22770 org-yank-folded-subtrees
22771 When set, the subtree(s) will be folded after insertion, but only
22772 if doing so would now swallow text after the yanked text.
22774 org-yank-adjusted-subtrees
22775 When set, the subtree will be promoted or demoted in order to
22776 fit into the local outline tree structure, which means that the level
22777 will be adjusted so that it becomes the smaller one of the two
22778 *visible* surrounding headings.
22780 Any prefix to this command will cause `yank' to be called directly with
22781 no special treatment. In particular, a simple \\[universal-argument] prefix \
22782 will just
22783 plainly yank the text as it is.
22785 \[1] The test checks if the first non-white line is a heading
22786 and if there are no other headings with fewer stars."
22787 (interactive "P")
22788 (org-yank-generic 'yank arg))
22790 (defun org-yank-generic (command arg)
22791 "Perform some yank-like command.
22793 This function implements the behavior described in the `org-yank'
22794 documentation. However, it has been generalized to work for any
22795 interactive command with similar behavior."
22797 ;; pretend to be command COMMAND
22798 (setq this-command command)
22800 (if arg
22801 (call-interactively command)
22803 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22804 (and (org-kill-is-subtree-p)
22805 (or (bolp)
22806 (and (looking-at "[ \t]*$")
22807 (string-match
22808 "\\`\\*+\\'"
22809 (buffer-substring (point-at-bol) (point)))))))
22810 swallowp)
22811 (cond
22812 ((and subtreep org-yank-folded-subtrees)
22813 (let ((beg (point))
22814 end)
22815 (if (and subtreep org-yank-adjusted-subtrees)
22816 (org-paste-subtree nil nil 'for-yank)
22817 (call-interactively command))
22819 (setq end (point))
22820 (goto-char beg)
22821 (when (and (bolp) subtreep
22822 (not (setq swallowp
22823 (org-yank-folding-would-swallow-text beg end))))
22824 (org-with-limited-levels
22825 (or (looking-at org-outline-regexp)
22826 (re-search-forward org-outline-regexp-bol end t))
22827 (while (and (< (point) end) (looking-at org-outline-regexp))
22828 (hide-subtree)
22829 (org-cycle-show-empty-lines 'folded)
22830 (condition-case nil
22831 (outline-forward-same-level 1)
22832 (error (goto-char end))))))
22833 (when swallowp
22834 (message
22835 "Inserted text not folded because that would swallow text"))
22837 (goto-char end)
22838 (skip-chars-forward " \t\n\r")
22839 (beginning-of-line 1)
22840 (push-mark beg 'nomsg)))
22841 ((and subtreep org-yank-adjusted-subtrees)
22842 (let ((beg (point-at-bol)))
22843 (org-paste-subtree nil nil 'for-yank)
22844 (push-mark beg 'nomsg)))
22846 (call-interactively command))))))
22848 (defun org-yank-folding-would-swallow-text (beg end)
22849 "Would hide-subtree at BEG swallow any text after END?"
22850 (let (level)
22851 (org-with-limited-levels
22852 (save-excursion
22853 (goto-char beg)
22854 (when (or (looking-at org-outline-regexp)
22855 (re-search-forward org-outline-regexp-bol end t))
22856 (setq level (org-outline-level)))
22857 (goto-char end)
22858 (skip-chars-forward " \t\r\n\v\f")
22859 (if (or (eobp)
22860 (and (bolp) (looking-at org-outline-regexp)
22861 (<= (org-outline-level) level)))
22862 nil ; Nothing would be swallowed
22863 t))))) ; something would swallow
22865 (define-key org-mode-map "\C-y" 'org-yank)
22867 (defun org-truely-invisible-p ()
22868 "Check if point is at a character currently not visible.
22869 This version does not only check the character property, but also
22870 `visible-mode'."
22871 ;; Early versions of noutline don't have `outline-invisible-p'.
22872 (if (org-bound-and-true-p visible-mode)
22874 (outline-invisible-p)))
22876 (defun org-invisible-p2 ()
22877 "Check if point is at a character currently not visible."
22878 (save-excursion
22879 (if (and (eolp) (not (bobp))) (backward-char 1))
22880 ;; Early versions of noutline don't have `outline-invisible-p'.
22881 (outline-invisible-p)))
22883 (defun org-back-to-heading (&optional invisible-ok)
22884 "Call `outline-back-to-heading', but provide a better error message."
22885 (condition-case nil
22886 (outline-back-to-heading invisible-ok)
22887 (error (error "Before first headline at position %d in buffer %s"
22888 (point) (current-buffer)))))
22890 (defun org-before-first-heading-p ()
22891 "Before first heading?"
22892 (save-excursion
22893 (end-of-line)
22894 (null (re-search-backward org-outline-regexp-bol nil t))))
22896 (defun org-at-heading-p (&optional ignored)
22897 (outline-on-heading-p t))
22898 ;; Compatibility alias with Org versions < 7.8.03
22899 (defalias 'org-on-heading-p 'org-at-heading-p)
22901 (defun org-at-comment-p nil
22902 "Is cursor in a line starting with a # character?"
22903 (save-excursion
22904 (beginning-of-line)
22905 (looking-at "^#")))
22907 (defun org-at-drawer-p nil
22908 "Is cursor at a drawer keyword?"
22909 (save-excursion
22910 (move-beginning-of-line 1)
22911 (looking-at org-drawer-regexp)))
22913 (defun org-at-block-p nil
22914 "Is cursor at a block keyword?"
22915 (save-excursion
22916 (move-beginning-of-line 1)
22917 (looking-at org-block-regexp)))
22919 (defun org-point-at-end-of-empty-headline ()
22920 "If point is at the end of an empty headline, return t, else nil.
22921 If the heading only contains a TODO keyword, it is still still considered
22922 empty."
22923 (and (looking-at "[ \t]*$")
22924 (when org-todo-line-regexp
22925 (save-excursion
22926 (beginning-of-line 1)
22927 (let ((case-fold-search nil))
22928 (looking-at org-todo-line-regexp)
22929 (string= (match-string 3) ""))))))
22931 (defun org-at-heading-or-item-p ()
22932 (or (org-at-heading-p) (org-at-item-p)))
22934 (defun org-at-target-p ()
22935 (or (org-in-regexp org-radio-target-regexp)
22936 (org-in-regexp org-target-regexp)))
22937 ;; Compatibility alias with Org versions < 7.8.03
22938 (defalias 'org-on-target-p 'org-at-target-p)
22940 (defun org-up-heading-all (arg)
22941 "Move to the heading line of which the present line is a subheading.
22942 This function considers both visible and invisible heading lines.
22943 With argument, move up ARG levels."
22944 (if (fboundp 'outline-up-heading-all)
22945 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22946 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22948 (defun org-up-heading-safe ()
22949 "Move to the heading line of which the present line is a subheading.
22950 This version will not throw an error. It will return the level of the
22951 headline found, or nil if no higher level is found.
22953 Also, this function will be a lot faster than `outline-up-heading',
22954 because it relies on stars being the outline starters. This can really
22955 make a significant difference in outlines with very many siblings."
22956 (let (start-level re)
22957 (org-back-to-heading t)
22958 (setq start-level (funcall outline-level))
22959 (if (equal start-level 1)
22961 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22962 (if (re-search-backward re nil t)
22963 (funcall outline-level)))))
22965 (defun org-first-sibling-p ()
22966 "Is this heading the first child of its parents?"
22967 (interactive)
22968 (let ((re org-outline-regexp-bol)
22969 level l)
22970 (unless (org-at-heading-p t)
22971 (user-error "Not at a heading"))
22972 (setq level (funcall outline-level))
22973 (save-excursion
22974 (if (not (re-search-backward re nil t))
22976 (setq l (funcall outline-level))
22977 (< l level)))))
22979 (defun org-goto-sibling (&optional previous)
22980 "Goto the next sibling, even if it is invisible.
22981 When PREVIOUS is set, go to the previous sibling instead. Returns t
22982 when a sibling was found. When none is found, return nil and don't
22983 move point."
22984 (let ((fun (if previous 're-search-backward 're-search-forward))
22985 (pos (point))
22986 (re org-outline-regexp-bol)
22987 level l)
22988 (when (condition-case nil (org-back-to-heading t) (error nil))
22989 (setq level (funcall outline-level))
22990 (catch 'exit
22991 (or previous (forward-char 1))
22992 (while (funcall fun re nil t)
22993 (setq l (funcall outline-level))
22994 (when (< l level) (goto-char pos) (throw 'exit nil))
22995 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22996 (goto-char pos)
22997 nil))))
22999 (defun org-show-siblings ()
23000 "Show all siblings of the current headline."
23001 (save-excursion
23002 (while (org-goto-sibling) (org-flag-heading nil)))
23003 (save-excursion
23004 (while (org-goto-sibling 'previous)
23005 (org-flag-heading nil))))
23007 (defun org-goto-first-child ()
23008 "Goto the first child, even if it is invisible.
23009 Return t when a child was found. Otherwise don't move point and
23010 return nil."
23011 (let (level (pos (point)) (re org-outline-regexp-bol))
23012 (when (condition-case nil (org-back-to-heading t) (error nil))
23013 (setq level (outline-level))
23014 (forward-char 1)
23015 (if (and (re-search-forward re nil t) (> (outline-level) level))
23016 (progn (goto-char (match-beginning 0)) t)
23017 (goto-char pos) nil))))
23019 (defun org-show-hidden-entry ()
23020 "Show an entry where even the heading is hidden."
23021 (save-excursion
23022 (org-show-entry)))
23024 (defun org-flag-heading (flag &optional entry)
23025 "Flag the current heading. FLAG non-nil means make invisible.
23026 When ENTRY is non-nil, show the entire entry."
23027 (save-excursion
23028 (org-back-to-heading t)
23029 ;; Check if we should show the entire entry
23030 (if entry
23031 (progn
23032 (org-show-entry)
23033 (save-excursion
23034 (and (outline-next-heading)
23035 (org-flag-heading nil))))
23036 (outline-flag-region (max (point-min) (1- (point)))
23037 (save-excursion (outline-end-of-heading) (point))
23038 flag))))
23040 (defun org-get-next-sibling ()
23041 "Move to next heading of the same level, and return point.
23042 If there is no such heading, return nil.
23043 This is like outline-next-sibling, but invisible headings are ok."
23044 (let ((level (funcall outline-level)))
23045 (outline-next-heading)
23046 (while (and (not (eobp)) (> (funcall outline-level) level))
23047 (outline-next-heading))
23048 (if (or (eobp) (< (funcall outline-level) level))
23050 (point))))
23052 (defun org-get-last-sibling ()
23053 "Move to previous heading of the same level, and return point.
23054 If there is no such heading, return nil."
23055 (let ((opoint (point))
23056 (level (funcall outline-level)))
23057 (outline-previous-heading)
23058 (when (and (/= (point) opoint) (outline-on-heading-p t))
23059 (while (and (> (funcall outline-level) level)
23060 (not (bobp)))
23061 (outline-previous-heading))
23062 (if (< (funcall outline-level) level)
23064 (point)))))
23066 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23067 "Goto to the end of a subtree."
23068 ;; This contains an exact copy of the original function, but it uses
23069 ;; `org-back-to-heading', to make it work also in invisible
23070 ;; trees. And is uses an invisible-ok argument.
23071 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23072 ;; Furthermore, when used inside Org, finding the end of a large subtree
23073 ;; with many children and grandchildren etc, this can be much faster
23074 ;; than the outline version.
23075 (org-back-to-heading invisible-ok)
23076 (let ((first t)
23077 (level (funcall outline-level)))
23078 (if (and (derived-mode-p 'org-mode) (< level 1000))
23079 ;; A true heading (not a plain list item), in Org-mode
23080 ;; This means we can easily find the end by looking
23081 ;; only for the right number of stars. Using a regexp to do
23082 ;; this is so much faster than using a Lisp loop.
23083 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23084 (forward-char 1)
23085 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23086 ;; something else, do it the slow way
23087 (while (and (not (eobp))
23088 (or first (> (funcall outline-level) level)))
23089 (setq first nil)
23090 (outline-next-heading)))
23091 (unless to-heading
23092 (if (memq (preceding-char) '(?\n ?\^M))
23093 (progn
23094 ;; Go to end of line before heading
23095 (forward-char -1)
23096 (if (memq (preceding-char) '(?\n ?\^M))
23097 ;; leave blank line before heading
23098 (forward-char -1))))))
23099 (point))
23101 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23102 "Use Org version in org-mode, for dramatic speed-up."
23103 (if (derived-mode-p 'org-mode)
23104 (progn
23105 (org-end-of-subtree nil t)
23106 (unless (eobp) (backward-char 1)))
23107 ad-do-it))
23109 (defun org-end-of-meta-data-and-drawers ()
23110 "Jump to the first text after meta data and drawers in the current entry.
23111 This will move over empty lines, lines with planning time stamps,
23112 clocking lines, and drawers."
23113 (org-back-to-heading t)
23114 (let ((end (save-excursion (outline-next-heading) (point)))
23115 (re (concat "\\(" org-drawer-regexp "\\)"
23116 "\\|" "[ \t]*" org-keyword-time-regexp)))
23117 (forward-line 1)
23118 (while (re-search-forward re end t)
23119 (if (not (match-end 1))
23120 ;; empty or planning line
23121 (forward-line 1)
23122 ;; a drawer, find the end
23123 (re-search-forward "^[ \t]*:END:" end 'move)
23124 (forward-line 1)))
23125 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23126 (point)))
23128 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23129 "Move forward to the ARG'th subheading at same level as this one.
23130 Stop at the first and last subheadings of a superior heading.
23131 Normally this only looks at visible headings, but when INVISIBLE-OK is
23132 non-nil it will also look at invisible ones."
23133 (interactive "p")
23134 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23135 (if (and arg (< arg 0))
23136 (goto-char (point-min))
23137 (outline-next-heading))
23138 (org-at-heading-p)
23139 (let ((level (- (match-end 0) (match-beginning 0) 1))
23140 (f (if (and arg (< arg 0))
23141 're-search-backward
23142 're-search-forward))
23143 (count (if arg (abs arg) 1))
23144 (result (point)))
23145 (while (and (prog1 (> count 0)
23146 (forward-char (if (and arg (< arg 0)) -1 1)))
23147 (funcall f org-outline-regexp-bol nil 'move))
23148 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23149 (cond ((< l level) (setq count 0))
23150 ((and (= l level)
23151 (or invisible-ok
23152 (progn
23153 (goto-char (line-beginning-position))
23154 (not (outline-invisible-p)))))
23155 (setq count (1- count))
23156 (when (eq l level)
23157 (setq result (point)))))))
23158 (goto-char result))
23159 (beginning-of-line 1)))
23161 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23162 "Move backward to the ARG'th subheading at same level as this one.
23163 Stop at the first and last subheadings of a superior heading."
23164 (interactive "p")
23165 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23167 (defun org-next-block (arg &optional backward block-regexp)
23168 "Jump to the next block.
23169 With a prefix argument ARG, jump forward ARG many source blocks.
23170 When BACKWARD is non-nil, jump to the previous block.
23171 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23172 (interactive "p")
23173 (let ((re (or block-regexp org-block-regexp))
23174 (re-search-fn (or (and backward 're-search-backward)
23175 're-search-forward)))
23176 (if (looking-at re) (forward-char 1))
23177 (condition-case nil
23178 (funcall re-search-fn re nil nil arg)
23179 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23180 (goto-char (match-beginning 0)) (org-show-context)))
23182 (defun org-previous-block (arg &optional block-regexp)
23183 "Jump to the previous block.
23184 With a prefix argument ARG, jump backward ARG many source blocks.
23185 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23186 (interactive "p")
23187 (org-next-block arg t block-regexp))
23189 (defun org-forward-element ()
23190 "Move forward by one element.
23191 Move to the next element at the same level, when possible."
23192 (interactive)
23193 (cond ((eobp) (user-error "Cannot move further down"))
23194 ((org-with-limited-levels (org-at-heading-p))
23195 (let ((origin (point)))
23196 (goto-char (org-end-of-subtree nil t))
23197 (unless (org-with-limited-levels (org-at-heading-p))
23198 (goto-char origin)
23199 (user-error "Cannot move further down"))))
23201 (let* ((elem (org-element-at-point))
23202 (end (org-element-property :end elem))
23203 (parent (org-element-property :parent elem)))
23204 (if (and parent (= (org-element-property :contents-end parent) end))
23205 (goto-char (org-element-property :end parent))
23206 (goto-char end))))))
23208 (defun org-backward-element ()
23209 "Move backward by one element.
23210 Move to the previous element at the same level, when possible."
23211 (interactive)
23212 (cond ((bobp) (user-error "Cannot move further up"))
23213 ((org-with-limited-levels (org-at-heading-p))
23214 ;; At a headline, move to the previous one, if any, or stay
23215 ;; here.
23216 (let ((origin (point)))
23217 (org-with-limited-levels (org-backward-heading-same-level 1))
23218 ;; When current headline has no sibling above, move to its
23219 ;; parent.
23220 (when (= (point) origin)
23221 (or (org-with-limited-levels (org-up-heading-safe))
23222 (progn (goto-char origin)
23223 (user-error "Cannot move further up"))))))
23225 (let* ((trail (org-element-at-point 'keep-trail))
23226 (elem (car trail))
23227 (prev-elem (nth 1 trail))
23228 (beg (org-element-property :begin elem)))
23229 (cond
23230 ;; Move to beginning of current element if point isn't
23231 ;; there already.
23232 ((/= (point) beg) (goto-char beg))
23233 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23234 ((org-before-first-heading-p) (goto-char (point-min)))
23235 (t (org-back-to-heading)))))))
23237 (defun org-up-element ()
23238 "Move to upper element."
23239 (interactive)
23240 (if (org-with-limited-levels (org-at-heading-p))
23241 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23242 (let* ((elem (org-element-at-point))
23243 (parent (org-element-property :parent elem)))
23244 (if parent (goto-char (org-element-property :begin parent))
23245 (if (org-with-limited-levels (org-before-first-heading-p))
23246 (user-error "No surrounding element")
23247 (org-with-limited-levels (org-back-to-heading)))))))
23249 (defvar org-element-greater-elements)
23250 (defun org-down-element ()
23251 "Move to inner element."
23252 (interactive)
23253 (let ((element (org-element-at-point)))
23254 (cond
23255 ((memq (org-element-type element) '(plain-list table))
23256 (goto-char (org-element-property :contents-begin element))
23257 (forward-char))
23258 ((memq (org-element-type element) org-element-greater-elements)
23259 ;; If contents are hidden, first disclose them.
23260 (when (org-element-property :hiddenp element) (org-cycle))
23261 (goto-char (or (org-element-property :contents-begin element)
23262 (user-error "No content for this element"))))
23263 (t (user-error "No inner element")))))
23265 (defun org-drag-element-backward ()
23266 "Move backward element at point."
23267 (interactive)
23268 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23269 (let* ((trail (org-element-at-point 'keep-trail))
23270 (elem (car trail))
23271 (prev-elem (nth 1 trail)))
23272 ;; Error out if no previous element or previous element is
23273 ;; a parent of the current one.
23274 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23275 (user-error "Cannot drag element backward")
23276 (let ((pos (point)))
23277 (org-element-swap-A-B prev-elem elem)
23278 (goto-char (+ (org-element-property :begin prev-elem)
23279 (- pos (org-element-property :begin elem)))))))))
23281 (defun org-drag-element-forward ()
23282 "Move forward element at point."
23283 (interactive)
23284 (let* ((pos (point))
23285 (elem (org-element-at-point)))
23286 (when (= (point-max) (org-element-property :end elem))
23287 (user-error "Cannot drag element forward"))
23288 (goto-char (org-element-property :end elem))
23289 (let ((next-elem (org-element-at-point)))
23290 (when (or (org-element-nested-p elem next-elem)
23291 (and (eq (org-element-type next-elem) 'headline)
23292 (not (eq (org-element-type elem) 'headline))))
23293 (goto-char pos)
23294 (user-error "Cannot drag element forward"))
23295 ;; Compute new position of point: it's shifted by NEXT-ELEM
23296 ;; body's length (without final blanks) and by the length of
23297 ;; blanks between ELEM and NEXT-ELEM.
23298 (let ((size-next (- (save-excursion
23299 (goto-char (org-element-property :end next-elem))
23300 (skip-chars-backward " \r\t\n")
23301 (forward-line)
23302 ;; Small correction if buffer doesn't end
23303 ;; with a newline character.
23304 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23305 (org-element-property :begin next-elem)))
23306 (size-blank (- (org-element-property :end elem)
23307 (save-excursion
23308 (goto-char (org-element-property :end elem))
23309 (skip-chars-backward " \r\t\n")
23310 (forward-line)
23311 (point)))))
23312 (org-element-swap-A-B elem next-elem)
23313 (goto-char (+ pos size-next size-blank))))))
23315 (defun org-drag-line-forward (arg)
23316 "Drag the line at point ARG lines forward."
23317 (interactive "p")
23318 (dotimes (n (abs arg))
23319 (let ((c (current-column)))
23320 (if (< 0 arg)
23321 (progn
23322 (beginning-of-line 2)
23323 (transpose-lines 1)
23324 (beginning-of-line 0))
23325 (transpose-lines 1)
23326 (beginning-of-line -1))
23327 (org-move-to-column c))))
23329 (defun org-drag-line-backward (arg)
23330 "Drag the line at point ARG lines backward."
23331 (interactive "p")
23332 (org-drag-line-forward (- arg)))
23334 (defun org-mark-element ()
23335 "Put point at beginning of this element, mark at end.
23337 Interactively, if this command is repeated or (in Transient Mark
23338 mode) if the mark is active, it marks the next element after the
23339 ones already marked."
23340 (interactive)
23341 (let (deactivate-mark)
23342 (if (and (org-called-interactively-p 'any)
23343 (or (and (eq last-command this-command) (mark t))
23344 (and transient-mark-mode mark-active)))
23345 (set-mark
23346 (save-excursion
23347 (goto-char (mark))
23348 (goto-char (org-element-property :end (org-element-at-point)))))
23349 (let ((element (org-element-at-point)))
23350 (end-of-line)
23351 (push-mark (org-element-property :end element) t t)
23352 (goto-char (org-element-property :begin element))))))
23354 (defun org-narrow-to-element ()
23355 "Narrow buffer to current element."
23356 (interactive)
23357 (let ((elem (org-element-at-point)))
23358 (cond
23359 ((eq (car elem) 'headline)
23360 (narrow-to-region
23361 (org-element-property :begin elem)
23362 (org-element-property :end elem)))
23363 ((memq (car elem) org-element-greater-elements)
23364 (narrow-to-region
23365 (org-element-property :contents-begin elem)
23366 (org-element-property :contents-end elem)))
23368 (narrow-to-region
23369 (org-element-property :begin elem)
23370 (org-element-property :end elem))))))
23372 (defun org-transpose-element ()
23373 "Transpose current and previous elements, keeping blank lines between.
23374 Point is moved after both elements."
23375 (interactive)
23376 (org-skip-whitespace)
23377 (let ((end (org-element-property :end (org-element-at-point))))
23378 (org-drag-element-backward)
23379 (goto-char end)))
23381 (defun org-unindent-buffer ()
23382 "Un-indent the visible part of the buffer.
23383 Relative indentation (between items, inside blocks, etc.) isn't
23384 modified."
23385 (interactive)
23386 (unless (eq major-mode 'org-mode)
23387 (user-error "Cannot un-indent a buffer not in Org mode"))
23388 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23389 unindent-tree ; For byte-compiler.
23390 (unindent-tree
23391 (function
23392 (lambda (contents)
23393 (mapc
23394 (lambda (element)
23395 (if (memq (org-element-type element) '(headline section))
23396 (funcall unindent-tree (org-element-contents element))
23397 (save-excursion
23398 (save-restriction
23399 (narrow-to-region
23400 (org-element-property :begin element)
23401 (org-element-property :end element))
23402 (org-do-remove-indentation)))))
23403 (reverse contents))))))
23404 (funcall unindent-tree (org-element-contents parse-tree))))
23406 (defun org-show-subtree ()
23407 "Show everything after this heading at deeper levels."
23408 (interactive)
23409 (outline-flag-region
23410 (point)
23411 (save-excursion
23412 (org-end-of-subtree t t))
23413 nil))
23415 (defun org-show-entry ()
23416 "Show the body directly following this heading.
23417 Show the heading too, if it is currently invisible."
23418 (interactive)
23419 (save-excursion
23420 (condition-case nil
23421 (progn
23422 (org-back-to-heading t)
23423 (outline-flag-region
23424 (max (point-min) (1- (point)))
23425 (save-excursion
23426 (if (re-search-forward
23427 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23428 (match-beginning 1)
23429 (point-max)))
23430 nil)
23431 (org-cycle-hide-drawers 'children))
23432 (error nil))))
23434 (defun org-make-options-regexp (kwds &optional extra)
23435 "Make a regular expression for keyword lines."
23436 (concat
23437 "^#\\+\\("
23438 (mapconcat 'regexp-quote kwds "\\|")
23439 (if extra (concat "\\|" extra))
23440 "\\):[ \t]*\\(.*\\)"))
23442 ;; Make isearch reveal the necessary context
23443 (defun org-isearch-end ()
23444 "Reveal context after isearch exits."
23445 (when isearch-success ; only if search was successful
23446 (if (featurep 'xemacs)
23447 ;; Under XEmacs, the hook is run in the correct place,
23448 ;; we directly show the context.
23449 (org-show-context 'isearch)
23450 ;; In Emacs the hook runs *before* restoring the overlays.
23451 ;; So we have to use a one-time post-command-hook to do this.
23452 ;; (Emacs 22 has a special variable, see function `org-mode')
23453 (unless (and (boundp 'isearch-mode-end-hook-quit)
23454 isearch-mode-end-hook-quit)
23455 ;; Only when the isearch was not quitted.
23456 (org-add-hook 'post-command-hook 'org-isearch-post-command
23457 'append 'local)))
23458 (org-fix-ellipsis-at-bol)))
23460 (defun org-isearch-post-command ()
23461 "Remove self from hook, and show context."
23462 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23463 (org-show-context 'isearch))
23466 ;;;; Integration with and fixes for other packages
23468 ;;; Imenu support
23470 (defvar org-imenu-markers nil
23471 "All markers currently used by Imenu.")
23472 (make-variable-buffer-local 'org-imenu-markers)
23474 (defun org-imenu-new-marker (&optional pos)
23475 "Return a new marker for use by Imenu, and remember the marker."
23476 (let ((m (make-marker)))
23477 (move-marker m (or pos (point)))
23478 (push m org-imenu-markers)
23481 (defun org-imenu-get-tree ()
23482 "Produce the index for Imenu."
23483 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23484 (setq org-imenu-markers nil)
23485 (let* ((n org-imenu-depth)
23486 (re (concat "^" (org-get-limited-outline-regexp)))
23487 (subs (make-vector (1+ n) nil))
23488 (last-level 0)
23489 m level head0 head)
23490 (save-excursion
23491 (save-restriction
23492 (widen)
23493 (goto-char (point-max))
23494 (while (re-search-backward re nil t)
23495 (setq level (org-reduced-level (funcall outline-level)))
23496 (when (and (<= level n)
23497 (looking-at org-complex-heading-regexp)
23498 (setq head0 (org-match-string-no-properties 4)))
23499 (setq head (org-link-display-format head0)
23500 m (org-imenu-new-marker))
23501 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23502 (if (>= level last-level)
23503 (push (cons head m) (aref subs level))
23504 (push (cons head (aref subs (1+ level))) (aref subs level))
23505 (loop for i from (1+ level) to n do (aset subs i nil)))
23506 (setq last-level level)))))
23507 (aref subs 1)))
23509 (eval-after-load "imenu"
23510 '(progn
23511 (add-hook 'imenu-after-jump-hook
23512 (lambda ()
23513 (if (derived-mode-p 'org-mode)
23514 (org-show-context 'org-goto))))))
23516 (defun org-link-display-format (link)
23517 "Replace a link with its the description.
23518 If there is no description, use the link target."
23519 (save-match-data
23520 (if (string-match org-bracket-link-analytic-regexp link)
23521 (replace-match (if (match-end 5)
23522 (match-string 5 link)
23523 (concat (match-string 1 link)
23524 (match-string 3 link)))
23525 nil t link)
23526 link)))
23528 (defun org-toggle-link-display ()
23529 "Toggle the literal or descriptive display of links."
23530 (interactive)
23531 (if org-descriptive-links
23532 (progn (org-remove-from-invisibility-spec '(org-link))
23533 (org-restart-font-lock)
23534 (setq org-descriptive-links nil))
23535 (progn (add-to-invisibility-spec '(org-link))
23536 (org-restart-font-lock)
23537 (setq org-descriptive-links t))))
23539 ;; Speedbar support
23541 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23542 "Overlay marking the agenda restriction line in speedbar.")
23543 (overlay-put org-speedbar-restriction-lock-overlay
23544 'face 'org-agenda-restriction-lock)
23545 (overlay-put org-speedbar-restriction-lock-overlay
23546 'help-echo "Agendas are currently limited to this item.")
23547 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23549 (defun org-speedbar-set-agenda-restriction ()
23550 "Restrict future agenda commands to the location at point in speedbar.
23551 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23552 (interactive)
23553 (require 'org-agenda)
23554 (let (p m tp np dir txt)
23555 (cond
23556 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23557 'org-imenu t))
23558 (setq m (get-text-property p 'org-imenu-marker))
23559 (with-current-buffer (marker-buffer m)
23560 (goto-char m)
23561 (org-agenda-set-restriction-lock 'subtree)))
23562 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23563 'speedbar-function 'speedbar-find-file))
23564 (setq tp (previous-single-property-change
23565 (1+ p) 'speedbar-function)
23566 np (next-single-property-change
23567 tp 'speedbar-function)
23568 dir (speedbar-line-directory)
23569 txt (buffer-substring-no-properties (or tp (point-min))
23570 (or np (point-max))))
23571 (with-current-buffer (find-file-noselect
23572 (let ((default-directory dir))
23573 (expand-file-name txt)))
23574 (unless (derived-mode-p 'org-mode)
23575 (user-error "Cannot restrict to non-Org-mode file"))
23576 (org-agenda-set-restriction-lock 'file)))
23577 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23578 (move-overlay org-speedbar-restriction-lock-overlay
23579 (point-at-bol) (point-at-eol))
23580 (setq current-prefix-arg nil)
23581 (org-agenda-maybe-redo)))
23583 (eval-after-load "speedbar"
23584 '(progn
23585 (speedbar-add-supported-extension ".org")
23586 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23587 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23588 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23589 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23590 (add-hook 'speedbar-visiting-tag-hook
23591 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23593 ;;; Fixes and Hacks for problems with other packages
23595 ;; Make flyspell not check words in links, to not mess up our keymap
23596 (defvar org-element-affiliated-keywords) ; From org-element.el
23597 (defvar org-element-block-name-alist) ; From org-element.el
23598 (defun org-mode-flyspell-verify ()
23599 "Don't let flyspell put overlays at active buttons, or on
23600 {todo,all-time,additional-option-like}-keywords."
23601 (require 'org-element) ; For `org-element-affiliated-keywords'
23602 (let ((pos (max (1- (point)) (point-min)))
23603 (word (thing-at-point 'word)))
23604 (and (not (get-text-property pos 'keymap))
23605 (not (get-text-property pos 'org-no-flyspell))
23606 (not (member word org-todo-keywords-1))
23607 (not (member word org-all-time-keywords))
23608 (not (member word org-options-keywords))
23609 (not (member word (mapcar 'car org-startup-options)))
23610 (not (member-ignore-case word org-element-affiliated-keywords))
23611 (not (member-ignore-case word (org-get-export-keywords)))
23612 (not (member-ignore-case
23613 word (mapcar 'car org-element-block-name-alist)))
23614 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23615 (not (org-in-src-block-p)))))
23617 (defun org-remove-flyspell-overlays-in (beg end)
23618 "Remove flyspell overlays in region."
23619 (and (org-bound-and-true-p flyspell-mode)
23620 (fboundp 'flyspell-delete-region-overlays)
23621 (flyspell-delete-region-overlays beg end))
23622 (add-text-properties beg end '(org-no-flyspell t)))
23624 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23625 (eval-after-load "bookmark"
23626 '(if (boundp 'bookmark-after-jump-hook)
23627 ;; We can use the hook
23628 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23629 ;; Hook not available, use advice
23630 (defadvice bookmark-jump (after org-make-visible activate)
23631 "Make the position visible."
23632 (org-bookmark-jump-unhide))))
23634 ;; Make sure saveplace shows the location if it was hidden
23635 (eval-after-load "saveplace"
23636 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23637 "Make the position visible."
23638 (org-bookmark-jump-unhide)))
23640 ;; Make sure ecb shows the location if it was hidden
23641 (eval-after-load "ecb"
23642 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23643 "Make hierarchy visible when jumping into location from ECB tree buffer."
23644 (if (derived-mode-p 'org-mode)
23645 (org-show-context))))
23647 (defun org-bookmark-jump-unhide ()
23648 "Unhide the current position, to show the bookmark location."
23649 (and (derived-mode-p 'org-mode)
23650 (or (outline-invisible-p)
23651 (save-excursion (goto-char (max (point-min) (1- (point))))
23652 (outline-invisible-p)))
23653 (org-show-context 'bookmark-jump)))
23655 ;; Make session.el ignore our circular variable
23656 (eval-after-load "session"
23657 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23659 ;;;; Finish up
23661 (provide 'org)
23663 (run-hooks 'org-load-hook)
23665 ;;; org.el ends here