Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobb1a2fa8f57759e763964ddcd145cbb2aa6230a9e
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 (declare-function org-export-backend-name "ox" (backend))
442 (defcustom org-export-backends '(ascii html icalendar latex)
443 "List of export back-ends that should be always available.
445 If a description starts with <C>, the file is not part of Emacs
446 and loading it will require that you have downloaded and properly
447 installed the Org mode distribution.
449 Unlike to `org-modules', libraries in this list will not be
450 loaded along with Org, but only once the export framework is
451 needed.
453 This variable needs to be set before org.el is loaded. If you
454 need to make a change while Emacs is running, use the customize
455 interface or run the following code, where VAL stands for the new
456 value of the variable, after updating it:
458 \(progn
459 \(setq org-export--registered-backends
460 \(org-remove-if-not
461 \(lambda (backend)
462 \(let ((name (org-export-backend-name backend)))
463 \(or (memq name val)
464 \(catch 'parentp
465 \(dolist (b val)
466 \(and (org-export-derived-backend-p b name)
467 \(throw 'parentp t)))))))
468 org-export--registered-backends))
469 \(let ((new-list (mapcar 'org-export-backend-name
470 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 'org-export-backends 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 (let ((name (org-export-backend-name backend)))
495 (or (memq name val)
496 (catch 'parentp
497 (dolist (b val)
498 (and (org-export-derived-backend-p b name)
499 (throw 'parentp t)))))))
500 org-export--registered-backends))
501 ;; Now build NEW-LIST of both new back-ends and required
502 ;; parents.
503 (let ((new-list (mapcar 'org-export-backend-name
504 org-export--registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defcustom org-bookmark-names-plist
1036 '(:last-capture "org-capture-last-stored"
1037 :last-refile "org-refile-last-stored"
1038 :last-capture-marker "org-capture-last-stored-marker")
1039 "Names for bookmarks automatically set by some Org commands.
1040 This can provide strings as names for a number of bookmakrs Org sets
1041 automatically. The following keys are currently implemented:
1042 :last-capture
1043 :last-capture-marker
1044 :last-refile
1045 When a key does not show up in the property list, the corresponding bookmark
1046 is not set."
1047 :group 'org-structure
1048 :type 'plist)
1050 (defgroup org-cycle nil
1051 "Options concerning visibility cycling in Org-mode."
1052 :tag "Org Cycle"
1053 :group 'org-structure)
1055 (defcustom org-cycle-skip-children-state-if-no-children t
1056 "Non-nil means skip CHILDREN state in entries that don't have any."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-max-level nil
1061 "Maximum level which should still be subject to visibility cycling.
1062 Levels higher than this will, for cycling, be treated as text, not a headline.
1063 When `org-odd-levels-only' is set, a value of N in this variable actually
1064 means 2N-1 stars as the limiting headline.
1065 When nil, cycle all levels.
1066 Note that the limiting level of cycling is also influenced by
1067 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1068 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1069 than its value."
1070 :group 'org-cycle
1071 :type '(choice
1072 (const :tag "No limit" nil)
1073 (integer :tag "Maximum level")))
1075 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1076 "Names of drawers. Drawers are not opened by cycling on the headline above.
1077 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1078 this:
1079 :DRAWERNAME:
1080 .....
1081 :END:
1082 The drawer \"PROPERTIES\" is special for capturing properties through
1083 the property API.
1085 Drawers can be defined on the per-file basis with a line like:
1087 #+DRAWERS: HIDDEN STATE PROPERTIES"
1088 :group 'org-structure
1089 :group 'org-cycle
1090 :type '(repeat (string :tag "Drawer Name")))
1092 (defcustom org-hide-block-startup nil
1093 "Non-nil means entering Org-mode will fold all blocks.
1094 This can also be set in on a per-file basis with
1096 #+STARTUP: hideblocks
1097 #+STARTUP: showblocks"
1098 :group 'org-startup
1099 :group 'org-cycle
1100 :type 'boolean)
1102 (defcustom org-cycle-global-at-bob nil
1103 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1104 This makes it possible to do global cycling without having to use S-TAB or
1105 \\[universal-argument] TAB. For this special case to work, the first line
1106 of the buffer must not be a headline -- it may be empty or some other text.
1107 When used in this way, `org-cycle-hook' is disabled temporarily to make
1108 sure the cursor stays at the beginning of the buffer. When this option is
1109 nil, don't do anything special at the beginning of the buffer."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-level-after-item/entry-creation t
1114 "Non-nil means cycle entry level or item indentation in new empty entries.
1116 When the cursor is at the end of an empty headline, i.e., with only stars
1117 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1118 and then all possible ancestor states, before returning to the original state.
1119 This makes data entry extremely fast: M-RET to create a new headline,
1120 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1122 When the cursor is at the end of an empty plain list item, one TAB will
1123 make it a subitem, two or more tabs will back up to make this an item
1124 higher up in the item hierarchy."
1125 :group 'org-cycle
1126 :type 'boolean)
1128 (defcustom org-cycle-emulate-tab t
1129 "Where should `org-cycle' emulate TAB.
1130 nil Never
1131 white Only in completely white lines
1132 whitestart Only at the beginning of lines, before the first non-white char
1133 t Everywhere except in headlines
1134 exc-hl-bol Everywhere except at the start of a headline
1135 If TAB is used in a place where it does not emulate TAB, the current subtree
1136 visibility is cycled."
1137 :group 'org-cycle
1138 :type '(choice (const :tag "Never" nil)
1139 (const :tag "Only in completely white lines" white)
1140 (const :tag "Before first char in a line" whitestart)
1141 (const :tag "Everywhere except in headlines" t)
1142 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1144 (defcustom org-cycle-separator-lines 2
1145 "Number of empty lines needed to keep an empty line between collapsed trees.
1146 If you leave an empty line between the end of a subtree and the following
1147 headline, this empty line is hidden when the subtree is folded.
1148 Org-mode will leave (exactly) one empty line visible if the number of
1149 empty lines is equal or larger to the number given in this variable.
1150 So the default 2 means at least 2 empty lines after the end of a subtree
1151 are needed to produce free space between a collapsed subtree and the
1152 following headline.
1154 If the number is negative, and the number of empty lines is at least -N,
1155 all empty lines are shown.
1157 Special case: when 0, never leave empty lines in collapsed view."
1158 :group 'org-cycle
1159 :type 'integer)
1160 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1162 (defcustom org-pre-cycle-hook nil
1163 "Hook that is run before visibility cycling is happening.
1164 The function(s) in this hook must accept a single argument which indicates
1165 the new state that will be set right after running this hook. The
1166 argument is a symbol. Before a global state change, it can have the values
1167 `overview', `content', or `all'. Before a local state change, it can have
1168 the values `folded', `children', or `subtree'."
1169 :group 'org-cycle
1170 :type 'hook)
1172 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1173 org-cycle-hide-drawers
1174 org-cycle-hide-inline-tasks
1175 org-cycle-show-empty-lines
1176 org-optimize-window-after-visibility-change)
1177 "Hook that is run after `org-cycle' has changed the buffer visibility.
1178 The function(s) in this hook must accept a single argument which indicates
1179 the new state that was set by the most recent `org-cycle' command. The
1180 argument is a symbol. After a global state change, it can have the values
1181 `overview', `contents', or `all'. After a local state change, it can have
1182 the values `folded', `children', or `subtree'."
1183 :group 'org-cycle
1184 :type 'hook)
1186 (defgroup org-edit-structure nil
1187 "Options concerning structure editing in Org-mode."
1188 :tag "Org Edit Structure"
1189 :group 'org-structure)
1191 (defcustom org-odd-levels-only nil
1192 "Non-nil means skip even levels and only use odd levels for the outline.
1193 This has the effect that two stars are being added/taken away in
1194 promotion/demotion commands. It also influences how levels are
1195 handled by the exporters.
1196 Changing it requires restart of `font-lock-mode' to become effective
1197 for fontification also in regions already fontified.
1198 You may also set this on a per-file basis by adding one of the following
1199 lines to the buffer:
1201 #+STARTUP: odd
1202 #+STARTUP: oddeven"
1203 :group 'org-edit-structure
1204 :group 'org-appearance
1205 :type 'boolean)
1207 (defcustom org-adapt-indentation t
1208 "Non-nil means adapt indentation to outline node level.
1210 When this variable is set, Org assumes that you write outlines by
1211 indenting text in each node to align with the headline (after the stars).
1212 The following issues are influenced by this variable:
1214 - When this is set and the *entire* text in an entry is indented, the
1215 indentation is increased by one space in a demotion command, and
1216 decreased by one in a promotion command. If any line in the entry
1217 body starts with text at column 0, indentation is not changed at all.
1219 - Property drawers and planning information is inserted indented when
1220 this variable s set. When nil, they will not be indented.
1222 - TAB indents a line relative to context. The lines below a headline
1223 will be indented when this variable is set.
1225 Note that this is all about true indentation, by adding and removing
1226 space characters. See also `org-indent.el' which does level-dependent
1227 indentation in a virtual way, i.e. at display time in Emacs."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-special-ctrl-a/e nil
1232 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1234 When t, `C-a' will bring back the cursor to the beginning of the
1235 headline text, i.e. after the stars and after a possible TODO
1236 keyword. In an item, this will be the position after bullet and
1237 check-box, if any. When the cursor is already at that position,
1238 another `C-a' will bring it to the beginning of the line.
1240 `C-e' will jump to the end of the headline, ignoring the presence
1241 of tags in the headline. A second `C-e' will then jump to the
1242 true end of the line, after any tags. This also means that, when
1243 this variable is non-nil, `C-e' also will never jump beyond the
1244 end of the heading of a folded section, i.e. not after the
1245 ellipses.
1247 When set to the symbol `reversed', the first `C-a' or `C-e' works
1248 normally, going to the true line boundary first. Only a directly
1249 following, identical keypress will bring the cursor to the
1250 special positions.
1252 This may also be a cons cell where the behavior for `C-a' and
1253 `C-e' is set separately."
1254 :group 'org-edit-structure
1255 :type '(choice
1256 (const :tag "off" nil)
1257 (const :tag "on: after stars/bullet and before tags first" t)
1258 (const :tag "reversed: true line boundary first" reversed)
1259 (cons :tag "Set C-a and C-e separately"
1260 (choice :tag "Special C-a"
1261 (const :tag "off" nil)
1262 (const :tag "on: after stars/bullet first" t)
1263 (const :tag "reversed: before stars/bullet first" reversed))
1264 (choice :tag "Special C-e"
1265 (const :tag "off" nil)
1266 (const :tag "on: before tags first" t)
1267 (const :tag "reversed: after tags first" reversed)))))
1268 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1270 (defcustom org-special-ctrl-k nil
1271 "Non-nil means `C-k' will behave specially in headlines.
1272 When nil, `C-k' will call the default `kill-line' command.
1273 When t, the following will happen while the cursor is in the headline:
1275 - When the cursor is at the beginning of a headline, kill the entire
1276 line and possible the folded subtree below the line.
1277 - When in the middle of the headline text, kill the headline up to the tags.
1278 - When after the headline text, kill the tags."
1279 :group 'org-edit-structure
1280 :type 'boolean)
1282 (defcustom org-ctrl-k-protect-subtree nil
1283 "Non-nil means, do not delete a hidden subtree with C-k.
1284 When set to the symbol `error', simply throw an error when C-k is
1285 used to kill (part-of) a headline that has hidden text behind it.
1286 Any other non-nil value will result in a query to the user, if it is
1287 OK to kill that hidden subtree. When nil, kill without remorse."
1288 :group 'org-edit-structure
1289 :version "24.1"
1290 :type '(choice
1291 (const :tag "Do not protect hidden subtrees" nil)
1292 (const :tag "Protect hidden subtrees with a security query" t)
1293 (const :tag "Never kill a hidden subtree with C-k" error)))
1295 (defcustom org-catch-invisible-edits nil
1296 "Check if in invisible region before inserting or deleting a character.
1297 Valid values are:
1299 nil Do not check, so just do invisible edits.
1300 error Throw an error and do nothing.
1301 show Make point visible, and do the requested edit.
1302 show-and-error Make point visible, then throw an error and abort the edit.
1303 smart Make point visible, and do insertion/deletion if it is
1304 adjacent to visible text and the change feels predictable.
1305 Never delete a previously invisible character or add in the
1306 middle or right after an invisible region. Basically, this
1307 allows insertion and backward-delete right before ellipses.
1308 FIXME: maybe in this case we should not even show?"
1309 :group 'org-edit-structure
1310 :version "24.1"
1311 :type '(choice
1312 (const :tag "Do not check" nil)
1313 (const :tag "Throw error when trying to edit" error)
1314 (const :tag "Unhide, but do not do the edit" show-and-error)
1315 (const :tag "Show invisible part and do the edit" show)
1316 (const :tag "Be smart and do the right thing" smart)))
1318 (defcustom org-yank-folded-subtrees t
1319 "Non-nil means when yanking subtrees, fold them.
1320 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1321 it starts with a heading and all other headings in it are either children
1322 or siblings, then fold all the subtrees. However, do this only if no
1323 text after the yank would be swallowed into a folded tree by this action."
1324 :group 'org-edit-structure
1325 :type 'boolean)
1327 (defcustom org-yank-adjusted-subtrees nil
1328 "Non-nil means when yanking subtrees, adjust the level.
1329 With this setting, `org-paste-subtree' is used to insert the subtree, see
1330 this function for details."
1331 :group 'org-edit-structure
1332 :type 'boolean)
1334 (defcustom org-M-RET-may-split-line '((default . t))
1335 "Non-nil means M-RET will split the line at the cursor position.
1336 When nil, it will go to the end of the line before making a
1337 new line.
1338 You may also set this option in a different way for different
1339 contexts. Valid contexts are:
1341 headline when creating a new headline
1342 item when creating a new item
1343 table in a table field
1344 default the value to be used for all contexts not explicitly
1345 customized"
1346 :group 'org-structure
1347 :group 'org-table
1348 :type '(choice
1349 (const :tag "Always" t)
1350 (const :tag "Never" nil)
1351 (repeat :greedy t :tag "Individual contexts"
1352 (cons
1353 (choice :tag "Context"
1354 (const headline)
1355 (const item)
1356 (const table)
1357 (const default))
1358 (boolean)))))
1361 (defcustom org-insert-heading-respect-content nil
1362 "Non-nil means insert new headings after the current subtree.
1363 When nil, the new heading is created directly after the current line.
1364 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1365 this variable on for the duration of the command."
1366 :group 'org-structure
1367 :type 'boolean)
1369 (defcustom org-blank-before-new-entry '((heading . auto)
1370 (plain-list-item . auto))
1371 "Should `org-insert-heading' leave a blank line before new heading/item?
1372 The value is an alist, with `heading' and `plain-list-item' as CAR,
1373 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1374 which case Org will look at the surrounding headings/items and try to
1375 make an intelligent decision whether to insert a blank line or not.
1377 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1378 the setting here is ignored and no empty line is inserted to avoid breaking
1379 the list structure."
1380 :group 'org-edit-structure
1381 :type '(list
1382 (cons (const heading)
1383 (choice (const :tag "Never" nil)
1384 (const :tag "Always" t)
1385 (const :tag "Auto" auto)))
1386 (cons (const plain-list-item)
1387 (choice (const :tag "Never" nil)
1388 (const :tag "Always" t)
1389 (const :tag "Auto" auto)))))
1391 (defcustom org-insert-heading-hook nil
1392 "Hook being run after inserting a new heading."
1393 :group 'org-edit-structure
1394 :type 'hook)
1396 (defcustom org-enable-fixed-width-editor t
1397 "Non-nil means lines starting with \":\" are treated as fixed-width.
1398 This currently only means they are never auto-wrapped.
1399 When nil, such lines will be treated like ordinary lines.
1400 See also the QUOTE keyword."
1401 :group 'org-edit-structure
1402 :type 'boolean)
1404 (defcustom org-goto-auto-isearch t
1405 "Non-nil means typing characters in `org-goto' starts incremental search.
1406 When nil, you can use these keybindings to navigate the buffer:
1408 q Quit the org-goto interface
1409 n Go to the next visible heading
1410 p Go to the previous visible heading
1411 f Go one heading forward on same level
1412 b Go one heading backward on same level
1413 u Go one heading up"
1414 :group 'org-edit-structure
1415 :type 'boolean)
1417 (defgroup org-sparse-trees nil
1418 "Options concerning sparse trees in Org-mode."
1419 :tag "Org Sparse Trees"
1420 :group 'org-structure)
1422 (defcustom org-highlight-sparse-tree-matches t
1423 "Non-nil means highlight all matches that define a sparse tree.
1424 The highlights will automatically disappear the next time the buffer is
1425 changed by an edit command."
1426 :group 'org-sparse-trees
1427 :type 'boolean)
1429 (defcustom org-remove-highlights-with-change t
1430 "Non-nil means any change to the buffer will remove temporary highlights.
1431 Such highlights are created by `org-occur' and `org-clock-display'.
1432 When nil, `C-c C-c needs to be used to get rid of the highlights.
1433 The highlights created by `org-preview-latex-fragment' always need
1434 `C-c C-c' to be removed."
1435 :group 'org-sparse-trees
1436 :group 'org-time
1437 :type 'boolean)
1440 (defcustom org-occur-hook '(org-first-headline-recenter)
1441 "Hook that is run after `org-occur' has constructed a sparse tree.
1442 This can be used to recenter the window to show as much of the structure
1443 as possible."
1444 :group 'org-sparse-trees
1445 :type 'hook)
1447 (defgroup org-imenu-and-speedbar nil
1448 "Options concerning imenu and speedbar in Org-mode."
1449 :tag "Org Imenu and Speedbar"
1450 :group 'org-structure)
1452 (defcustom org-imenu-depth 2
1453 "The maximum level for Imenu access to Org-mode headlines.
1454 This also applied for speedbar access."
1455 :group 'org-imenu-and-speedbar
1456 :type 'integer)
1458 (defgroup org-table nil
1459 "Options concerning tables in Org-mode."
1460 :tag "Org Table"
1461 :group 'org)
1463 (defcustom org-enable-table-editor 'optimized
1464 "Non-nil means lines starting with \"|\" are handled by the table editor.
1465 When nil, such lines will be treated like ordinary lines.
1467 When equal to the symbol `optimized', the table editor will be optimized to
1468 do the following:
1469 - Automatic overwrite mode in front of whitespace in table fields.
1470 This makes the structure of the table stay in tact as long as the edited
1471 field does not exceed the column width.
1472 - Minimize the number of realigns. Normally, the table is aligned each time
1473 TAB or RET are pressed to move to another field. With optimization this
1474 happens only if changes to a field might have changed the column width.
1475 Optimization requires replacing the functions `self-insert-command',
1476 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1477 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1478 very good at guessing when a re-align will be necessary, but you can always
1479 force one with \\[org-ctrl-c-ctrl-c].
1481 If you would like to use the optimized version in Org-mode, but the
1482 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1484 This variable can be used to turn on and off the table editor during a session,
1485 but in order to toggle optimization, a restart is required.
1487 See also the variable `org-table-auto-blank-field'."
1488 :group 'org-table
1489 :type '(choice
1490 (const :tag "off" nil)
1491 (const :tag "on" t)
1492 (const :tag "on, optimized" optimized)))
1494 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1495 (version<= emacs-version "24.1"))
1496 "Non-nil means cluster self-insert commands for undo when possible.
1497 If this is set, then, like in the Emacs command loop, 20 consecutive
1498 characters will be undone together.
1499 This is configurable, because there is some impact on typing performance."
1500 :group 'org-table
1501 :type 'boolean)
1503 (defcustom org-table-tab-recognizes-table.el t
1504 "Non-nil means TAB will automatically notice a table.el table.
1505 When it sees such a table, it moves point into it and - if necessary -
1506 calls `table-recognize-table'."
1507 :group 'org-table-editing
1508 :type 'boolean)
1510 (defgroup org-link nil
1511 "Options concerning links in Org-mode."
1512 :tag "Org Link"
1513 :group 'org)
1515 (defvar org-link-abbrev-alist-local nil
1516 "Buffer-local version of `org-link-abbrev-alist', which see.
1517 The value of this is taken from the #+LINK lines.")
1518 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1520 (defcustom org-link-abbrev-alist nil
1521 "Alist of link abbreviations.
1522 The car of each element is a string, to be replaced at the start of a link.
1523 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1524 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1526 [[linkkey:tag][description]]
1528 The 'linkkey' must be a word word, starting with a letter, followed
1529 by letters, numbers, '-' or '_'.
1531 If REPLACE is a string, the tag will simply be appended to create the link.
1532 If the string contains \"%s\", the tag will be inserted there. If the string
1533 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1534 at that point (see the function `url-hexify-string'). If the string contains
1535 the specifier \"%(my-function)\", then the custom function `my-function' will
1536 be invoked: this function takes the tag as its only argument and must return
1537 a string.
1539 REPLACE may also be a function that will be called with the tag as the
1540 only argument to create the link, which should be returned as a string.
1542 See the manual for examples."
1543 :group 'org-link
1544 :type '(repeat
1545 (cons
1546 (string :tag "Protocol")
1547 (choice
1548 (string :tag "Format")
1549 (function)))))
1551 (defcustom org-descriptive-links t
1552 "Non-nil means Org will display descriptive links.
1553 E.g. [[http://orgmode.org][Org website]] will be displayed as
1554 \"Org Website\", hiding the link itself and just displaying its
1555 description. When set to `nil', Org will display the full links
1556 literally.
1558 You can interactively set the value of this variable by calling
1559 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1560 :group 'org-link
1561 :type 'boolean)
1563 (defcustom org-link-file-path-type 'adaptive
1564 "How the path name in file links should be stored.
1565 Valid values are:
1567 relative Relative to the current directory, i.e. the directory of the file
1568 into which the link is being inserted.
1569 absolute Absolute path, if possible with ~ for home directory.
1570 noabbrev Absolute path, no abbreviation of home directory.
1571 adaptive Use relative path for files in the current directory and sub-
1572 directories of it. For other files, use an absolute path."
1573 :group 'org-link
1574 :type '(choice
1575 (const relative)
1576 (const absolute)
1577 (const noabbrev)
1578 (const adaptive)))
1580 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1581 "Types of links that should be activated in Org-mode files.
1582 This is a list of symbols, each leading to the activation of a certain link
1583 type. In principle, it does not hurt to turn on most link types - there may
1584 be a small gain when turning off unused link types. The types are:
1586 bracket The recommended [[link][description]] or [[link]] links with hiding.
1587 angle Links in angular brackets that may contain whitespace like
1588 <bbdb:Carsten Dominik>.
1589 plain Plain links in normal text, no whitespace, like http://google.com.
1590 radio Text that is matched by a radio target, see manual for details.
1591 tag Tag settings in a headline (link to tag search).
1592 date Time stamps (link to calendar).
1593 footnote Footnote labels.
1595 Changing this variable requires a restart of Emacs to become effective."
1596 :group 'org-link
1597 :type '(set :greedy t
1598 (const :tag "Double bracket links" bracket)
1599 (const :tag "Angular bracket links" angle)
1600 (const :tag "Plain text links" plain)
1601 (const :tag "Radio target matches" radio)
1602 (const :tag "Tags" tag)
1603 (const :tag "Timestamps" date)
1604 (const :tag "Footnotes" footnote)))
1606 (defcustom org-make-link-description-function nil
1607 "Function to use for generating link descriptions from links.
1608 When nil, the link location will be used. This function must take
1609 two parameters: the first one is the link, the second one is the
1610 description generated by `org-insert-link'. The function should
1611 return the description to use."
1612 :group 'org-link
1613 :type '(choice (const nil) (function)))
1615 (defgroup org-link-store nil
1616 "Options concerning storing links in Org-mode."
1617 :tag "Org Store Link"
1618 :group 'org-link)
1620 (defcustom org-url-hexify-p t
1621 "When non-nil, hexify URL when creating a link."
1622 :type 'boolean
1623 :version "24.3"
1624 :group 'org-link-store)
1626 (defcustom org-email-link-description-format "Email %c: %.30s"
1627 "Format of the description part of a link to an email or usenet message.
1628 The following %-escapes will be replaced by corresponding information:
1630 %F full \"From\" field
1631 %f name, taken from \"From\" field, address if no name
1632 %T full \"To\" field
1633 %t first name in \"To\" field, address if no name
1634 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1635 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1636 %s subject
1637 %d date
1638 %m message-id.
1640 You may use normal field width specification between the % and the letter.
1641 This is for example useful to limit the length of the subject.
1643 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1644 :group 'org-link-store
1645 :type 'string)
1647 (defcustom org-from-is-user-regexp
1648 (let (r1 r2)
1649 (when (and user-mail-address (not (string= user-mail-address "")))
1650 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1651 (when (and user-full-name (not (string= user-full-name "")))
1652 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1653 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1654 "Regexp matched against the \"From:\" header of an email or usenet message.
1655 It should match if the message is from the user him/herself."
1656 :group 'org-link-store
1657 :type 'regexp)
1659 (defcustom org-context-in-file-links t
1660 "Non-nil means file links from `org-store-link' contain context.
1661 A search string will be added to the file name with :: as separator and
1662 used to find the context when the link is activated by the command
1663 `org-open-at-point'. When this option is t, the entire active region
1664 will be placed in the search string of the file link. If set to a
1665 positive integer, only the first n lines of context will be stored.
1667 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1668 negates this setting for the duration of the command."
1669 :group 'org-link-store
1670 :type '(choice boolean integer))
1672 (defcustom org-keep-stored-link-after-insertion nil
1673 "Non-nil means keep link in list for entire session.
1675 The command `org-store-link' adds a link pointing to the current
1676 location to an internal list. These links accumulate during a session.
1677 The command `org-insert-link' can be used to insert links into any
1678 Org-mode file (offering completion for all stored links). When this
1679 option is nil, every link which has been inserted once using \\[org-insert-link]
1680 will be removed from the list, to make completing the unused links
1681 more efficient."
1682 :group 'org-link-store
1683 :type 'boolean)
1685 (defgroup org-link-follow nil
1686 "Options concerning following links in Org-mode."
1687 :tag "Org Follow Link"
1688 :group 'org-link)
1690 (defcustom org-link-translation-function nil
1691 "Function to translate links with different syntax to Org syntax.
1692 This can be used to translate links created for example by the Planner
1693 or emacs-wiki packages to Org syntax.
1694 The function must accept two parameters, a TYPE containing the link
1695 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1696 which is everything after the link protocol. It should return a cons
1697 with possibly modified values of type and path.
1698 Org contains a function for this, so if you set this variable to
1699 `org-translate-link-from-planner', you should be able follow many
1700 links created by planner."
1701 :group 'org-link-follow
1702 :type '(choice (const nil) (function)))
1704 (defcustom org-follow-link-hook nil
1705 "Hook that is run after a link has been followed."
1706 :group 'org-link-follow
1707 :type 'hook)
1709 (defcustom org-tab-follows-link nil
1710 "Non-nil means on links TAB will follow the link.
1711 Needs to be set before org.el is loaded.
1712 This really should not be used, it does not make sense, and the
1713 implementation is bad."
1714 :group 'org-link-follow
1715 :type 'boolean)
1717 (defcustom org-return-follows-link nil
1718 "Non-nil means on links RET will follow the link.
1719 In tables, the special behavior of RET has precedence."
1720 :group 'org-link-follow
1721 :type 'boolean)
1723 (defcustom org-mouse-1-follows-link
1724 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1725 "Non-nil means mouse-1 on a link will follow the link.
1726 A longer mouse click will still set point. Does not work on XEmacs.
1727 Needs to be set before org.el is loaded."
1728 :group 'org-link-follow
1729 :type 'boolean)
1731 (defcustom org-mark-ring-length 4
1732 "Number of different positions to be recorded in the ring.
1733 Changing this requires a restart of Emacs to work correctly."
1734 :group 'org-link-follow
1735 :type 'integer)
1737 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1738 "Non-nil means internal links in Org files must exactly match a headline.
1739 When nil, the link search tries to match a phrase with all words
1740 in the search text."
1741 :group 'org-link-follow
1742 :version "24.1"
1743 :type '(choice
1744 (const :tag "Use fuzzy text search" nil)
1745 (const :tag "Match only exact headline" t)
1746 (const :tag "Match exact headline or query to create it"
1747 query-to-create)))
1749 (defcustom org-link-frame-setup
1750 '((vm . vm-visit-folder-other-frame)
1751 (vm-imap . vm-visit-imap-folder-other-frame)
1752 (gnus . org-gnus-no-new-news)
1753 (file . find-file-other-window)
1754 (wl . wl-other-frame))
1755 "Setup the frame configuration for following links.
1756 When following a link with Emacs, it may often be useful to display
1757 this link in another window or frame. This variable can be used to
1758 set this up for the different types of links.
1759 For VM, use any of
1760 `vm-visit-folder'
1761 `vm-visit-folder-other-window'
1762 `vm-visit-folder-other-frame'
1763 For Gnus, use any of
1764 `gnus'
1765 `gnus-other-frame'
1766 `org-gnus-no-new-news'
1767 For FILE, use any of
1768 `find-file'
1769 `find-file-other-window'
1770 `find-file-other-frame'
1771 For Wanderlust use any of
1772 `wl'
1773 `wl-other-frame'
1774 For the calendar, use the variable `calendar-setup'.
1775 For BBDB, it is currently only possible to display the matches in
1776 another window."
1777 :group 'org-link-follow
1778 :type '(list
1779 (cons (const vm)
1780 (choice
1781 (const vm-visit-folder)
1782 (const vm-visit-folder-other-window)
1783 (const vm-visit-folder-other-frame)))
1784 (cons (const vm-imap)
1785 (choice
1786 (const vm-visit-imap-folder)
1787 (const vm-visit-imap-folder-other-window)
1788 (const vm-visit-imap-folder-other-frame)))
1789 (cons (const gnus)
1790 (choice
1791 (const gnus)
1792 (const gnus-other-frame)
1793 (const org-gnus-no-new-news)))
1794 (cons (const file)
1795 (choice
1796 (const find-file)
1797 (const find-file-other-window)
1798 (const find-file-other-frame)))
1799 (cons (const wl)
1800 (choice
1801 (const wl)
1802 (const wl-other-frame)))))
1804 (defcustom org-display-internal-link-with-indirect-buffer nil
1805 "Non-nil means use indirect buffer to display infile links.
1806 Activating internal links (from one location in a file to another location
1807 in the same file) normally just jumps to the location. When the link is
1808 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1809 is displayed in
1810 another window. When this option is set, the other window actually displays
1811 an indirect buffer clone of the current buffer, to avoid any visibility
1812 changes to the current buffer."
1813 :group 'org-link-follow
1814 :type 'boolean)
1816 (defcustom org-open-non-existing-files nil
1817 "Non-nil means `org-open-file' will open non-existing files.
1818 When nil, an error will be generated.
1819 This variable applies only to external applications because they
1820 might choke on non-existing files. If the link is to a file that
1821 will be opened in Emacs, the variable is ignored."
1822 :group 'org-link-follow
1823 :type 'boolean)
1825 (defcustom org-open-directory-means-index-dot-org nil
1826 "Non-nil means a link to a directory really means to index.org.
1827 When nil, following a directory link will run dired or open a finder/explorer
1828 window on that directory."
1829 :group 'org-link-follow
1830 :type 'boolean)
1832 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1833 "Function and arguments to call for following mailto links.
1834 This is a list with the first element being a Lisp function, and the
1835 remaining elements being arguments to the function. In string arguments,
1836 %a will be replaced by the address, and %s will be replaced by the subject
1837 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1838 :group 'org-link-follow
1839 :type '(choice
1840 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1841 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1842 (const :tag "message-mail" (message-mail "%a" "%s"))
1843 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1845 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1846 "Non-nil means ask for confirmation before executing shell links.
1847 Shell links can be dangerous: just think about a link
1849 [[shell:rm -rf ~/*][Google Search]]
1851 This link would show up in your Org-mode document as \"Google Search\",
1852 but really it would remove your entire home directory.
1853 Therefore we advise against setting this variable to nil.
1854 Just change it to `y-or-n-p' if you want to confirm with a
1855 single keystroke rather than having to type \"yes\"."
1856 :group 'org-link-follow
1857 :type '(choice
1858 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1859 (const :tag "with y-or-n (faster)" y-or-n-p)
1860 (const :tag "no confirmation (dangerous)" nil)))
1861 (put 'org-confirm-shell-link-function
1862 'safe-local-variable
1863 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1865 (defcustom org-confirm-shell-link-not-regexp ""
1866 "A regexp to skip confirmation for shell links."
1867 :group 'org-link-follow
1868 :version "24.1"
1869 :type 'regexp)
1871 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1872 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1873 Elisp links can be dangerous: just think about a link
1875 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1877 This link would show up in your Org-mode document as \"Google Search\",
1878 but really it would remove your entire home directory.
1879 Therefore we advise against setting this variable to nil.
1880 Just change it to `y-or-n-p' if you want to confirm with a
1881 single keystroke rather than having to type \"yes\"."
1882 :group 'org-link-follow
1883 :type '(choice
1884 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1885 (const :tag "with y-or-n (faster)" y-or-n-p)
1886 (const :tag "no confirmation (dangerous)" nil)))
1887 (put 'org-confirm-shell-link-function
1888 'safe-local-variable
1889 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1891 (defcustom org-confirm-elisp-link-not-regexp ""
1892 "A regexp to skip confirmation for Elisp links."
1893 :group 'org-link-follow
1894 :version "24.1"
1895 :type 'regexp)
1897 (defconst org-file-apps-defaults-gnu
1898 '((remote . emacs)
1899 (system . mailcap)
1900 (t . mailcap))
1901 "Default file applications on a UNIX or GNU/Linux system.
1902 See `org-file-apps'.")
1904 (defconst org-file-apps-defaults-macosx
1905 '((remote . emacs)
1906 (t . "open %s")
1907 (system . "open %s")
1908 ("ps.gz" . "gv %s")
1909 ("eps.gz" . "gv %s")
1910 ("dvi" . "xdvi %s")
1911 ("fig" . "xfig %s"))
1912 "Default file applications on a MacOS X system.
1913 The system \"open\" is known as a default, but we use X11 applications
1914 for some files for which the OS does not have a good default.
1915 See `org-file-apps'.")
1917 (defconst org-file-apps-defaults-windowsnt
1918 (list
1919 '(remote . emacs)
1920 (cons t
1921 (list (if (featurep 'xemacs)
1922 'mswindows-shell-execute
1923 'w32-shell-execute)
1924 "open" 'file))
1925 (cons 'system
1926 (list (if (featurep 'xemacs)
1927 'mswindows-shell-execute
1928 'w32-shell-execute)
1929 "open" 'file)))
1930 "Default file applications on a Windows NT system.
1931 The system \"open\" is used for most files.
1932 See `org-file-apps'.")
1934 (defcustom org-file-apps
1935 '((auto-mode . emacs)
1936 ("\\.mm\\'" . default)
1937 ("\\.x?html?\\'" . default)
1938 ("\\.pdf\\'" . default))
1939 "External applications for opening `file:path' items in a document.
1940 Org-mode uses system defaults for different file types, but
1941 you can use this variable to set the application for a given file
1942 extension. The entries in this list are cons cells where the car identifies
1943 files and the cdr the corresponding command. Possible values for the
1944 file identifier are
1945 \"string\" A string as a file identifier can be interpreted in different
1946 ways, depending on its contents:
1948 - Alphanumeric characters only:
1949 Match links with this file extension.
1950 Example: (\"pdf\" . \"evince %s\")
1951 to open PDFs with evince.
1953 - Regular expression: Match links where the
1954 filename matches the regexp. If you want to
1955 use groups here, use shy groups.
1957 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1958 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1959 to open *.html and *.xhtml with firefox.
1961 - Regular expression which contains (non-shy) groups:
1962 Match links where the whole link, including \"::\", and
1963 anything after that, matches the regexp.
1964 In a custom command string, %1, %2, etc. are replaced with
1965 the parts of the link that were matched by the groups.
1966 For backwards compatibility, if a command string is given
1967 that does not use any of the group matches, this case is
1968 handled identically to the second one (i.e. match against
1969 file name only).
1970 In a custom lisp form, you can access the group matches with
1971 (match-string n link).
1973 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1974 to open [[file:document.pdf::5]] with evince at page 5.
1976 `directory' Matches a directory
1977 `remote' Matches a remote file, accessible through tramp or efs.
1978 Remote files most likely should be visited through Emacs
1979 because external applications cannot handle such paths.
1980 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1981 so all files Emacs knows how to handle. Using this with
1982 command `emacs' will open most files in Emacs. Beware that this
1983 will also open html files inside Emacs, unless you add
1984 (\"html\" . default) to the list as well.
1985 t Default for files not matched by any of the other options.
1986 `system' The system command to open files, like `open' on Windows
1987 and Mac OS X, and mailcap under GNU/Linux. This is the command
1988 that will be selected if you call `C-c C-o' with a double
1989 \\[universal-argument] \\[universal-argument] prefix.
1991 Possible values for the command are:
1992 `emacs' The file will be visited by the current Emacs process.
1993 `default' Use the default application for this file type, which is the
1994 association for t in the list, most likely in the system-specific
1995 part.
1996 This can be used to overrule an unwanted setting in the
1997 system-specific variable.
1998 `system' Use the system command for opening files, like \"open\".
1999 This command is specified by the entry whose car is `system'.
2000 Most likely, the system-specific version of this variable
2001 does define this command, but you can overrule/replace it
2002 here.
2003 string A command to be executed by a shell; %s will be replaced
2004 by the path to the file.
2005 sexp A Lisp form which will be evaluated. The file path will
2006 be available in the Lisp variable `file'.
2007 For more examples, see the system specific constants
2008 `org-file-apps-defaults-macosx'
2009 `org-file-apps-defaults-windowsnt'
2010 `org-file-apps-defaults-gnu'."
2011 :group 'org-link-follow
2012 :type '(repeat
2013 (cons (choice :value ""
2014 (string :tag "Extension")
2015 (const :tag "System command to open files" system)
2016 (const :tag "Default for unrecognized files" t)
2017 (const :tag "Remote file" remote)
2018 (const :tag "Links to a directory" directory)
2019 (const :tag "Any files that have Emacs modes"
2020 auto-mode))
2021 (choice :value ""
2022 (const :tag "Visit with Emacs" emacs)
2023 (const :tag "Use default" default)
2024 (const :tag "Use the system command" system)
2025 (string :tag "Command")
2026 (sexp :tag "Lisp form")))))
2028 (defcustom org-doi-server-url "http://dx.doi.org/"
2029 "The URL of the DOI server."
2030 :type 'string
2031 :version "24.3"
2032 :group 'org-link-follow)
2034 (defgroup org-refile nil
2035 "Options concerning refiling entries in Org-mode."
2036 :tag "Org Refile"
2037 :group 'org)
2039 (defcustom org-directory "~/org"
2040 "Directory with org files.
2041 This is just a default location to look for Org files. There is no need
2042 at all to put your files into this directory. It is only used in the
2043 following situations:
2045 1. When a capture template specifies a target file that is not an
2046 absolute path. The path will then be interpreted relative to
2047 `org-directory'
2048 2. When a capture note is filed away in an interactive way (when exiting the
2049 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2050 with `org-directory' as the default path."
2051 :group 'org-refile
2052 :group 'org-remember
2053 :group 'org-capture
2054 :type 'directory)
2056 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2057 "Default target for storing notes.
2058 Used as a fall back file for org-remember.el and org-capture.el, for
2059 templates that do not specify a target file."
2060 :group 'org-refile
2061 :group 'org-remember
2062 :group 'org-capture
2063 :type '(choice
2064 (const :tag "Default from remember-data-file" nil)
2065 file))
2067 (defcustom org-goto-interface 'outline
2068 "The default interface to be used for `org-goto'.
2069 Allowed values are:
2070 outline The interface shows an outline of the relevant file
2071 and the correct heading is found by moving through
2072 the outline or by searching with incremental search.
2073 outline-path-completion Headlines in the current buffer are offered via
2074 completion. This is the interface also used by
2075 the refile command."
2076 :group 'org-refile
2077 :type '(choice
2078 (const :tag "Outline" outline)
2079 (const :tag "Outline-path-completion" outline-path-completion)))
2081 (defcustom org-goto-max-level 5
2082 "Maximum target level when running `org-goto' with refile interface."
2083 :group 'org-refile
2084 :type 'integer)
2086 (defcustom org-reverse-note-order nil
2087 "Non-nil means store new notes at the beginning of a file or entry.
2088 When nil, new notes will be filed to the end of a file or entry.
2089 This can also be a list with cons cells of regular expressions that
2090 are matched against file names, and values."
2091 :group 'org-remember
2092 :group 'org-capture
2093 :group 'org-refile
2094 :type '(choice
2095 (const :tag "Reverse always" t)
2096 (const :tag "Reverse never" nil)
2097 (repeat :tag "By file name regexp"
2098 (cons regexp boolean))))
2100 (defcustom org-log-refile nil
2101 "Information to record when a task is refiled.
2103 Possible values are:
2105 nil Don't add anything
2106 time Add a time stamp to the task
2107 note Prompt for a note and add it with template `org-log-note-headings'
2109 This option can also be set with on a per-file-basis with
2111 #+STARTUP: nologrefile
2112 #+STARTUP: logrefile
2113 #+STARTUP: lognoterefile
2115 You can have local logging settings for a subtree by setting the LOGGING
2116 property to one or more of these keywords.
2118 When bulk-refiling from the agenda, the value `note' is forbidden and
2119 will temporarily be changed to `time'."
2120 :group 'org-refile
2121 :group 'org-progress
2122 :version "24.1"
2123 :type '(choice
2124 (const :tag "No logging" nil)
2125 (const :tag "Record timestamp" time)
2126 (const :tag "Record timestamp with note." note)))
2128 (defcustom org-refile-targets nil
2129 "Targets for refiling entries with \\[org-refile].
2130 This is a list of cons cells. Each cell contains:
2131 - a specification of the files to be considered, either a list of files,
2132 or a symbol whose function or variable value will be used to retrieve
2133 a file name or a list of file names. If you use `org-agenda-files' for
2134 that, all agenda files will be scanned for targets. Nil means consider
2135 headings in the current buffer.
2136 - A specification of how to find candidate refile targets. This may be
2137 any of:
2138 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2139 This tag has to be present in all target headlines, inheritance will
2140 not be considered.
2141 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2142 todo keyword.
2143 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2144 headlines that are refiling targets.
2145 - a cons cell (:level . N). Any headline of level N is considered a target.
2146 Note that, when `org-odd-levels-only' is set, level corresponds to
2147 order in hierarchy, not to the number of stars.
2148 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2149 Note that, when `org-odd-levels-only' is set, level corresponds to
2150 order in hierarchy, not to the number of stars.
2152 Each element of this list generates a set of possible targets.
2153 The union of these sets is presented (with completion) to
2154 the user by `org-refile'.
2156 You can set the variable `org-refile-target-verify-function' to a function
2157 to verify each headline found by the simple criteria above.
2159 When this variable is nil, all top-level headlines in the current buffer
2160 are used, equivalent to the value `((nil . (:level . 1))'."
2161 :group 'org-refile
2162 :type '(repeat
2163 (cons
2164 (choice :value org-agenda-files
2165 (const :tag "All agenda files" org-agenda-files)
2166 (const :tag "Current buffer" nil)
2167 (function) (variable) (file))
2168 (choice :tag "Identify target headline by"
2169 (cons :tag "Specific tag" (const :value :tag) (string))
2170 (cons :tag "TODO keyword" (const :value :todo) (string))
2171 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2172 (cons :tag "Level number" (const :value :level) (integer))
2173 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2175 (defcustom org-refile-target-verify-function nil
2176 "Function to verify if the headline at point should be a refile target.
2177 The function will be called without arguments, with point at the
2178 beginning of the headline. It should return t and leave point
2179 where it is if the headline is a valid target for refiling.
2181 If the target should not be selected, the function must return nil.
2182 In addition to this, it may move point to a place from where the search
2183 should be continued. For example, the function may decide that the entire
2184 subtree of the current entry should be excluded and move point to the end
2185 of the subtree."
2186 :group 'org-refile
2187 :type '(choice
2188 (const nil)
2189 (function)))
2191 (defcustom org-refile-use-cache nil
2192 "Non-nil means cache refile targets to speed up the process.
2193 The cache for a particular file will be updated automatically when
2194 the buffer has been killed, or when any of the marker used for flagging
2195 refile targets no longer points at a live buffer.
2196 If you have added new entries to a buffer that might themselves be targets,
2197 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2198 find that easier, `C-u C-u C-u C-c C-w'."
2199 :group 'org-refile
2200 :version "24.1"
2201 :type 'boolean)
2203 (defcustom org-refile-use-outline-path nil
2204 "Non-nil means provide refile targets as paths.
2205 So a level 3 headline will be available as level1/level2/level3.
2207 When the value is `file', also include the file name (without directory)
2208 into the path. In this case, you can also stop the completion after
2209 the file name, to get entries inserted as top level in the file.
2211 When `full-file-path', include the full file path."
2212 :group 'org-refile
2213 :type '(choice
2214 (const :tag "Not" nil)
2215 (const :tag "Yes" t)
2216 (const :tag "Start with file name" file)
2217 (const :tag "Start with full file path" full-file-path)))
2219 (defcustom org-outline-path-complete-in-steps t
2220 "Non-nil means complete the outline path in hierarchical steps.
2221 When Org-mode uses the refile interface to select an outline path
2222 \(see variable `org-refile-use-outline-path'), the completion of
2223 the path can be done is a single go, or if can be done in steps down
2224 the headline hierarchy. Going in steps is probably the best if you
2225 do not use a special completion package like `ido' or `icicles'.
2226 However, when using these packages, going in one step can be very
2227 fast, while still showing the whole path to the entry."
2228 :group 'org-refile
2229 :type 'boolean)
2231 (defcustom org-refile-allow-creating-parent-nodes nil
2232 "Non-nil means allow to create new nodes as refile targets.
2233 New nodes are then created by adding \"/new node name\" to the completion
2234 of an existing node. When the value of this variable is `confirm',
2235 new node creation must be confirmed by the user (recommended)
2236 When nil, the completion must match an existing entry.
2238 Note that, if the new heading is not seen by the criteria
2239 listed in `org-refile-targets', multiple instances of the same
2240 heading would be created by trying again to file under the new
2241 heading."
2242 :group 'org-refile
2243 :type '(choice
2244 (const :tag "Never" nil)
2245 (const :tag "Always" t)
2246 (const :tag "Prompt for confirmation" confirm)))
2248 (defcustom org-refile-active-region-within-subtree nil
2249 "Non-nil means also refile active region within a subtree.
2251 By default `org-refile' doesn't allow refiling regions if they
2252 don't contain a set of subtrees, but it might be convenient to
2253 do so sometimes: in that case, the first line of the region is
2254 converted to a headline before refiling."
2255 :group 'org-refile
2256 :version "24.1"
2257 :type 'boolean)
2259 (defgroup org-todo nil
2260 "Options concerning TODO items in Org-mode."
2261 :tag "Org TODO"
2262 :group 'org)
2264 (defgroup org-progress nil
2265 "Options concerning Progress logging in Org-mode."
2266 :tag "Org Progress"
2267 :group 'org-time)
2269 (defvar org-todo-interpretation-widgets
2270 '((:tag "Sequence (cycling hits every state)" sequence)
2271 (:tag "Type (cycling directly to DONE)" type))
2272 "The available interpretation symbols for customizing `org-todo-keywords'.
2273 Interested libraries should add to this list.")
2275 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2276 "List of TODO entry keyword sequences and their interpretation.
2277 \\<org-mode-map>This is a list of sequences.
2279 Each sequence starts with a symbol, either `sequence' or `type',
2280 indicating if the keywords should be interpreted as a sequence of
2281 action steps, or as different types of TODO items. The first
2282 keywords are states requiring action - these states will select a headline
2283 for inclusion into the global TODO list Org-mode produces. If one of
2284 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2285 signify that no further action is necessary. If \"|\" is not found,
2286 the last keyword is treated as the only DONE state of the sequence.
2288 The command \\[org-todo] cycles an entry through these states, and one
2289 additional state where no keyword is present. For details about this
2290 cycling, see the manual.
2292 TODO keywords and interpretation can also be set on a per-file basis with
2293 the special #+SEQ_TODO and #+TYP_TODO lines.
2295 Each keyword can optionally specify a character for fast state selection
2296 \(in combination with the variable `org-use-fast-todo-selection')
2297 and specifiers for state change logging, using the same syntax that
2298 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2299 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2300 indicates to record a time stamp each time this state is selected.
2302 Each keyword may also specify if a timestamp or a note should be
2303 recorded when entering or leaving the state, by adding additional
2304 characters in the parenthesis after the keyword. This looks like this:
2305 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2306 record only the time of the state change. With X and Y being either
2307 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2308 Y when leaving the state if and only if the *target* state does not
2309 define X. You may omit any of the fast-selection key or X or /Y,
2310 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2312 For backward compatibility, this variable may also be just a list
2313 of keywords. In this case the interpretation (sequence or type) will be
2314 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2315 :group 'org-todo
2316 :group 'org-keywords
2317 :type '(choice
2318 (repeat :tag "Old syntax, just keywords"
2319 (string :tag "Keyword"))
2320 (repeat :tag "New syntax"
2321 (cons
2322 (choice
2323 :tag "Interpretation"
2324 ;;Quick and dirty way to see
2325 ;;`org-todo-interpretations'. This takes the
2326 ;;place of item arguments
2327 :convert-widget
2328 (lambda (widget)
2329 (widget-put widget
2330 :args (mapcar
2331 #'(lambda (x)
2332 (widget-convert
2333 (cons 'const x)))
2334 org-todo-interpretation-widgets))
2335 widget))
2336 (repeat
2337 (string :tag "Keyword"))))))
2339 (defvar org-todo-keywords-1 nil
2340 "All TODO and DONE keywords active in a buffer.")
2341 (make-variable-buffer-local 'org-todo-keywords-1)
2342 (defvar org-todo-keywords-for-agenda nil)
2343 (defvar org-done-keywords-for-agenda nil)
2344 (defvar org-drawers-for-agenda nil)
2345 (defvar org-todo-keyword-alist-for-agenda nil)
2346 (defvar org-tag-alist-for-agenda nil
2347 "Alist of all tags from all agenda files.")
2348 (defvar org-tag-groups-alist-for-agenda nil
2349 "Alist of all groups tags from all current agenda files.")
2350 (defvar org-tag-groups-alist nil)
2351 (make-variable-buffer-local 'org-tag-groups-alist)
2352 (defvar org-agenda-contributing-files nil)
2353 (defvar org-not-done-keywords nil)
2354 (make-variable-buffer-local 'org-not-done-keywords)
2355 (defvar org-done-keywords nil)
2356 (make-variable-buffer-local 'org-done-keywords)
2357 (defvar org-todo-heads nil)
2358 (make-variable-buffer-local 'org-todo-heads)
2359 (defvar org-todo-sets nil)
2360 (make-variable-buffer-local 'org-todo-sets)
2361 (defvar org-todo-log-states nil)
2362 (make-variable-buffer-local 'org-todo-log-states)
2363 (defvar org-todo-kwd-alist nil)
2364 (make-variable-buffer-local 'org-todo-kwd-alist)
2365 (defvar org-todo-key-alist nil)
2366 (make-variable-buffer-local 'org-todo-key-alist)
2367 (defvar org-todo-key-trigger nil)
2368 (make-variable-buffer-local 'org-todo-key-trigger)
2370 (defcustom org-todo-interpretation 'sequence
2371 "Controls how TODO keywords are interpreted.
2372 This variable is in principle obsolete and is only used for
2373 backward compatibility, if the interpretation of todo keywords is
2374 not given already in `org-todo-keywords'. See that variable for
2375 more information."
2376 :group 'org-todo
2377 :group 'org-keywords
2378 :type '(choice (const sequence)
2379 (const type)))
2381 (defcustom org-use-fast-todo-selection t
2382 "Non-nil means use the fast todo selection scheme with C-c C-t.
2383 This variable describes if and under what circumstances the cycling
2384 mechanism for TODO keywords will be replaced by a single-key, direct
2385 selection scheme.
2387 When nil, fast selection is never used.
2389 When the symbol `prefix', it will be used when `org-todo' is called
2390 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2391 `C-u t' in an agenda buffer.
2393 When t, fast selection is used by default. In this case, the prefix
2394 argument forces cycling instead.
2396 In all cases, the special interface is only used if access keys have
2397 actually been assigned by the user, i.e. if keywords in the configuration
2398 are followed by a letter in parenthesis, like TODO(t)."
2399 :group 'org-todo
2400 :type '(choice
2401 (const :tag "Never" nil)
2402 (const :tag "By default" t)
2403 (const :tag "Only with C-u C-c C-t" prefix)))
2405 (defcustom org-provide-todo-statistics t
2406 "Non-nil means update todo statistics after insert and toggle.
2407 ALL-HEADLINES means update todo statistics by including headlines
2408 with no TODO keyword as well, counting them as not done.
2409 A list of TODO keywords means the same, but skip keywords that are
2410 not in this list.
2412 When this is set, todo statistics is updated in the parent of the
2413 current entry each time a todo state is changed."
2414 :group 'org-todo
2415 :type '(choice
2416 (const :tag "Yes, only for TODO entries" t)
2417 (const :tag "Yes, including all entries" 'all-headlines)
2418 (repeat :tag "Yes, for TODOs in this list"
2419 (string :tag "TODO keyword"))
2420 (other :tag "No TODO statistics" nil)))
2422 (defcustom org-hierarchical-todo-statistics t
2423 "Non-nil means TODO statistics covers just direct children.
2424 When nil, all entries in the subtree are considered.
2425 This has only an effect if `org-provide-todo-statistics' is set.
2426 To set this to nil for only a single subtree, use a COOKIE_DATA
2427 property and include the word \"recursive\" into the value."
2428 :group 'org-todo
2429 :type 'boolean)
2431 (defcustom org-after-todo-state-change-hook nil
2432 "Hook which is run after the state of a TODO item was changed.
2433 The new state (a string with a TODO keyword, or nil) is available in the
2434 Lisp variable `org-state'."
2435 :group 'org-todo
2436 :type 'hook)
2438 (defvar org-blocker-hook nil
2439 "Hook for functions that are allowed to block a state change.
2441 Functions in this hook should not modify the buffer.
2442 Each function gets as its single argument a property list,
2443 see `org-trigger-hook' for more information about this list.
2445 If any of the functions in this hook returns nil, the state change
2446 is blocked.")
2448 (defvar org-trigger-hook nil
2449 "Hook for functions that are triggered by a state change.
2451 Each function gets as its single argument a property list with at
2452 least the following elements:
2454 (:type type-of-change :position pos-at-entry-start
2455 :from old-state :to new-state)
2457 Depending on the type, more properties may be present.
2459 This mechanism is currently implemented for:
2461 TODO state changes
2462 ------------------
2463 :type todo-state-change
2464 :from previous state (keyword as a string), or nil, or a symbol
2465 'todo' or 'done', to indicate the general type of state.
2466 :to new state, like in :from")
2468 (defcustom org-enforce-todo-dependencies nil
2469 "Non-nil means undone TODO entries will block switching the parent to DONE.
2470 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2471 be blocked if any prior sibling is not yet done.
2472 Finally, if the parent is blocked because of ordered siblings of its own,
2473 the child will also be blocked."
2474 :set (lambda (var val)
2475 (set var val)
2476 (if val
2477 (add-hook 'org-blocker-hook
2478 'org-block-todo-from-children-or-siblings-or-parent)
2479 (remove-hook 'org-blocker-hook
2480 'org-block-todo-from-children-or-siblings-or-parent)))
2481 :group 'org-todo
2482 :type 'boolean)
2484 (defcustom org-enforce-todo-checkbox-dependencies nil
2485 "Non-nil means unchecked boxes will block switching the parent to DONE.
2486 When this is nil, checkboxes have no influence on switching TODO states.
2487 When non-nil, you first need to check off all check boxes before the TODO
2488 entry can be switched to DONE.
2489 This variable needs to be set before org.el is loaded, and you need to
2490 restart Emacs after a change to make the change effective. The only way
2491 to change is while Emacs is running is through the customize interface."
2492 :set (lambda (var val)
2493 (set var val)
2494 (if val
2495 (add-hook 'org-blocker-hook
2496 'org-block-todo-from-checkboxes)
2497 (remove-hook 'org-blocker-hook
2498 'org-block-todo-from-checkboxes)))
2499 :group 'org-todo
2500 :type 'boolean)
2502 (defcustom org-treat-insert-todo-heading-as-state-change nil
2503 "Non-nil means inserting a TODO heading is treated as state change.
2504 So when the command \\[org-insert-todo-heading] is used, state change
2505 logging will apply if appropriate. When nil, the new TODO item will
2506 be inserted directly, and no logging will take place."
2507 :group 'org-todo
2508 :type 'boolean)
2510 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2511 "Non-nil means switching TODO states with S-cursor counts as state change.
2512 This is the default behavior. However, setting this to nil allows a
2513 convenient way to select a TODO state and bypass any logging associated
2514 with that."
2515 :group 'org-todo
2516 :type 'boolean)
2518 (defcustom org-todo-state-tags-triggers nil
2519 "Tag changes that should be triggered by TODO state changes.
2520 This is a list. Each entry is
2522 (state-change (tag . flag) .......)
2524 State-change can be a string with a state, and empty string to indicate the
2525 state that has no TODO keyword, or it can be one of the symbols `todo'
2526 or `done', meaning any not-done or done state, respectively."
2527 :group 'org-todo
2528 :group 'org-tags
2529 :type '(repeat
2530 (cons (choice :tag "When changing to"
2531 (const :tag "Not-done state" todo)
2532 (const :tag "Done state" done)
2533 (string :tag "State"))
2534 (repeat
2535 (cons :tag "Tag action"
2536 (string :tag "Tag")
2537 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2539 (defcustom org-log-done nil
2540 "Information to record when a task moves to the DONE state.
2542 Possible values are:
2544 nil Don't add anything, just change the keyword
2545 time Add a time stamp to the task
2546 note Prompt for a note and add it with template `org-log-note-headings'
2548 This option can also be set with on a per-file-basis with
2550 #+STARTUP: nologdone
2551 #+STARTUP: logdone
2552 #+STARTUP: lognotedone
2554 You can have local logging settings for a subtree by setting the LOGGING
2555 property to one or more of these keywords."
2556 :group 'org-todo
2557 :group 'org-progress
2558 :type '(choice
2559 (const :tag "No logging" nil)
2560 (const :tag "Record CLOSED timestamp" time)
2561 (const :tag "Record CLOSED timestamp with note." note)))
2563 ;; Normalize old uses of org-log-done.
2564 (cond
2565 ((eq org-log-done t) (setq org-log-done 'time))
2566 ((and (listp org-log-done) (memq 'done org-log-done))
2567 (setq org-log-done 'note)))
2569 (defcustom org-log-reschedule nil
2570 "Information to record when the scheduling date of a tasks is modified.
2572 Possible values are:
2574 nil Don't add anything, just change the date
2575 time Add a time stamp to the task
2576 note Prompt for a note and add it with template `org-log-note-headings'
2578 This option can also be set with on a per-file-basis with
2580 #+STARTUP: nologreschedule
2581 #+STARTUP: logreschedule
2582 #+STARTUP: lognotereschedule"
2583 :group 'org-todo
2584 :group 'org-progress
2585 :type '(choice
2586 (const :tag "No logging" nil)
2587 (const :tag "Record timestamp" time)
2588 (const :tag "Record timestamp with note." note)))
2590 (defcustom org-log-redeadline nil
2591 "Information to record when the deadline date of a tasks is modified.
2593 Possible values are:
2595 nil Don't add anything, just change the date
2596 time Add a time stamp to the task
2597 note Prompt for a note and add it with template `org-log-note-headings'
2599 This option can also be set with on a per-file-basis with
2601 #+STARTUP: nologredeadline
2602 #+STARTUP: logredeadline
2603 #+STARTUP: lognoteredeadline
2605 You can have local logging settings for a subtree by setting the LOGGING
2606 property to one or more of these keywords."
2607 :group 'org-todo
2608 :group 'org-progress
2609 :type '(choice
2610 (const :tag "No logging" nil)
2611 (const :tag "Record timestamp" time)
2612 (const :tag "Record timestamp with note." note)))
2614 (defcustom org-log-note-clock-out nil
2615 "Non-nil means record a note when clocking out of an item.
2616 This can also be configured on a per-file basis by adding one of
2617 the following lines anywhere in the buffer:
2619 #+STARTUP: lognoteclock-out
2620 #+STARTUP: nolognoteclock-out"
2621 :group 'org-todo
2622 :group 'org-progress
2623 :type 'boolean)
2625 (defcustom org-log-done-with-time t
2626 "Non-nil means the CLOSED time stamp will contain date and time.
2627 When nil, only the date will be recorded."
2628 :group 'org-progress
2629 :type 'boolean)
2631 (defcustom org-log-note-headings
2632 '((done . "CLOSING NOTE %t")
2633 (state . "State %-12s from %-12S %t")
2634 (note . "Note taken on %t")
2635 (reschedule . "Rescheduled from %S on %t")
2636 (delschedule . "Not scheduled, was %S on %t")
2637 (redeadline . "New deadline from %S on %t")
2638 (deldeadline . "Removed deadline, was %S on %t")
2639 (refile . "Refiled on %t")
2640 (clock-out . ""))
2641 "Headings for notes added to entries.
2642 The value is an alist, with the car being a symbol indicating the note
2643 context, and the cdr is the heading to be used. The heading may also be the
2644 empty string.
2645 %t in the heading will be replaced by a time stamp.
2646 %T will be an active time stamp instead the default inactive one
2647 %d will be replaced by a short-format time stamp.
2648 %D will be replaced by an active short-format time stamp.
2649 %s will be replaced by the new TODO state, in double quotes.
2650 %S will be replaced by the old TODO state, in double quotes.
2651 %u will be replaced by the user name.
2652 %U will be replaced by the full user name.
2654 In fact, it is not a good idea to change the `state' entry, because
2655 agenda log mode depends on the format of these entries."
2656 :group 'org-todo
2657 :group 'org-progress
2658 :type '(list :greedy t
2659 (cons (const :tag "Heading when closing an item" done) string)
2660 (cons (const :tag
2661 "Heading when changing todo state (todo sequence only)"
2662 state) string)
2663 (cons (const :tag "Heading when just taking a note" note) string)
2664 (cons (const :tag "Heading when clocking out" clock-out) string)
2665 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2666 (cons (const :tag "Heading when rescheduling" reschedule) string)
2667 (cons (const :tag "Heading when changing deadline" redeadline) string)
2668 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2669 (cons (const :tag "Heading when refiling" refile) string)))
2671 (unless (assq 'note org-log-note-headings)
2672 (push '(note . "%t") org-log-note-headings))
2674 (defcustom org-log-into-drawer nil
2675 "Non-nil means insert state change notes and time stamps into a drawer.
2676 When nil, state changes notes will be inserted after the headline and
2677 any scheduling and clock lines, but not inside a drawer.
2679 The value of this variable should be the name of the drawer to use.
2680 LOGBOOK is proposed as the default drawer for this purpose, you can
2681 also set this to a string to define the drawer of your choice.
2683 A value of t is also allowed, representing \"LOGBOOK\".
2685 A value of t or nil can also be set with on a per-file-basis with
2687 #+STARTUP: logdrawer
2688 #+STARTUP: nologdrawer
2690 If this variable is set, `org-log-state-notes-insert-after-drawers'
2691 will be ignored.
2693 You can set the property LOG_INTO_DRAWER to overrule this setting for
2694 a subtree."
2695 :group 'org-todo
2696 :group 'org-progress
2697 :type '(choice
2698 (const :tag "Not into a drawer" nil)
2699 (const :tag "LOGBOOK" t)
2700 (string :tag "Other")))
2702 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2704 (defun org-log-into-drawer ()
2705 "Return the value of `org-log-into-drawer', but let properties overrule.
2706 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2707 used instead of the default value."
2708 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2709 (cond
2710 ((not p) org-log-into-drawer)
2711 ((equal p "nil") nil)
2712 ((equal p "t") "LOGBOOK")
2713 (t p))))
2715 (defcustom org-log-state-notes-insert-after-drawers nil
2716 "Non-nil means insert state change notes after any drawers in entry.
2717 Only the drawers that *immediately* follow the headline and the
2718 deadline/scheduled line are skipped.
2719 When nil, insert notes right after the heading and perhaps the line
2720 with deadline/scheduling if present.
2722 This variable will have no effect if `org-log-into-drawer' is
2723 set."
2724 :group 'org-todo
2725 :group 'org-progress
2726 :type 'boolean)
2728 (defcustom org-log-states-order-reversed t
2729 "Non-nil means the latest state note will be directly after heading.
2730 When nil, the state change notes will be ordered according to time.
2732 This option can also be set with on a per-file-basis with
2734 #+STARTUP: logstatesreversed
2735 #+STARTUP: nologstatesreversed"
2736 :group 'org-todo
2737 :group 'org-progress
2738 :type 'boolean)
2740 (defcustom org-todo-repeat-to-state nil
2741 "The TODO state to which a repeater should return the repeating task.
2742 By default this is the first task in a TODO sequence, or the previous state
2743 in a TODO_TYP set. But you can specify another task here.
2744 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2745 :group 'org-todo
2746 :version "24.1"
2747 :type '(choice (const :tag "Head of sequence" nil)
2748 (string :tag "Specific state")))
2750 (defcustom org-log-repeat 'time
2751 "Non-nil means record moving through the DONE state when triggering repeat.
2752 An auto-repeating task is immediately switched back to TODO when
2753 marked DONE. If you are not logging state changes (by adding \"@\"
2754 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2755 record a closing note, there will be no record of the task moving
2756 through DONE. This variable forces taking a note anyway.
2758 nil Don't force a record
2759 time Record a time stamp
2760 note Prompt for a note and add it with template `org-log-note-headings'
2762 This option can also be set with on a per-file-basis with
2764 #+STARTUP: nologrepeat
2765 #+STARTUP: logrepeat
2766 #+STARTUP: lognoterepeat
2768 You can have local logging settings for a subtree by setting the LOGGING
2769 property to one or more of these keywords."
2770 :group 'org-todo
2771 :group 'org-progress
2772 :type '(choice
2773 (const :tag "Don't force a record" nil)
2774 (const :tag "Force recording the DONE state" time)
2775 (const :tag "Force recording a note with the DONE state" note)))
2778 (defgroup org-priorities nil
2779 "Priorities in Org-mode."
2780 :tag "Org Priorities"
2781 :group 'org-todo)
2783 (defcustom org-enable-priority-commands t
2784 "Non-nil means priority commands are active.
2785 When nil, these commands will be disabled, so that you never accidentally
2786 set a priority."
2787 :group 'org-priorities
2788 :type 'boolean)
2790 (defcustom org-highest-priority ?A
2791 "The highest priority of TODO items. A character like ?A, ?B etc.
2792 Must have a smaller ASCII number than `org-lowest-priority'."
2793 :group 'org-priorities
2794 :type 'character)
2796 (defcustom org-lowest-priority ?C
2797 "The lowest priority of TODO items. A character like ?A, ?B etc.
2798 Must have a larger ASCII number than `org-highest-priority'."
2799 :group 'org-priorities
2800 :type 'character)
2802 (defcustom org-default-priority ?B
2803 "The default priority of TODO items.
2804 This is the priority an item gets if no explicit priority is given.
2805 When starting to cycle on an empty priority the first step in the cycle
2806 depends on `org-priority-start-cycle-with-default'. The resulting first
2807 step priority must not exceed the range from `org-highest-priority' to
2808 `org-lowest-priority' which means that `org-default-priority' has to be
2809 in this range exclusive or inclusive the range boundaries. Else the
2810 first step refuses to set the default and the second will fall back
2811 to (depending on the command used) the highest or lowest priority."
2812 :group 'org-priorities
2813 :type 'character)
2815 (defcustom org-priority-start-cycle-with-default t
2816 "Non-nil means start with default priority when starting to cycle.
2817 When this is nil, the first step in the cycle will be (depending on the
2818 command used) one higher or lower than the default priority.
2819 See also `org-default-priority'."
2820 :group 'org-priorities
2821 :type 'boolean)
2823 (defcustom org-get-priority-function nil
2824 "Function to extract the priority from a string.
2825 The string is normally the headline. If this is nil Org computes the
2826 priority from the priority cookie like [#A] in the headline. It returns
2827 an integer, increasing by 1000 for each priority level.
2828 The user can set a different function here, which should take a string
2829 as an argument and return the numeric priority."
2830 :group 'org-priorities
2831 :version "24.1"
2832 :type '(choice
2833 (const nil)
2834 (function)))
2836 (defgroup org-time nil
2837 "Options concerning time stamps and deadlines in Org-mode."
2838 :tag "Org Time"
2839 :group 'org)
2841 (defcustom org-insert-labeled-timestamps-at-point nil
2842 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2843 When nil, these labeled time stamps are forces into the second line of an
2844 entry, just after the headline. When scheduling from the global TODO list,
2845 the time stamp will always be forced into the second line."
2846 :group 'org-time
2847 :type 'boolean)
2849 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2850 "Formats for `format-time-string' which are used for time stamps.
2851 It is not recommended to change this constant.")
2853 (defcustom org-time-stamp-rounding-minutes '(0 5)
2854 "Number of minutes to round time stamps to.
2855 These are two values, the first applies when first creating a time stamp.
2856 The second applies when changing it with the commands `S-up' and `S-down'.
2857 When changing the time stamp, this means that it will change in steps
2858 of N minutes, as given by the second value.
2860 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2861 numbers should be factors of 60, so for example 5, 10, 15.
2863 When this is larger than 1, you can still force an exact time stamp by using
2864 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2865 and by using a prefix arg to `S-up/down' to specify the exact number
2866 of minutes to shift."
2867 :group 'org-time
2868 :get #'(lambda (var) ; Make sure both elements are there
2869 (if (integerp (default-value var))
2870 (list (default-value var) 5)
2871 (default-value var)))
2872 :type '(list
2873 (integer :tag "when inserting times")
2874 (integer :tag "when modifying times")))
2876 ;; Normalize old customizations of this variable.
2877 (when (integerp org-time-stamp-rounding-minutes)
2878 (setq org-time-stamp-rounding-minutes
2879 (list org-time-stamp-rounding-minutes
2880 org-time-stamp-rounding-minutes)))
2882 (defcustom org-display-custom-times nil
2883 "Non-nil means overlay custom formats over all time stamps.
2884 The formats are defined through the variable `org-time-stamp-custom-formats'.
2885 To turn this on on a per-file basis, insert anywhere in the file:
2886 #+STARTUP: customtime"
2887 :group 'org-time
2888 :set 'set-default
2889 :type 'sexp)
2890 (make-variable-buffer-local 'org-display-custom-times)
2892 (defcustom org-time-stamp-custom-formats
2893 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2894 "Custom formats for time stamps. See `format-time-string' for the syntax.
2895 These are overlaid over the default ISO format if the variable
2896 `org-display-custom-times' is set. Time like %H:%M should be at the
2897 end of the second format. The custom formats are also honored by export
2898 commands, if custom time display is turned on at the time of export."
2899 :group 'org-time
2900 :type 'sexp)
2902 (defun org-time-stamp-format (&optional long inactive)
2903 "Get the right format for a time string."
2904 (let ((f (if long (cdr org-time-stamp-formats)
2905 (car org-time-stamp-formats))))
2906 (if inactive
2907 (concat "[" (substring f 1 -1) "]")
2908 f)))
2910 (defcustom org-time-clocksum-format
2911 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2912 "The format string used when creating CLOCKSUM lines.
2913 This is also used when Org mode generates a time duration.
2915 The value can be a single format string containing two
2916 %-sequences, which will be filled with the number of hours and
2917 minutes in that order.
2919 Alternatively, the value can be a plist associating any of the
2920 keys :years, :months, :weeks, :days, :hours or :minutes with
2921 format strings. The time duration is formatted using only the
2922 time components that are needed and concatenating the results.
2923 If a time unit in absent, it falls back to the next smallest
2924 unit.
2926 The keys :require-years, :require-months, :require-days,
2927 :require-weeks, :require-hours, :require-minutes are also
2928 meaningful. A non-nil value for these keys indicates that the
2929 corresponding time component should always be included, even if
2930 its value is 0.
2933 For example,
2935 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2936 :require-minutes t)
2938 means durations longer than a day will be expressed in days,
2939 hours and minutes, and durations less than a day will always be
2940 expressed in hours and minutes (even for durations less than an
2941 hour).
2943 The value
2945 \(:days \"%dd\" :minutes \"%dm\")
2947 means durations longer than a day will be expressed in days and
2948 minutes, and durations less than a day will be expressed entirely
2949 in minutes (even for durations longer than an hour)."
2950 :group 'org-time
2951 :group 'org-clock
2952 :version "24.4"
2953 :package-version '(Org . "8.0")
2954 :type '(choice (string :tag "Format string")
2955 (set :tag "Plist"
2956 (group :inline t (const :tag "Years" :years)
2957 (string :tag "Format string"))
2958 (group :inline t
2959 (const :tag "Always show years" :require-years)
2960 (const t))
2961 (group :inline t (const :tag "Months" :months)
2962 (string :tag "Format string"))
2963 (group :inline t
2964 (const :tag "Always show months" :require-months)
2965 (const t))
2966 (group :inline t (const :tag "Weeks" :weeks)
2967 (string :tag "Format string"))
2968 (group :inline t
2969 (const :tag "Always show weeks" :require-weeks)
2970 (const t))
2971 (group :inline t (const :tag "Days" :days)
2972 (string :tag "Format string"))
2973 (group :inline t
2974 (const :tag "Always show days" :require-days)
2975 (const t))
2976 (group :inline t (const :tag "Hours" :hours)
2977 (string :tag "Format string"))
2978 (group :inline t
2979 (const :tag "Always show hours" :require-hours)
2980 (const t))
2981 (group :inline t (const :tag "Minutes" :minutes)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show minutes" :require-minutes)
2985 (const t)))))
2987 (defcustom org-time-clocksum-use-fractional nil
2988 "When non-nil, \\[org-clock-display] uses fractional times.
2989 See `org-time-clocksum-format' for more on time clock formats."
2990 :group 'org-time
2991 :group 'org-clock
2992 :version "24.3"
2993 :type 'boolean)
2995 (defcustom org-time-clocksum-use-effort-durations nil
2996 "When non-nil, \\[org-clock-display] uses effort durations.
2997 E.g. by default, one day is considered to be a 8 hours effort,
2998 so a task that has been clocked for 16 hours will be displayed
2999 as during 2 days in the clock display or in the clocktable.
3001 See `org-effort-durations' on how to set effort durations
3002 and `org-time-clocksum-format' for more on time clock formats."
3003 :group 'org-time
3004 :group 'org-clock
3005 :version "24.4"
3006 :package-version '(Org . "8.0")
3007 :type 'boolean)
3009 (defcustom org-time-clocksum-fractional-format "%.2f"
3010 "The format string used when creating CLOCKSUM lines,
3011 or when Org mode generates a time duration, if
3012 `org-time-clocksum-use-fractional' is enabled.
3014 The value can be a single format string containing one
3015 %-sequence, which will be filled with the number of hours as
3016 a float.
3018 Alternatively, the value can be a plist associating any of the
3019 keys :years, :months, :weeks, :days, :hours or :minutes with
3020 a format string. The time duration is formatted using the
3021 largest time unit which gives a non-zero integer part. If all
3022 specified formats have zero integer part, the smallest time unit
3023 is used."
3024 :group 'org-time
3025 :type '(choice (string :tag "Format string")
3026 (set (group :inline t (const :tag "Years" :years)
3027 (string :tag "Format string"))
3028 (group :inline t (const :tag "Months" :months)
3029 (string :tag "Format string"))
3030 (group :inline t (const :tag "Weeks" :weeks)
3031 (string :tag "Format string"))
3032 (group :inline t (const :tag "Days" :days)
3033 (string :tag "Format string"))
3034 (group :inline t (const :tag "Hours" :hours)
3035 (string :tag "Format string"))
3036 (group :inline t (const :tag "Minutes" :minutes)
3037 (string :tag "Format string")))))
3039 (defcustom org-deadline-warning-days 14
3040 "Number of days before expiration during which a deadline becomes active.
3041 This variable governs the display in sparse trees and in the agenda.
3042 When 0 or negative, it means use this number (the absolute value of it)
3043 even if a deadline has a different individual lead time specified.
3045 Custom commands can set this variable in the options section."
3046 :group 'org-time
3047 :group 'org-agenda-daily/weekly
3048 :type 'integer)
3050 (defcustom org-scheduled-delay-days 0
3051 "Number of days before a scheduled item becomes active.
3052 This variable governs the display in sparse trees and in the agenda.
3053 The default value (i.e. 0) means: don't delay scheduled item.
3054 When negative, it means use this number (the absolute value of it)
3055 even if a scheduled item has a different individual delay time
3056 specified.
3058 Custom commands can set this variable in the options section."
3059 :group 'org-time
3060 :group 'org-agenda-daily/weekly
3061 :version "24.4"
3062 :package-version '(Org . "8.0")
3063 :type 'integer)
3065 (defcustom org-read-date-prefer-future t
3066 "Non-nil means assume future for incomplete date input from user.
3067 This affects the following situations:
3068 1. The user gives a month but not a year.
3069 For example, if it is April and you enter \"feb 2\", this will be read
3070 as Feb 2, *next* year. \"May 5\", however, will be this year.
3071 2. The user gives a day, but no month.
3072 For example, if today is the 15th, and you enter \"3\", Org-mode will
3073 read this as the third of *next* month. However, if you enter \"17\",
3074 it will be considered as *this* month.
3076 If you set this variable to the symbol `time', then also the following
3077 will work:
3079 3. If the user gives a time.
3080 If the time is before now, it will be interpreted as tomorrow.
3082 Currently none of this works for ISO week specifications.
3084 When this option is nil, the current day, month and year will always be
3085 used as defaults.
3087 See also `org-agenda-jump-prefer-future'."
3088 :group 'org-time
3089 :type '(choice
3090 (const :tag "Never" nil)
3091 (const :tag "Check month and day" t)
3092 (const :tag "Check month, day, and time" time)))
3094 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3095 "Should the agenda jump command prefer the future for incomplete dates?
3096 The default is to do the same as configured in `org-read-date-prefer-future'.
3097 But you can also set a deviating value here.
3098 This may t or nil, or the symbol `org-read-date-prefer-future'."
3099 :group 'org-agenda
3100 :group 'org-time
3101 :version "24.1"
3102 :type '(choice
3103 (const :tag "Use org-read-date-prefer-future"
3104 org-read-date-prefer-future)
3105 (const :tag "Never" nil)
3106 (const :tag "Always" t)))
3108 (defcustom org-read-date-force-compatible-dates t
3109 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3111 Depending on the system Emacs is running on, certain dates cannot
3112 be represented with the type used internally to represent time.
3113 Dates between 1970-1-1 and 2038-1-1 can always be represented
3114 correctly. Some systems allow for earlier dates, some for later,
3115 some for both. One way to find out it to insert any date into an
3116 Org buffer, putting the cursor on the year and hitting S-up and
3117 S-down to test the range.
3119 When this variable is set to t, the date/time prompt will not let
3120 you specify dates outside the 1970-2037 range, so it is certain that
3121 these dates will work in whatever version of Emacs you are
3122 running, and also that you can move a file from one Emacs implementation
3123 to another. WHenever Org is forcing the year for you, it will display
3124 a message and beep.
3126 When this variable is nil, Org will check if the date is
3127 representable in the specific Emacs implementation you are using.
3128 If not, it will force a year, usually the current year, and beep
3129 to remind you. Currently this setting is not recommended because
3130 the likelihood that you will open your Org files in an Emacs that
3131 has limited date range is not negligible.
3133 A workaround for this problem is to use diary sexp dates for time
3134 stamps outside of this range."
3135 :group 'org-time
3136 :version "24.1"
3137 :type 'boolean)
3139 (defcustom org-read-date-display-live t
3140 "Non-nil means display current interpretation of date prompt live.
3141 This display will be in an overlay, in the minibuffer."
3142 :group 'org-time
3143 :type 'boolean)
3145 (defcustom org-read-date-popup-calendar t
3146 "Non-nil means pop up a calendar when prompting for a date.
3147 In the calendar, the date can be selected with mouse-1. However, the
3148 minibuffer will also be active, and you can simply enter the date as well.
3149 When nil, only the minibuffer will be available."
3150 :group 'org-time
3151 :type 'boolean)
3152 (org-defvaralias 'org-popup-calendar-for-date-prompt
3153 'org-read-date-popup-calendar)
3155 (make-obsolete-variable
3156 'org-read-date-minibuffer-setup-hook
3157 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3158 (defcustom org-read-date-minibuffer-setup-hook nil
3159 "Hook to be used to set up keys for the date/time interface.
3160 Add key definitions to `minibuffer-local-map', which will be a
3161 temporary copy.
3163 WARNING: This option is obsolete, you should use
3164 `org-read-date-minibuffer-local-map' to set up keys."
3165 :group 'org-time
3166 :type 'hook)
3168 (defcustom org-extend-today-until 0
3169 "The hour when your day really ends. Must be an integer.
3170 This has influence for the following applications:
3171 - When switching the agenda to \"today\". It it is still earlier than
3172 the time given here, the day recognized as TODAY is actually yesterday.
3173 - When a date is read from the user and it is still before the time given
3174 here, the current date and time will be assumed to be yesterday, 23:59.
3175 Also, timestamps inserted in capture templates follow this rule.
3177 IMPORTANT: This is a feature whose implementation is and likely will
3178 remain incomplete. Really, it is only here because past midnight seems to
3179 be the favorite working time of John Wiegley :-)"
3180 :group 'org-time
3181 :type 'integer)
3183 (defcustom org-use-effective-time nil
3184 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3185 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3186 \"effective time\" of any timestamps between midnight and 8am will be
3187 23:59 of the previous day."
3188 :group 'org-time
3189 :version "24.1"
3190 :type 'boolean)
3192 (defcustom org-use-last-clock-out-time-as-effective-time nil
3193 "When non-nil, use the last clock out time for `org-todo'.
3194 Note that this option has precedence over the combined use of
3195 `org-use-effective-time' and `org-extend-today-until'."
3196 :group 'org-time
3197 :version "24.4"
3198 :package-version '(Org . "8.0")
3199 :type 'boolean)
3201 (defcustom org-edit-timestamp-down-means-later nil
3202 "Non-nil means S-down will increase the time in a time stamp.
3203 When nil, S-up will increase."
3204 :group 'org-time
3205 :type 'boolean)
3207 (defcustom org-calendar-follow-timestamp-change t
3208 "Non-nil means make the calendar window follow timestamp changes.
3209 When a timestamp is modified and the calendar window is visible, it will be
3210 moved to the new date."
3211 :group 'org-time
3212 :type 'boolean)
3214 (defgroup org-tags nil
3215 "Options concerning tags in Org-mode."
3216 :tag "Org Tags"
3217 :group 'org)
3219 (defcustom org-tag-alist nil
3220 "List of tags allowed in Org-mode files.
3221 When this list is nil, Org-mode will base TAG input on what is already in the
3222 buffer.
3223 The value of this variable is an alist, the car of each entry must be a
3224 keyword as a string, the cdr may be a character that is used to select
3225 that tag through the fast-tag-selection interface.
3226 See the manual for details."
3227 :group 'org-tags
3228 :type '(repeat
3229 (choice
3230 (cons (string :tag "Tag name")
3231 (character :tag "Access char"))
3232 (list :tag "Start radio group"
3233 (const :startgroup)
3234 (option (string :tag "Group description")))
3235 (list :tag "Group tags delimiter"
3236 (const :grouptags))
3237 (list :tag "End radio group"
3238 (const :endgroup)
3239 (option (string :tag "Group description")))
3240 (const :tag "New line" (:newline)))))
3242 (defcustom org-tag-persistent-alist nil
3243 "List of tags that will always appear in all Org-mode files.
3244 This is in addition to any in buffer settings or customizations
3245 of `org-tag-alist'.
3246 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3247 The value of this variable is an alist, the car of each entry must be a
3248 keyword as a string, the cdr may be a character that is used to select
3249 that tag through the fast-tag-selection interface.
3250 See the manual for details.
3251 To disable these tags on a per-file basis, insert anywhere in the file:
3252 #+STARTUP: noptag"
3253 :group 'org-tags
3254 :type '(repeat
3255 (choice
3256 (cons (string :tag "Tag name")
3257 (character :tag "Access char"))
3258 (const :tag "Start radio group" (:startgroup))
3259 (const :tag "Group tags delimiter" (:grouptags))
3260 (const :tag "End radio group" (:endgroup))
3261 (const :tag "New line" (:newline)))))
3263 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3264 "If non-nil, always offer completion for all tags of all agenda files.
3265 Instead of customizing this variable directly, you might want to
3266 set it locally for capture buffers, because there no list of
3267 tags in that file can be created dynamically (there are none).
3269 (add-hook 'org-capture-mode-hook
3270 (lambda ()
3271 (set (make-local-variable
3272 'org-complete-tags-always-offer-all-agenda-tags)
3273 t)))"
3274 :group 'org-tags
3275 :version "24.1"
3276 :type 'boolean)
3278 (defvar org-file-tags nil
3279 "List of tags that can be inherited by all entries in the file.
3280 The tags will be inherited if the variable `org-use-tag-inheritance'
3281 says they should be.
3282 This variable is populated from #+FILETAGS lines.")
3284 (defcustom org-use-fast-tag-selection 'auto
3285 "Non-nil means use fast tag selection scheme.
3286 This is a special interface to select and deselect tags with single keys.
3287 When nil, fast selection is never used.
3288 When the symbol `auto', fast selection is used if and only if selection
3289 characters for tags have been configured, either through the variable
3290 `org-tag-alist' or through a #+TAGS line in the buffer.
3291 When t, fast selection is always used and selection keys are assigned
3292 automatically if necessary."
3293 :group 'org-tags
3294 :type '(choice
3295 (const :tag "Always" t)
3296 (const :tag "Never" nil)
3297 (const :tag "When selection characters are configured" auto)))
3299 (defcustom org-fast-tag-selection-single-key nil
3300 "Non-nil means fast tag selection exits after first change.
3301 When nil, you have to press RET to exit it.
3302 During fast tag selection, you can toggle this flag with `C-c'.
3303 This variable can also have the value `expert'. In this case, the window
3304 displaying the tags menu is not even shown, until you press C-c again."
3305 :group 'org-tags
3306 :type '(choice
3307 (const :tag "No" nil)
3308 (const :tag "Yes" t)
3309 (const :tag "Expert" expert)))
3311 (defvar org-fast-tag-selection-include-todo nil
3312 "Non-nil means fast tags selection interface will also offer TODO states.
3313 This is an undocumented feature, you should not rely on it.")
3315 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3316 "The column to which tags should be indented in a headline.
3317 If this number is positive, it specifies the column. If it is negative,
3318 it means that the tags should be flushright to that column. For example,
3319 -80 works well for a normal 80 character screen.
3320 When 0, place tags directly after headline text, with only one space in
3321 between."
3322 :group 'org-tags
3323 :type 'integer)
3325 (defcustom org-auto-align-tags t
3326 "Non-nil keeps tags aligned when modifying headlines.
3327 Some operations (i.e. demoting) change the length of a headline and
3328 therefore shift the tags around. With this option turned on, after
3329 each such operation the tags are again aligned to `org-tags-column'."
3330 :group 'org-tags
3331 :type 'boolean)
3333 (defcustom org-use-tag-inheritance t
3334 "Non-nil means tags in levels apply also for sublevels.
3335 When nil, only the tags directly given in a specific line apply there.
3336 This may also be a list of tags that should be inherited, or a regexp that
3337 matches tags that should be inherited. Additional control is possible
3338 with the variable `org-tags-exclude-from-inheritance' which gives an
3339 explicit list of tags to be excluded from inheritance, even if the value of
3340 `org-use-tag-inheritance' would select it for inheritance.
3342 If this option is t, a match early-on in a tree can lead to a large
3343 number of matches in the subtree when constructing the agenda or creating
3344 a sparse tree. If you only want to see the first match in a tree during
3345 a search, check out the variable `org-tags-match-list-sublevels'."
3346 :group 'org-tags
3347 :type '(choice
3348 (const :tag "Not" nil)
3349 (const :tag "Always" t)
3350 (repeat :tag "Specific tags" (string :tag "Tag"))
3351 (regexp :tag "Tags matched by regexp")))
3353 (defcustom org-tags-exclude-from-inheritance nil
3354 "List of tags that should never be inherited.
3355 This is a way to exclude a few tags from inheritance. For way to do
3356 the opposite, to actively allow inheritance for selected tags,
3357 see the variable `org-use-tag-inheritance'."
3358 :group 'org-tags
3359 :type '(repeat (string :tag "Tag")))
3361 (defun org-tag-inherit-p (tag)
3362 "Check if TAG is one that should be inherited."
3363 (cond
3364 ((member tag org-tags-exclude-from-inheritance) nil)
3365 ((eq org-use-tag-inheritance t) t)
3366 ((not org-use-tag-inheritance) nil)
3367 ((stringp org-use-tag-inheritance)
3368 (string-match org-use-tag-inheritance tag))
3369 ((listp org-use-tag-inheritance)
3370 (member tag org-use-tag-inheritance))
3371 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3373 (defcustom org-tags-match-list-sublevels t
3374 "Non-nil means list also sublevels of headlines matching a search.
3375 This variable applies to tags/property searches, and also to stuck
3376 projects because this search is based on a tags match as well.
3378 When set to the symbol `indented', sublevels are indented with
3379 leading dots.
3381 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3382 the sublevels of a headline matching a tag search often also match
3383 the same search. Listing all of them can create very long lists.
3384 Setting this variable to nil causes subtrees of a match to be skipped.
3386 This variable is semi-obsolete and probably should always be true. It
3387 is better to limit inheritance to certain tags using the variables
3388 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3389 :group 'org-tags
3390 :type '(choice
3391 (const :tag "No, don't list them" nil)
3392 (const :tag "Yes, do list them" t)
3393 (const :tag "List them, indented with leading dots" indented)))
3395 (defcustom org-tags-sort-function nil
3396 "When set, tags are sorted using this function as a comparator."
3397 :group 'org-tags
3398 :type '(choice
3399 (const :tag "No sorting" nil)
3400 (const :tag "Alphabetical" string<)
3401 (const :tag "Reverse alphabetical" string>)
3402 (function :tag "Custom function" nil)))
3404 (defvar org-tags-history nil
3405 "History of minibuffer reads for tags.")
3406 (defvar org-last-tags-completion-table nil
3407 "The last used completion table for tags.")
3408 (defvar org-after-tags-change-hook nil
3409 "Hook that is run after the tags in a line have changed.")
3411 (defgroup org-properties nil
3412 "Options concerning properties in Org-mode."
3413 :tag "Org Properties"
3414 :group 'org)
3416 (defcustom org-property-format "%-10s %s"
3417 "How property key/value pairs should be formatted by `indent-line'.
3418 When `indent-line' hits a property definition, it will format the line
3419 according to this format, mainly to make sure that the values are
3420 lined-up with respect to each other."
3421 :group 'org-properties
3422 :type 'string)
3424 (defcustom org-properties-postprocess-alist nil
3425 "Alist of properties and functions to adjust inserted values.
3426 Elements of this alist must be of the form
3428 ([string] [function])
3430 where [string] must be a property name and [function] must be a
3431 lambda expression: this lambda expression must take one argument,
3432 the value to adjust, and return the new value as a string.
3434 For example, this element will allow the property \"Remaining\"
3435 to be updated wrt the relation between the \"Effort\" property
3436 and the clock summary:
3438 ((\"Remaining\" (lambda(value)
3439 (let ((clocksum (org-clock-sum-current-item))
3440 (effort (org-duration-string-to-minutes
3441 (org-entry-get (point) \"Effort\"))))
3442 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3443 :group 'org-properties
3444 :version "24.1"
3445 :type '(alist :key-type (string :tag "Property")
3446 :value-type (function :tag "Function")))
3448 (defcustom org-use-property-inheritance nil
3449 "Non-nil means properties apply also for sublevels.
3451 This setting is chiefly used during property searches. Turning it on can
3452 cause significant overhead when doing a search, which is why it is not
3453 on by default.
3455 When nil, only the properties directly given in the current entry count.
3456 When t, every property is inherited. The value may also be a list of
3457 properties that should have inheritance, or a regular expression matching
3458 properties that should be inherited.
3460 However, note that some special properties use inheritance under special
3461 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3462 and the properties ending in \"_ALL\" when they are used as descriptor
3463 for valid values of a property.
3465 Note for programmers:
3466 When querying an entry with `org-entry-get', you can control if inheritance
3467 should be used. By default, `org-entry-get' looks only at the local
3468 properties. You can request inheritance by setting the inherit argument
3469 to t (to force inheritance) or to `selective' (to respect the setting
3470 in this variable)."
3471 :group 'org-properties
3472 :type '(choice
3473 (const :tag "Not" nil)
3474 (const :tag "Always" t)
3475 (repeat :tag "Specific properties" (string :tag "Property"))
3476 (regexp :tag "Properties matched by regexp")))
3478 (defun org-property-inherit-p (property)
3479 "Check if PROPERTY is one that should be inherited."
3480 (cond
3481 ((eq org-use-property-inheritance t) t)
3482 ((not org-use-property-inheritance) nil)
3483 ((stringp org-use-property-inheritance)
3484 (string-match org-use-property-inheritance property))
3485 ((listp org-use-property-inheritance)
3486 (member property org-use-property-inheritance))
3487 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3489 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3490 "The default column format, if no other format has been defined.
3491 This variable can be set on the per-file basis by inserting a line
3493 #+COLUMNS: %25ITEM ....."
3494 :group 'org-properties
3495 :type 'string)
3497 (defcustom org-columns-ellipses ".."
3498 "The ellipses to be used when a field in column view is truncated.
3499 When this is the empty string, as many characters as possible are shown,
3500 but then there will be no visual indication that the field has been truncated.
3501 When this is a string of length N, the last N characters of a truncated
3502 field are replaced by this string. If the column is narrower than the
3503 ellipses string, only part of the ellipses string will be shown."
3504 :group 'org-properties
3505 :type 'string)
3507 (defcustom org-columns-modify-value-for-display-function nil
3508 "Function that modifies values for display in column view.
3509 For example, it can be used to cut out a certain part from a time stamp.
3510 The function must take 2 arguments:
3512 column-title The title of the column (*not* the property name)
3513 value The value that should be modified.
3515 The function should return the value that should be displayed,
3516 or nil if the normal value should be used."
3517 :group 'org-properties
3518 :type '(choice (const nil) (function)))
3520 (defcustom org-effort-property "Effort"
3521 "The property that is being used to keep track of effort estimates.
3522 Effort estimates given in this property need to have the format H:MM."
3523 :group 'org-properties
3524 :group 'org-progress
3525 :type '(string :tag "Property"))
3527 (defconst org-global-properties-fixed
3528 '(("VISIBILITY_ALL" . "folded children content all")
3529 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3530 "List of property/value pairs that can be inherited by any entry.
3532 These are fixed values, for the preset properties. The user variable
3533 that can be used to add to this list is `org-global-properties'.
3535 The entries in this list are cons cells where the car is a property
3536 name and cdr is a string with the value. If the value represents
3537 multiple items like an \"_ALL\" property, separate the items by
3538 spaces.")
3540 (defcustom org-global-properties nil
3541 "List of property/value pairs that can be inherited by any entry.
3543 This list will be combined with the constant `org-global-properties-fixed'.
3545 The entries in this list are cons cells where the car is a property
3546 name and cdr is a string with the value.
3548 You can set buffer-local values for the same purpose in the variable
3549 `org-file-properties' this by adding lines like
3551 #+PROPERTY: NAME VALUE"
3552 :group 'org-properties
3553 :type '(repeat
3554 (cons (string :tag "Property")
3555 (string :tag "Value"))))
3557 (defvar org-file-properties nil
3558 "List of property/value pairs that can be inherited by any entry.
3559 Valid for the current buffer.
3560 This variable is populated from #+PROPERTY lines.")
3561 (make-variable-buffer-local 'org-file-properties)
3563 (defgroup org-agenda nil
3564 "Options concerning agenda views in Org-mode."
3565 :tag "Org Agenda"
3566 :group 'org)
3568 (defvar org-category nil
3569 "Variable used by org files to set a category for agenda display.
3570 Such files should use a file variable to set it, for example
3572 # -*- mode: org; org-category: \"ELisp\"
3574 or contain a special line
3576 #+CATEGORY: ELisp
3578 If the file does not specify a category, then file's base name
3579 is used instead.")
3580 (make-variable-buffer-local 'org-category)
3581 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3583 (defcustom org-agenda-files nil
3584 "The files to be used for agenda display.
3585 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3586 \\[org-remove-file]. You can also use customize to edit the list.
3588 If an entry is a directory, all files in that directory that are matched by
3589 `org-agenda-file-regexp' will be part of the file list.
3591 If the value of the variable is not a list but a single file name, then
3592 the list of agenda files is actually stored and maintained in that file, one
3593 agenda file per line. In this file paths can be given relative to
3594 `org-directory'. Tilde expansion and environment variable substitution
3595 are also made."
3596 :group 'org-agenda
3597 :type '(choice
3598 (repeat :tag "List of files and directories" file)
3599 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3601 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3602 "Regular expression to match files for `org-agenda-files'.
3603 If any element in the list in that variable contains a directory instead
3604 of a normal file, all files in that directory that are matched by this
3605 regular expression will be included."
3606 :group 'org-agenda
3607 :type 'regexp)
3609 (defcustom org-agenda-text-search-extra-files nil
3610 "List of extra files to be searched by text search commands.
3611 These files will be searched in addition to the agenda files by the
3612 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3613 Note that these files will only be searched for text search commands,
3614 not for the other agenda views like todo lists, tag searches or the weekly
3615 agenda. This variable is intended to list notes and possibly archive files
3616 that should also be searched by these two commands.
3617 In fact, if the first element in the list is the symbol `agenda-archives',
3618 then all archive files of all agenda files will be added to the search
3619 scope."
3620 :group 'org-agenda
3621 :type '(set :greedy t
3622 (const :tag "Agenda Archives" agenda-archives)
3623 (repeat :inline t (file))))
3625 (org-defvaralias 'org-agenda-multi-occur-extra-files
3626 'org-agenda-text-search-extra-files)
3628 (defcustom org-agenda-skip-unavailable-files nil
3629 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3630 A nil value means to remove them, after a query, from the list."
3631 :group 'org-agenda
3632 :type 'boolean)
3634 (defcustom org-calendar-to-agenda-key [?c]
3635 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3636 The command `org-calendar-goto-agenda' will be bound to this key. The
3637 default is the character `c' because then `c' can be used to switch back and
3638 forth between agenda and calendar."
3639 :group 'org-agenda
3640 :type 'sexp)
3642 (defcustom org-calendar-insert-diary-entry-key [?i]
3643 "The key to be installed in `calendar-mode-map' for adding diary entries.
3644 This option is irrelevant until `org-agenda-diary-file' has been configured
3645 to point to an Org-mode file. When that is the case, the command
3646 `org-agenda-diary-entry' will be bound to the key given here, by default
3647 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3648 if you want to continue doing this, you need to change this to a different
3649 key."
3650 :group 'org-agenda
3651 :type 'sexp)
3653 (defcustom org-agenda-diary-file 'diary-file
3654 "File to which to add new entries with the `i' key in agenda and calendar.
3655 When this is the symbol `diary-file', the functionality in the Emacs
3656 calendar will be used to add entries to the `diary-file'. But when this
3657 points to a file, `org-agenda-diary-entry' will be used instead."
3658 :group 'org-agenda
3659 :type '(choice
3660 (const :tag "The standard Emacs diary file" diary-file)
3661 (file :tag "Special Org file diary entries")))
3663 (eval-after-load "calendar"
3664 '(progn
3665 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3666 'org-calendar-goto-agenda)
3667 (add-hook 'calendar-mode-hook
3668 (lambda ()
3669 (unless (eq org-agenda-diary-file 'diary-file)
3670 (define-key calendar-mode-map
3671 org-calendar-insert-diary-entry-key
3672 'org-agenda-diary-entry))))))
3674 (defgroup org-latex nil
3675 "Options for embedding LaTeX code into Org-mode."
3676 :tag "Org LaTeX"
3677 :group 'org)
3679 (defcustom org-format-latex-options
3680 '(:foreground default :background default :scale 1.0
3681 :html-foreground "Black" :html-background "Transparent"
3682 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3683 "Options for creating images from LaTeX fragments.
3684 This is a property list with the following properties:
3685 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3686 `default' means use the foreground of the default face.
3687 `auto' means use the foreground from the text face.
3688 :background the background color, or \"Transparent\".
3689 `default' means use the background of the default face.
3690 `auto' means use the background from the text face.
3691 :scale a scaling factor for the size of the images, to get more pixels
3692 :html-foreground, :html-background, :html-scale
3693 the same numbers for HTML export.
3694 :matchers a list indicating which matchers should be used to
3695 find LaTeX fragments. Valid members of this list are:
3696 \"begin\" find environments
3697 \"$1\" find single characters surrounded by $.$
3698 \"$\" find math expressions surrounded by $...$
3699 \"$$\" find math expressions surrounded by $$....$$
3700 \"\\(\" find math expressions surrounded by \\(...\\)
3701 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3702 :group 'org-latex
3703 :type 'plist)
3705 (defcustom org-format-latex-signal-error t
3706 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3707 When nil, just push out a message."
3708 :group 'org-latex
3709 :version "24.1"
3710 :type 'boolean)
3712 (defcustom org-latex-to-mathml-jar-file nil
3713 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3714 Use this to specify additional executable file say a jar file.
3716 When using MathToWeb as the converter, specify the full-path to
3717 your mathtoweb.jar file."
3718 :group 'org-latex
3719 :version "24.1"
3720 :type '(choice
3721 (const :tag "None" nil)
3722 (file :tag "JAR file" :must-match t)))
3724 (defcustom org-latex-to-mathml-convert-command nil
3725 "Command to convert LaTeX fragments to MathML.
3726 Replace format-specifiers in the command as noted below and use
3727 `shell-command' to convert LaTeX to MathML.
3728 %j: Executable file in fully expanded form as specified by
3729 `org-latex-to-mathml-jar-file'.
3730 %I: Input LaTeX file in fully expanded form
3731 %o: Output MathML file
3732 This command is used by `org-create-math-formula'.
3734 When using MathToWeb as the converter, set this to
3735 \"java -jar %j -unicode -force -df %o %I\"."
3736 :group 'org-latex
3737 :version "24.1"
3738 :type '(choice
3739 (const :tag "None" nil)
3740 (string :tag "\nShell command")))
3742 (defcustom org-latex-create-formula-image-program 'dvipng
3743 "Program to convert LaTeX fragments with.
3745 dvipng Process the LaTeX fragments to dvi file, then convert
3746 dvi files to png files using dvipng.
3747 This will also include processing of non-math environments.
3748 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3749 to convert pdf files to png files"
3750 :group 'org-latex
3751 :version "24.1"
3752 :type '(choice
3753 (const :tag "dvipng" dvipng)
3754 (const :tag "imagemagick" imagemagick)))
3756 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3757 "Path to store latex preview images.
3758 A relative path here creates many directories relative to the
3759 processed org files paths. An absolute path puts all preview
3760 images at the same place."
3761 :group 'org-latex
3762 :version "24.3"
3763 :type 'string)
3765 (defun org-format-latex-mathml-available-p ()
3766 "Return t if `org-latex-to-mathml-convert-command' is usable."
3767 (save-match-data
3768 (when (and (boundp 'org-latex-to-mathml-convert-command)
3769 org-latex-to-mathml-convert-command)
3770 (let ((executable (car (split-string
3771 org-latex-to-mathml-convert-command))))
3772 (when (executable-find executable)
3773 (if (string-match
3774 "%j" org-latex-to-mathml-convert-command)
3775 (file-readable-p org-latex-to-mathml-jar-file)
3776 t))))))
3778 (defcustom org-format-latex-header "\\documentclass{article}
3779 \\usepackage[usenames]{color}
3780 \\usepackage{amsmath}
3781 \\usepackage[mathscr]{eucal}
3782 \[PACKAGES]
3783 \[DEFAULT-PACKAGES]
3784 \\pagestyle{empty} % do not remove
3785 % The settings below are copied from fullpage.sty
3786 \\setlength{\\textwidth}{\\paperwidth}
3787 \\addtolength{\\textwidth}{-3cm}
3788 \\setlength{\\oddsidemargin}{1.5cm}
3789 \\addtolength{\\oddsidemargin}{-2.54cm}
3790 \\setlength{\\evensidemargin}{\\oddsidemargin}
3791 \\setlength{\\textheight}{\\paperheight}
3792 \\addtolength{\\textheight}{-\\headheight}
3793 \\addtolength{\\textheight}{-\\headsep}
3794 \\addtolength{\\textheight}{-\\footskip}
3795 \\addtolength{\\textheight}{-3cm}
3796 \\setlength{\\topmargin}{1.5cm}
3797 \\addtolength{\\topmargin}{-2.54cm}"
3798 "The document header used for processing LaTeX fragments.
3799 It is imperative that this header make sure that no page number
3800 appears on the page. The package defined in the variables
3801 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3802 will either replace the placeholder \"[PACKAGES]\" in this
3803 header, or they will be appended."
3804 :group 'org-latex
3805 :type 'string)
3807 (defun org-set-packages-alist (var val)
3808 "Set the packages alist and make sure it has 3 elements per entry."
3809 (set var (mapcar (lambda (x)
3810 (if (and (consp x) (= (length x) 2))
3811 (list (car x) (nth 1 x) t)
3813 val)))
3815 (defun org-get-packages-alist (var)
3816 "Get the packages alist and make sure it has 3 elements per entry."
3817 (mapcar (lambda (x)
3818 (if (and (consp x) (= (length x) 2))
3819 (list (car x) (nth 1 x) t)
3821 (default-value var)))
3823 (defcustom org-latex-default-packages-alist
3824 '(("AUTO" "inputenc" t)
3825 ("T1" "fontenc" t)
3826 ("" "fixltx2e" nil)
3827 ("" "graphicx" t)
3828 ("" "longtable" nil)
3829 ("" "float" nil)
3830 ("" "wrapfig" nil)
3831 ("normalem" "ulem" t)
3832 ("" "textcomp" t)
3833 ("" "marvosym" t)
3834 ("" "wasysym" t)
3835 ("" "latexsym" t)
3836 ("" "amssymb" t)
3837 ("" "amstext" nil)
3838 ("" "hyperref" nil)
3839 "\\tolerance=1000")
3840 "Alist of default packages to be inserted in the header.
3842 Change this only if one of the packages here causes an
3843 incompatibility with another package you are using.
3845 The packages in this list are needed by one part or another of
3846 Org mode to function properly:
3848 - inputenc, fontenc: for basic font and character selection
3849 - amstext: for subscript and superscript
3850 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3851 symbols used for interpreting the entities in `org-entities'.
3852 You can skip some of these packages if you don't use any of the
3853 symbols in it.
3854 - ulem: for underline and strike-through
3855 - graphicx: for including images
3856 - float, wrapfig: for figure placement
3857 - longtable: for long tables
3858 - hyperref: for cross references
3860 Therefore you should not modify this variable unless you know
3861 what you are doing. The one reason to change it anyway is that
3862 you might be loading some other package that conflicts with one
3863 of the default packages. Each cell is of the format
3864 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3865 the package also needs to be included when compiling LaTeX
3866 snippets into images for inclusion into non-LaTeX output."
3867 :group 'org-latex
3868 :group 'org-export-latex
3869 :set 'org-set-packages-alist
3870 :get 'org-get-packages-alist
3871 :version "24.1"
3872 :type '(repeat
3873 (choice
3874 (list :tag "options/package pair"
3875 (string :tag "options")
3876 (string :tag "package")
3877 (boolean :tag "Snippet"))
3878 (string :tag "A line of LaTeX"))))
3880 (defcustom org-latex-packages-alist nil
3881 "Alist of packages to be inserted in every LaTeX header.
3883 These will be inserted after `org-latex-default-packages-alist'.
3884 Each cell is of the format:
3886 \(\"options\" \"package\" snippet-flag)
3888 SNIPPET-FLAG, when t, indicates that this package is also needed
3889 when turning LaTeX snippets into images for inclusion into
3890 non-LaTeX output.
3892 Make sure that you only list packages here which:
3894 - you want in every file
3895 - do not conflict with the setup in `org-format-latex-header'.
3896 - do not conflict with the default packages in
3897 `org-latex-default-packages-alist'."
3898 :group 'org-latex
3899 :group 'org-export-latex
3900 :set 'org-set-packages-alist
3901 :get 'org-get-packages-alist
3902 :type '(repeat
3903 (choice
3904 (list :tag "options/package pair"
3905 (string :tag "options")
3906 (string :tag "package")
3907 (boolean :tag "Snippet"))
3908 (string :tag "A line of LaTeX"))))
3910 (defgroup org-appearance nil
3911 "Settings for Org-mode appearance."
3912 :tag "Org Appearance"
3913 :group 'org)
3915 (defcustom org-level-color-stars-only nil
3916 "Non-nil means fontify only the stars in each headline.
3917 When nil, the entire headline is fontified.
3918 Changing it requires restart of `font-lock-mode' to become effective
3919 also in regions already fontified."
3920 :group 'org-appearance
3921 :type 'boolean)
3923 (defcustom org-hide-leading-stars nil
3924 "Non-nil means hide the first N-1 stars in a headline.
3925 This works by using the face `org-hide' for these stars. This
3926 face is white for a light background, and black for a dark
3927 background. You may have to customize the face `org-hide' to
3928 make this work.
3929 Changing it requires restart of `font-lock-mode' to become effective
3930 also in regions already fontified.
3931 You may also set this on a per-file basis by adding one of the following
3932 lines to the buffer:
3934 #+STARTUP: hidestars
3935 #+STARTUP: showstars"
3936 :group 'org-appearance
3937 :type 'boolean)
3939 (defcustom org-hidden-keywords nil
3940 "List of symbols corresponding to keywords to be hidden the org buffer.
3941 For example, a value '(title) for this list will make the document's title
3942 appear in the buffer without the initial #+TITLE: keyword."
3943 :group 'org-appearance
3944 :version "24.1"
3945 :type '(set (const :tag "#+AUTHOR" author)
3946 (const :tag "#+DATE" date)
3947 (const :tag "#+EMAIL" email)
3948 (const :tag "#+TITLE" title)))
3950 (defcustom org-custom-properties nil
3951 "List of properties (as strings) with a special meaning.
3952 The default use of these custom properties is to let the user
3953 hide them with `org-toggle-custom-properties-visibility'."
3954 :group 'org-properties
3955 :group 'org-appearance
3956 :version "24.3"
3957 :type '(repeat (string :tag "Property Name")))
3959 (defcustom org-fontify-done-headline nil
3960 "Non-nil means change the face of a headline if it is marked DONE.
3961 Normally, only the TODO/DONE keyword indicates the state of a headline.
3962 When this is non-nil, the headline after the keyword is set to the
3963 `org-headline-done' as an additional indication."
3964 :group 'org-appearance
3965 :type 'boolean)
3967 (defcustom org-fontify-emphasized-text t
3968 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3969 Changing this variable requires a restart of Emacs to take effect."
3970 :group 'org-appearance
3971 :type 'boolean)
3973 (defcustom org-fontify-whole-heading-line nil
3974 "Non-nil means fontify the whole line for headings.
3975 This is useful when setting a background color for the
3976 org-level-* faces."
3977 :group 'org-appearance
3978 :type 'boolean)
3980 (defcustom org-highlight-latex-and-related nil
3981 "Non-nil means highlight LaTeX related syntax in the buffer.
3982 When non nil, the value should be a list containing any of the
3983 following symbols:
3984 `latex' Highlight LaTeX snippets and environments.
3985 `script' Highlight subscript and superscript.
3986 `entities' Highlight entities."
3987 :group 'org-appearance
3988 :version "24.4"
3989 :package-version '(Org . "8.0")
3990 :type '(choice
3991 (const :tag "No highlighting" nil)
3992 (set :greedy t :tag "Highlight"
3993 (const :tag "LaTeX snippets and environments" latex)
3994 (const :tag "Subscript and superscript" script)
3995 (const :tag "Entities" entities))))
3997 (defcustom org-hide-emphasis-markers nil
3998 "Non-nil mean font-lock should hide the emphasis marker characters."
3999 :group 'org-appearance
4000 :type 'boolean)
4002 (defcustom org-pretty-entities nil
4003 "Non-nil means show entities as UTF8 characters.
4004 When nil, the \\name form remains in the buffer."
4005 :group 'org-appearance
4006 :version "24.1"
4007 :type 'boolean)
4009 (defcustom org-pretty-entities-include-sub-superscripts t
4010 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4011 :group 'org-appearance
4012 :version "24.1"
4013 :type 'boolean)
4015 (defvar org-emph-re nil
4016 "Regular expression for matching emphasis.
4017 After a match, the match groups contain these elements:
4018 0 The match of the full regular expression, including the characters
4019 before and after the proper match
4020 1 The character before the proper match, or empty at beginning of line
4021 2 The proper match, including the leading and trailing markers
4022 3 The leading marker like * or /, indicating the type of highlighting
4023 4 The text between the emphasis markers, not including the markers
4024 5 The character after the match, empty at the end of a line")
4025 (defvar org-verbatim-re nil
4026 "Regular expression for matching verbatim text.")
4027 (defvar org-emphasis-regexp-components) ; defined just below
4028 (defvar org-emphasis-alist) ; defined just below
4029 (defun org-set-emph-re (var val)
4030 "Set variable and compute the emphasis regular expression."
4031 (set var val)
4032 (when (and (boundp 'org-emphasis-alist)
4033 (boundp 'org-emphasis-regexp-components)
4034 org-emphasis-alist org-emphasis-regexp-components)
4035 (let* ((e org-emphasis-regexp-components)
4036 (pre (car e))
4037 (post (nth 1 e))
4038 (border (nth 2 e))
4039 (body (nth 3 e))
4040 (nl (nth 4 e))
4041 (body1 (concat body "*?"))
4042 (markers (mapconcat 'car org-emphasis-alist ""))
4043 (vmarkers (mapconcat
4044 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4045 org-emphasis-alist "")))
4046 ;; make sure special characters appear at the right position in the class
4047 (if (string-match "\\^" markers)
4048 (setq markers (concat (replace-match "" t t markers) "^")))
4049 (if (string-match "-" markers)
4050 (setq markers (concat (replace-match "" t t markers) "-")))
4051 (if (string-match "\\^" vmarkers)
4052 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4053 (if (string-match "-" vmarkers)
4054 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4055 (if (> nl 0)
4056 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4057 (int-to-string nl) "\\}")))
4058 ;; Make the regexp
4059 (setq org-emph-re
4060 (concat "\\([" pre "]\\|^\\)"
4061 "\\("
4062 "\\([" markers "]\\)"
4063 "\\("
4064 "[^" border "]\\|"
4065 "[^" border "]"
4066 body1
4067 "[^" border "]"
4068 "\\)"
4069 "\\3\\)"
4070 "\\([" post "]\\|$\\)"))
4071 (setq org-verbatim-re
4072 (concat "\\([" pre "]\\|^\\)"
4073 "\\("
4074 "\\([" vmarkers "]\\)"
4075 "\\("
4076 "[^" border "]\\|"
4077 "[^" border "]"
4078 body1
4079 "[^" border "]"
4080 "\\)"
4081 "\\3\\)"
4082 "\\([" post "]\\|$\\)")))))
4084 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4085 ;; set this option proved cumbersome. See this message/thread:
4086 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4087 (defvar org-emphasis-regexp-components
4088 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4089 "Components used to build the regular expression for emphasis.
4090 This is a list with five entries. Terminology: In an emphasis string
4091 like \" *strong word* \", we call the initial space PREMATCH, the final
4092 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4093 and \"trong wor\" is the body. The different components in this variable
4094 specify what is allowed/forbidden in each part:
4096 pre Chars allowed as prematch. Beginning of line will be allowed too.
4097 post Chars allowed as postmatch. End of line will be allowed too.
4098 border The chars *forbidden* as border characters.
4099 body-regexp A regexp like \".\" to match a body character. Don't use
4100 non-shy groups here, and don't allow newline here.
4101 newline The maximum number of newlines allowed in an emphasis exp.
4103 You need to reload Org or to restart Emacs after customizing this.")
4105 (defcustom org-emphasis-alist
4106 `(("*" bold)
4107 ("/" italic)
4108 ("_" underline)
4109 ("=" org-code verbatim)
4110 ("~" org-verbatim verbatim)
4111 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4112 "Alist of characters and faces to emphasize text.
4113 Text starting and ending with a special character will be emphasized,
4114 for example *bold*, _underlined_ and /italic/. This variable sets the
4115 marker characters and the face to be used by font-lock for highlighting
4116 in Org-mode Emacs buffers.
4118 You need to reload Org or to restart Emacs after customizing this."
4119 :group 'org-appearance
4120 :set 'org-set-emph-re
4121 :version "24.4"
4122 :package-version '(Org . "8.0")
4123 :type '(repeat
4124 (list
4125 (string :tag "Marker character")
4126 (choice
4127 (face :tag "Font-lock-face")
4128 (plist :tag "Face property list"))
4129 (option (const verbatim)))))
4131 (defvar org-protecting-blocks
4132 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4133 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4134 This is needed for font-lock setup.")
4136 ;;; Miscellaneous options
4138 (defgroup org-completion nil
4139 "Completion in Org-mode."
4140 :tag "Org Completion"
4141 :group 'org)
4143 (defcustom org-completion-use-ido nil
4144 "Non-nil means use ido completion wherever possible.
4145 Note that `ido-mode' must be active for this variable to be relevant.
4146 If you decide to turn this variable on, you might well want to turn off
4147 `org-outline-path-complete-in-steps'.
4148 See also `org-completion-use-iswitchb'."
4149 :group 'org-completion
4150 :type 'boolean)
4152 (defcustom org-completion-use-iswitchb nil
4153 "Non-nil means use iswitchb completion wherever possible.
4154 Note that `iswitchb-mode' must be active for this variable to be relevant.
4155 If you decide to turn this variable on, you might well want to turn off
4156 `org-outline-path-complete-in-steps'.
4157 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4158 :group 'org-completion
4159 :type 'boolean)
4161 (defcustom org-completion-fallback-command 'hippie-expand
4162 "The expansion command called by \\[pcomplete] in normal context.
4163 Normal means, no org-mode-specific context."
4164 :group 'org-completion
4165 :type 'function)
4167 ;;; Functions and variables from their packages
4168 ;; Declared here to avoid compiler warnings
4170 ;; XEmacs only
4171 (defvar outline-mode-menu-heading)
4172 (defvar outline-mode-menu-show)
4173 (defvar outline-mode-menu-hide)
4174 (defvar zmacs-regions) ; XEmacs regions
4176 ;; Emacs only
4177 (defvar mark-active)
4179 ;; Various packages
4180 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4181 (declare-function calendar-forward-day "cal-move" (arg))
4182 (declare-function calendar-goto-date "cal-move" (date))
4183 (declare-function calendar-goto-today "cal-move" ())
4184 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4185 (defvar calc-embedded-close-formula)
4186 (defvar calc-embedded-open-formula)
4187 (declare-function cdlatex-tab "ext:cdlatex" ())
4188 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4189 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4190 (defvar font-lock-unfontify-region-function)
4191 (declare-function iswitchb-read-buffer "iswitchb"
4192 (prompt &optional default require-match start matches-set))
4193 (defvar iswitchb-temp-buflist)
4194 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4195 (defvar org-agenda-tags-todo-honor-ignore-options)
4196 (declare-function org-agenda-skip "org-agenda" ())
4197 (declare-function
4198 org-agenda-format-item "org-agenda"
4199 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4200 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4201 (declare-function org-agenda-change-all-lines "org-agenda"
4202 (newhead hdmarker &optional fixface just-this))
4203 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4204 (declare-function org-agenda-maybe-redo "org-agenda" ())
4205 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4206 (beg end))
4207 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4208 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4209 "org-agenda" (&optional end))
4210 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4211 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4212 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4213 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4214 (declare-function org-indent-mode "org-indent" (&optional arg))
4215 (declare-function parse-time-string "parse-time" (string))
4216 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4217 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4218 (defvar remember-data-file)
4219 (defvar texmathp-why)
4220 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4221 (declare-function table--at-cell-p "table" (position &optional object at-column))
4223 (defvar org-latex-regexps)
4225 ;;; Autoload and prepare some org modules
4227 ;; Some table stuff that needs to be defined here, because it is used
4228 ;; by the functions setting up org-mode or checking for table context.
4230 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4231 "Detect an org-type or table-type table.")
4232 (defconst org-table-line-regexp "^[ \t]*|"
4233 "Detect an org-type table line.")
4234 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4235 "Detect an org-type table line.")
4236 (defconst org-table-hline-regexp "^[ \t]*|-"
4237 "Detect an org-type table hline.")
4238 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4239 "Detect a table-type table hline.")
4240 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4241 "Detect the first line outside a table when searching from within it.
4242 This works for both table types.")
4244 ;; Autoload the functions in org-table.el that are needed by functions here.
4246 (eval-and-compile
4247 (org-autoload "org-table"
4248 '(org-table-begin org-table-blank-field org-table-end)))
4250 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4251 "Detect a #+TBLFM line.")
4253 ;;;###autoload
4254 (defun turn-on-orgtbl ()
4255 "Unconditionally turn on `orgtbl-mode'."
4256 (require 'org-table)
4257 (orgtbl-mode 1))
4259 (defun org-at-table-p (&optional table-type)
4260 "Return t if the cursor is inside an org-type table.
4261 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4262 (if org-enable-table-editor
4263 (save-excursion
4264 (beginning-of-line 1)
4265 (looking-at (if table-type org-table-any-line-regexp
4266 org-table-line-regexp)))
4267 nil))
4268 (defsubst org-table-p () (org-at-table-p))
4270 (defun org-at-table.el-p ()
4271 "Return t if and only if we are at a table.el table."
4272 (and (org-at-table-p 'any)
4273 (save-excursion
4274 (goto-char (org-table-begin 'any))
4275 (looking-at org-table1-hline-regexp))))
4277 (defun org-table-recognize-table.el ()
4278 "If there is a table.el table nearby, recognize it and move into it."
4279 (if org-table-tab-recognizes-table.el
4280 (if (org-at-table.el-p)
4281 (progn
4282 (beginning-of-line 1)
4283 (if (looking-at org-table-dataline-regexp)
4285 (if (looking-at org-table1-hline-regexp)
4286 (progn
4287 (beginning-of-line 2)
4288 (if (looking-at org-table-any-border-regexp)
4289 (beginning-of-line -1)))))
4290 (if (re-search-forward "|" (org-table-end t) t)
4291 (progn
4292 (require 'table)
4293 (if (table--at-cell-p (point))
4295 (message "recognizing table.el table...")
4296 (table-recognize-table)
4297 (message "recognizing table.el table...done")))
4298 (error "This should not happen"))
4300 nil)
4301 nil))
4303 (defun org-at-table-hline-p ()
4304 "Return t if the cursor is inside a hline in a table."
4305 (if org-enable-table-editor
4306 (save-excursion
4307 (beginning-of-line 1)
4308 (looking-at org-table-hline-regexp))
4309 nil))
4311 (defun org-table-map-tables (function &optional quietly)
4312 "Apply FUNCTION to the start of all tables in the buffer."
4313 (save-excursion
4314 (save-restriction
4315 (widen)
4316 (goto-char (point-min))
4317 (while (re-search-forward org-table-any-line-regexp nil t)
4318 (unless quietly
4319 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4320 (beginning-of-line 1)
4321 (when (and (looking-at org-table-line-regexp)
4322 ;; Exclude tables in src/example/verbatim/clocktable blocks
4323 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4324 (save-excursion (funcall function))
4325 (or (looking-at org-table-line-regexp)
4326 (forward-char 1)))
4327 (re-search-forward org-table-any-border-regexp nil 1))))
4328 (unless quietly (message "Mapping tables: done")))
4330 ;; Declare and autoload functions from org-agenda.el
4332 (eval-and-compile
4333 (org-autoload "org-agenda"
4334 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4336 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4337 (declare-function org-clock-update-mode-line "org-clock" ())
4338 (declare-function org-resolve-clocks "org-clock"
4339 (&optional also-non-dangling-p prompt last-valid))
4341 (defun org-at-TBLFM-p (&optional pos)
4342 "Return t when point (or POS) is in #+TBLFM line."
4343 (save-excursion
4344 (let ((pos pos)))
4345 (goto-char (or pos (point)))
4346 (beginning-of-line 1)
4347 (looking-at org-TBLFM-regexp)))
4349 (defvar org-clock-start-time)
4350 (defvar org-clock-marker (make-marker)
4351 "Marker recording the last clock-in.")
4352 (defvar org-clock-hd-marker (make-marker)
4353 "Marker recording the last clock-in, but the headline position.")
4354 (defvar org-clock-heading ""
4355 "The heading of the current clock entry.")
4356 (defun org-clock-is-active ()
4357 "Return the buffer where the clock is currently running.
4358 Return nil if no clock is running."
4359 (marker-buffer org-clock-marker))
4361 (eval-and-compile
4362 (org-autoload "org-clock" '(org-clock-remove-overlays
4363 org-clock-update-time-maybe
4364 org-clocktable-shift)))
4366 (defun org-check-running-clock ()
4367 "Check if the current buffer contains the running clock.
4368 If yes, offer to stop it and to save the buffer with the changes."
4369 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4370 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4371 (buffer-name))))
4372 (org-clock-out)
4373 (when (y-or-n-p "Save changed buffer?")
4374 (save-buffer))))
4376 (defun org-clocktable-try-shift (dir n)
4377 "Check if this line starts a clock table, if yes, shift the time block."
4378 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4379 (org-clocktable-shift dir n)))
4381 ;;;###autoload
4382 (defun org-clock-persistence-insinuate ()
4383 "Set up hooks for clock persistence."
4384 (require 'org-clock)
4385 (add-hook 'org-mode-hook 'org-clock-load)
4386 (add-hook 'kill-emacs-hook 'org-clock-save))
4388 ;; Define the variable already here, to make sure we have it.
4389 (defvar org-indent-mode nil
4390 "Non-nil if Org-Indent mode is enabled.
4391 Use the command `org-indent-mode' to change this variable.")
4393 ;; Autoload archiving code
4394 ;; The stuff that is needed for cycling and tags has to be defined here.
4396 (defgroup org-archive nil
4397 "Options concerning archiving in Org-mode."
4398 :tag "Org Archive"
4399 :group 'org-structure)
4401 (defcustom org-archive-location "%s_archive::"
4402 "The location where subtrees should be archived.
4404 The value of this variable is a string, consisting of two parts,
4405 separated by a double-colon. The first part is a filename and
4406 the second part is a headline.
4408 When the filename is omitted, archiving happens in the same file.
4409 %s in the filename will be replaced by the current file
4410 name (without the directory part). Archiving to a different file
4411 is useful to keep archived entries from contributing to the
4412 Org-mode Agenda.
4414 The archived entries will be filed as subtrees of the specified
4415 headline. When the headline is omitted, the subtrees are simply
4416 filed away at the end of the file, as top-level entries. Also in
4417 the heading you can use %s to represent the file name, this can be
4418 useful when using the same archive for a number of different files.
4420 Here are a few examples:
4421 \"%s_archive::\"
4422 If the current file is Projects.org, archive in file
4423 Projects.org_archive, as top-level trees. This is the default.
4425 \"::* Archived Tasks\"
4426 Archive in the current file, under the top-level headline
4427 \"* Archived Tasks\".
4429 \"~/org/archive.org::\"
4430 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4432 \"~/org/archive.org::* From %s\"
4433 Archive in file ~/org/archive.org (absolute path), under headlines
4434 \"From FILENAME\" where file name is the current file name.
4436 \"~/org/datetree.org::datetree/* Finished Tasks\"
4437 The \"datetree/\" string is special, signifying to archive
4438 items to the datetree. Items are placed in either the CLOSED
4439 date of the item, or the current date if there is no CLOSED date.
4440 The heading will be a subentry to the current date. There doesn't
4441 need to be a heading, but there always needs to be a slash after
4442 datetree. For example, to store archived items directly in the
4443 datetree, use \"~/org/datetree.org::datetree/\".
4445 \"basement::** Finished Tasks\"
4446 Archive in file ./basement (relative path), as level 3 trees
4447 below the level 2 heading \"** Finished Tasks\".
4449 You may set this option on a per-file basis by adding to the buffer a
4450 line like
4452 #+ARCHIVE: basement::** Finished Tasks
4454 You may also define it locally for a subtree by setting an ARCHIVE property
4455 in the entry. If such a property is found in an entry, or anywhere up
4456 the hierarchy, it will be used."
4457 :group 'org-archive
4458 :type 'string)
4460 (defcustom org-archive-tag "ARCHIVE"
4461 "The tag that marks a subtree as archived.
4462 An archived subtree does not open during visibility cycling, and does
4463 not contribute to the agenda listings.
4464 After changing this, font-lock must be restarted in the relevant buffers to
4465 get the proper fontification."
4466 :group 'org-archive
4467 :group 'org-keywords
4468 :type 'string)
4470 (defcustom org-agenda-skip-archived-trees t
4471 "Non-nil means the agenda will skip any items located in archived trees.
4472 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4473 variable is no longer recommended, you should leave it at the value t.
4474 Instead, use the key `v' to cycle the archives-mode in the agenda."
4475 :group 'org-archive
4476 :group 'org-agenda-skip
4477 :type 'boolean)
4479 (defcustom org-columns-skip-archived-trees t
4480 "Non-nil means ignore archived trees when creating column view."
4481 :group 'org-archive
4482 :group 'org-properties
4483 :type 'boolean)
4485 (defcustom org-cycle-open-archived-trees nil
4486 "Non-nil means `org-cycle' will open archived trees.
4487 An archived tree is a tree marked with the tag ARCHIVE.
4488 When nil, archived trees will stay folded. You can still open them with
4489 normal outline commands like `show-all', but not with the cycling commands."
4490 :group 'org-archive
4491 :group 'org-cycle
4492 :type 'boolean)
4494 (defcustom org-sparse-tree-open-archived-trees nil
4495 "Non-nil means sparse tree construction shows matches in archived trees.
4496 When nil, matches in these trees are highlighted, but the trees are kept in
4497 collapsed state."
4498 :group 'org-archive
4499 :group 'org-sparse-trees
4500 :type 'boolean)
4502 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4503 "The default date type when building a sparse tree.
4504 When this is nil, a date is a scheduled or a deadline timestamp.
4505 Otherwise, these types are allowed:
4507 all: all timestamps
4508 active: only active timestamps (<...>)
4509 inactive: only inactive timestamps (<...)
4510 scheduled: only scheduled timestamps
4511 deadline: only deadline timestamps"
4512 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4513 (const :tag "All timestamps" all)
4514 (const :tag "Only active timestamps" active)
4515 (const :tag "Only inactive timestamps" inactive)
4516 (const :tag "Only scheduled timestamps" scheduled)
4517 (const :tag "Only deadline timestamps" deadline)
4518 (const :tag "Only closed timestamps" closed))
4519 :version "24.3"
4520 :group 'org-sparse-trees)
4522 (defun org-cycle-hide-archived-subtrees (state)
4523 "Re-hide all archived subtrees after a visibility state change."
4524 (when (and (not org-cycle-open-archived-trees)
4525 (not (memq state '(overview folded))))
4526 (save-excursion
4527 (let* ((globalp (memq state '(contents all)))
4528 (beg (if globalp (point-min) (point)))
4529 (end (if globalp (point-max) (org-end-of-subtree t))))
4530 (org-hide-archived-subtrees beg end)
4531 (goto-char beg)
4532 (if (looking-at (concat ".*:" org-archive-tag ":"))
4533 (message "%s" (substitute-command-keys
4534 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4536 (defun org-force-cycle-archived ()
4537 "Cycle subtree even if it is archived."
4538 (interactive)
4539 (setq this-command 'org-cycle)
4540 (let ((org-cycle-open-archived-trees t))
4541 (call-interactively 'org-cycle)))
4543 (defun org-hide-archived-subtrees (beg end)
4544 "Re-hide all archived subtrees after a visibility state change."
4545 (save-excursion
4546 (let* ((re (concat ":" org-archive-tag ":")))
4547 (goto-char beg)
4548 (while (re-search-forward re end t)
4549 (when (org-at-heading-p)
4550 (org-flag-subtree t)
4551 (org-end-of-subtree t))))))
4553 (declare-function outline-end-of-heading "outline" ())
4554 (declare-function outline-flag-region "outline" (from to flag))
4555 (defun org-flag-subtree (flag)
4556 (save-excursion
4557 (org-back-to-heading t)
4558 (outline-end-of-heading)
4559 (outline-flag-region (point)
4560 (progn (org-end-of-subtree t) (point))
4561 flag)))
4563 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4565 (eval-and-compile
4566 (org-autoload "org-archive"
4567 '(org-add-archive-files)))
4569 ;; Autoload Column View Code
4571 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4572 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4573 (declare-function org-columns-compute "org-colview" (property))
4575 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4576 '(org-columns-number-to-string
4577 org-columns-get-format-and-top-level
4578 org-columns-compute
4579 org-columns-remove-overlays))
4581 ;; Autoload ID code
4583 (declare-function org-id-store-link "org-id")
4584 (declare-function org-id-locations-load "org-id")
4585 (declare-function org-id-locations-save "org-id")
4586 (defvar org-id-track-globally)
4587 (org-autoload "org-id"
4588 '(org-id-new
4589 org-id-copy
4590 org-id-get-with-outline-path-completion
4591 org-id-get-with-outline-drilling))
4593 ;;; Variables for pre-computed regular expressions, all buffer local
4595 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4596 "Matches first line of a hidden block.")
4597 (make-variable-buffer-local 'org-drawer-regexp)
4598 (defvar org-todo-regexp nil
4599 "Matches any of the TODO state keywords.")
4600 (make-variable-buffer-local 'org-todo-regexp)
4601 (defvar org-not-done-regexp nil
4602 "Matches any of the TODO state keywords except the last one.")
4603 (make-variable-buffer-local 'org-not-done-regexp)
4604 (defvar org-not-done-heading-regexp nil
4605 "Matches a TODO headline that is not done.")
4606 (make-variable-buffer-local 'org-not-done-regexp)
4607 (defvar org-todo-line-regexp nil
4608 "Matches a headline and puts TODO state into group 2 if present.")
4609 (make-variable-buffer-local 'org-todo-line-regexp)
4610 (defvar org-complex-heading-regexp nil
4611 "Matches a headline and puts everything into groups:
4612 group 1: the stars
4613 group 2: The todo keyword, maybe
4614 group 3: Priority cookie
4615 group 4: True headline
4616 group 5: Tags")
4617 (make-variable-buffer-local 'org-complex-heading-regexp)
4618 (defvar org-complex-heading-regexp-format nil
4619 "Printf format to make regexp to match an exact headline.
4620 This regexp will match the headline of any node which has the
4621 exact headline text that is put into the format, but may have any
4622 TODO state, priority and tags.")
4623 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4624 (defvar org-todo-line-tags-regexp nil
4625 "Matches a headline and puts TODO state into group 2 if present.
4626 Also put tags into group 4 if tags are present.")
4627 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4628 (defvar org-ds-keyword-length 12
4629 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4630 (make-variable-buffer-local 'org-ds-keyword-length)
4631 (defvar org-deadline-regexp nil
4632 "Matches the DEADLINE keyword.")
4633 (make-variable-buffer-local 'org-deadline-regexp)
4634 (defvar org-deadline-time-regexp nil
4635 "Matches the DEADLINE keyword together with a time stamp.")
4636 (make-variable-buffer-local 'org-deadline-time-regexp)
4637 (defvar org-deadline-time-hour-regexp nil
4638 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4639 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4640 (defvar org-deadline-line-regexp nil
4641 "Matches the DEADLINE keyword and the rest of the line.")
4642 (make-variable-buffer-local 'org-deadline-line-regexp)
4643 (defvar org-scheduled-regexp nil
4644 "Matches the SCHEDULED keyword.")
4645 (make-variable-buffer-local 'org-scheduled-regexp)
4646 (defvar org-scheduled-time-regexp nil
4647 "Matches the SCHEDULED keyword together with a time stamp.")
4648 (make-variable-buffer-local 'org-scheduled-time-regexp)
4649 (defvar org-scheduled-time-hour-regexp nil
4650 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4651 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4652 (defvar org-closed-time-regexp nil
4653 "Matches the CLOSED keyword together with a time stamp.")
4654 (make-variable-buffer-local 'org-closed-time-regexp)
4656 (defvar org-keyword-time-regexp nil
4657 "Matches any of the 4 keywords, together with the time stamp.")
4658 (make-variable-buffer-local 'org-keyword-time-regexp)
4659 (defvar org-keyword-time-not-clock-regexp nil
4660 "Matches any of the 3 keywords, together with the time stamp.")
4661 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4662 (defvar org-maybe-keyword-time-regexp nil
4663 "Matches a timestamp, possibly preceded by a keyword.")
4664 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4665 (defvar org-all-time-keywords nil
4666 "List of time keywords.")
4667 (make-variable-buffer-local 'org-all-time-keywords)
4669 (defconst org-plain-time-of-day-regexp
4670 (concat
4671 "\\(\\<[012]?[0-9]"
4672 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4673 "\\(--?"
4674 "\\(\\<[012]?[0-9]"
4675 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4676 "\\)?")
4677 "Regular expression to match a plain time or time range.
4678 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4679 groups carry important information:
4680 0 the full match
4681 1 the first time, range or not
4682 8 the second time, if it is a range.")
4684 (defconst org-plain-time-extension-regexp
4685 (concat
4686 "\\(\\<[012]?[0-9]"
4687 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4688 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4689 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4690 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4691 groups carry important information:
4692 0 the full match
4693 7 hours of duration
4694 9 minutes of duration")
4696 (defconst org-stamp-time-of-day-regexp
4697 (concat
4698 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4699 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4700 "\\(--?"
4701 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4702 "Regular expression to match a timestamp time or time range.
4703 After a match, the following groups carry important information:
4704 0 the full match
4705 1 date plus weekday, for back referencing to make sure both times are on the same day
4706 2 the first time, range or not
4707 4 the second time, if it is a range.")
4709 (defconst org-startup-options
4710 '(("fold" org-startup-folded t)
4711 ("overview" org-startup-folded t)
4712 ("nofold" org-startup-folded nil)
4713 ("showall" org-startup-folded nil)
4714 ("showeverything" org-startup-folded showeverything)
4715 ("content" org-startup-folded content)
4716 ("indent" org-startup-indented t)
4717 ("noindent" org-startup-indented nil)
4718 ("hidestars" org-hide-leading-stars t)
4719 ("showstars" org-hide-leading-stars nil)
4720 ("odd" org-odd-levels-only t)
4721 ("oddeven" org-odd-levels-only nil)
4722 ("align" org-startup-align-all-tables t)
4723 ("noalign" org-startup-align-all-tables nil)
4724 ("inlineimages" org-startup-with-inline-images t)
4725 ("noinlineimages" org-startup-with-inline-images nil)
4726 ("latexpreview" org-startup-with-latex-preview t)
4727 ("nolatexpreview" org-startup-with-latex-preview nil)
4728 ("customtime" org-display-custom-times t)
4729 ("logdone" org-log-done time)
4730 ("lognotedone" org-log-done note)
4731 ("nologdone" org-log-done nil)
4732 ("lognoteclock-out" org-log-note-clock-out t)
4733 ("nolognoteclock-out" org-log-note-clock-out nil)
4734 ("logrepeat" org-log-repeat state)
4735 ("lognoterepeat" org-log-repeat note)
4736 ("logdrawer" org-log-into-drawer t)
4737 ("nologdrawer" org-log-into-drawer nil)
4738 ("logstatesreversed" org-log-states-order-reversed t)
4739 ("nologstatesreversed" org-log-states-order-reversed nil)
4740 ("nologrepeat" org-log-repeat nil)
4741 ("logreschedule" org-log-reschedule time)
4742 ("lognotereschedule" org-log-reschedule note)
4743 ("nologreschedule" org-log-reschedule nil)
4744 ("logredeadline" org-log-redeadline time)
4745 ("lognoteredeadline" org-log-redeadline note)
4746 ("nologredeadline" org-log-redeadline nil)
4747 ("logrefile" org-log-refile time)
4748 ("lognoterefile" org-log-refile note)
4749 ("nologrefile" org-log-refile nil)
4750 ("fninline" org-footnote-define-inline t)
4751 ("nofninline" org-footnote-define-inline nil)
4752 ("fnlocal" org-footnote-section nil)
4753 ("fnauto" org-footnote-auto-label t)
4754 ("fnprompt" org-footnote-auto-label nil)
4755 ("fnconfirm" org-footnote-auto-label confirm)
4756 ("fnplain" org-footnote-auto-label plain)
4757 ("fnadjust" org-footnote-auto-adjust t)
4758 ("nofnadjust" org-footnote-auto-adjust nil)
4759 ("constcgs" constants-unit-system cgs)
4760 ("constSI" constants-unit-system SI)
4761 ("noptag" org-tag-persistent-alist nil)
4762 ("hideblocks" org-hide-block-startup t)
4763 ("nohideblocks" org-hide-block-startup nil)
4764 ("beamer" org-startup-with-beamer-mode t)
4765 ("entitiespretty" org-pretty-entities t)
4766 ("entitiesplain" org-pretty-entities nil))
4767 "Variable associated with STARTUP options for org-mode.
4768 Each element is a list of three items: the startup options (as written
4769 in the #+STARTUP line), the corresponding variable, and the value to set
4770 this variable to if the option is found. An optional forth element PUSH
4771 means to push this value onto the list in the variable.")
4773 (defun org-update-property-plist (key val props)
4774 "Update PROPS with KEY and VAL."
4775 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4776 (key (if appending (substring key 0 (- (length key) 1)) key))
4777 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4778 (previous (cdr (assoc key props))))
4779 (if appending
4780 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4781 (cons (cons key val) remainder))))
4783 (defconst org-block-regexp
4784 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4785 "Regular expression for hiding blocks.")
4786 (defconst org-heading-keyword-regexp-format
4787 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4788 "Printf format for a regexp matching a headline with some keyword.
4789 This regexp will match the headline of any node which has the
4790 exact keyword that is put into the format. The keyword isn't in
4791 any group by default, but the stars and the body are.")
4792 (defconst org-heading-keyword-maybe-regexp-format
4793 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4794 "Printf format for a regexp matching a headline, possibly with some keyword.
4795 This regexp can match any headline with the specified keyword, or
4796 without a keyword. The keyword isn't in any group by default,
4797 but the stars and the body are.")
4799 (defcustom org-group-tags t
4800 "When non-nil (the default), use group tags.
4801 This can be turned on/off through `org-toggle-tags-groups'."
4802 :group 'org-tags
4803 :group 'org-startup
4804 :type 'boolean)
4806 (defun org-toggle-tags-groups ()
4807 "Toggle support for group tags.
4808 Support for group tags is controlled by the option
4809 `org-group-tags', which is non-nil by default."
4810 (interactive)
4811 (setq org-group-tags (not org-group-tags))
4812 (cond ((and (derived-mode-p 'org-agenda-mode)
4813 org-group-tags)
4814 (org-agenda-redo))
4815 ((derived-mode-p 'org-mode)
4816 (let ((org-inhibit-startup t)) (org-mode))))
4817 (message "Groups tags support has been turned %s"
4818 (if org-group-tags "on" "off")))
4820 (defun org-set-regexps-and-options-for-tags ()
4821 "Precompute variables used for tags."
4822 (when (derived-mode-p 'org-mode)
4823 (org-set-local 'org-file-tags nil)
4824 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4825 (splitre "[ \t]+")
4826 (start 0)
4827 tags ftags key value)
4828 (save-excursion
4829 (save-restriction
4830 (widen)
4831 (goto-char (point-min))
4832 (while (re-search-forward re nil t)
4833 (setq key (upcase (org-match-string-no-properties 1))
4834 value (org-match-string-no-properties 2))
4835 (if (stringp value) (setq value (org-trim value)))
4836 (cond
4837 ((equal key "TAGS")
4838 (setq tags (append tags (if tags '("\\n") nil)
4839 (org-split-string value splitre))))
4840 ((equal key "FILETAGS")
4841 (when (string-match "\\S-" value)
4842 (setq ftags
4843 (append
4844 ftags
4845 (apply 'append
4846 (mapcar (lambda (x) (org-split-string x ":"))
4847 (org-split-string value)))))))))))
4848 ;; Process the file tags.
4849 (and ftags (org-set-local 'org-file-tags
4850 (mapcar 'org-add-prop-inherited ftags)))
4851 (org-set-local 'org-tag-groups-alist nil)
4852 ;; Process the tags.
4853 (when (and (not tags) org-tag-alist)
4854 (setq tags
4855 (mapcar
4856 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4857 ((eq (car tg) :endgroup) "}")
4858 ((eq (car tg) :grouptags) ":")
4859 ((eq (car tg) :newline) "\n")
4860 (t (concat (car tg)
4861 (if (characterp (cdr tg))
4862 (format "(%s)" (char-to-string (cdr tg))) "")))))
4863 org-tag-alist)))
4864 (let (e tgs g)
4865 (while (setq e (pop tags))
4866 (cond
4867 ((equal e "{")
4868 (progn (push '(:startgroup) tgs)
4869 (when (equal (nth 1 tags) ":")
4870 (push (list (replace-regexp-in-string
4871 "(.+)$" "" (nth 0 tags)))
4872 org-tag-groups-alist)
4873 (setq g 0))))
4874 ((equal e ":") (push '(:grouptags) tgs))
4875 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4876 ((equal e "\\n") (push '(:newline) tgs))
4877 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4878 (push (cons (match-string 1 e)
4879 (string-to-char (match-string 2 e))) tgs)
4880 (if (and g (> g 0))
4881 (setcar org-tag-groups-alist
4882 (append (car org-tag-groups-alist)
4883 (list (match-string 1 e)))))
4884 (if g (setq g (1+ g))))
4885 (t (push (list e) tgs)
4886 (if (and g (> g 0))
4887 (setcar org-tag-groups-alist
4888 (append (car org-tag-groups-alist) (list e))))
4889 (if g (setq g (1+ g))))))
4890 (org-set-local 'org-tag-alist nil)
4891 (while (setq e (pop tgs))
4892 (or (and (stringp (car e))
4893 (assoc (car e) org-tag-alist))
4894 (push e org-tag-alist)))
4895 ;; Return a list with tag variables
4896 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4898 (defvar org-ota nil)
4899 (defun org-set-regexps-and-options ()
4900 "Precompute regular expressions used in the current buffer."
4901 (when (derived-mode-p 'org-mode)
4902 (org-set-local 'org-todo-kwd-alist nil)
4903 (org-set-local 'org-todo-key-alist nil)
4904 (org-set-local 'org-todo-key-trigger nil)
4905 (org-set-local 'org-todo-keywords-1 nil)
4906 (org-set-local 'org-done-keywords nil)
4907 (org-set-local 'org-todo-heads nil)
4908 (org-set-local 'org-todo-sets nil)
4909 (org-set-local 'org-todo-log-states nil)
4910 (org-set-local 'org-file-properties nil)
4911 (let ((re (org-make-options-regexp
4912 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4913 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4914 "SETUPFILE" "OPTIONS")
4915 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4916 (splitre "[ \t]+")
4917 (scripts org-use-sub-superscripts)
4918 kwds kws0 kwsa key log value cat arch const links hw dws
4919 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4920 (start 0))
4921 (save-excursion
4922 (save-restriction
4923 (widen)
4924 (goto-char (point-min))
4925 (while
4926 (or (and
4927 ext-setup-or-nil
4928 (not org-ota)
4929 (let (ret)
4930 (with-temp-buffer
4931 (insert ext-setup-or-nil)
4932 (let ((major-mode 'org-mode) org-ota)
4933 (setq ret (save-match-data
4934 (org-set-regexps-and-options-for-tags)))))
4935 ;; Append setupfile tags to existing tags
4936 (setq org-ota t)
4937 (setq org-file-tags
4938 (delq nil (append org-file-tags (nth 0 ret)))
4939 org-tag-alist
4940 (delq nil (append org-tag-alist (nth 1 ret)))
4941 org-tag-groups-alist
4942 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4943 (and ext-setup-or-nil
4944 (string-match re ext-setup-or-nil start)
4945 (setq start (match-end 0)))
4946 (and (setq ext-setup-or-nil nil start 0)
4947 (re-search-forward re nil t)))
4948 (setq key (upcase (match-string 1 ext-setup-or-nil))
4949 value (org-match-string-no-properties 2 ext-setup-or-nil))
4950 (if (stringp value) (setq value (org-trim value)))
4951 (cond
4952 ((equal key "CATEGORY")
4953 (setq cat value))
4954 ((member key '("SEQ_TODO" "TODO"))
4955 (push (cons 'sequence (org-split-string value splitre)) kwds))
4956 ((equal key "TYP_TODO")
4957 (push (cons 'type (org-split-string value splitre)) kwds))
4958 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4959 ;; general TODO-like setup
4960 (push (cons (intern (downcase (match-string 1 key)))
4961 (org-split-string value splitre)) kwds))
4962 ((equal key "COLUMNS")
4963 (org-set-local 'org-columns-default-format value))
4964 ((equal key "LINK")
4965 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4966 (push (cons (match-string 1 value)
4967 (org-trim (match-string 2 value)))
4968 links)))
4969 ((equal key "PRIORITIES")
4970 (setq prio (org-split-string value " +")))
4971 ((equal key "PROPERTY")
4972 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4973 (setq props (org-update-property-plist (match-string 1 value)
4974 (match-string 2 value)
4975 props))))
4976 ((equal key "DRAWERS")
4977 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4978 ((equal key "CONSTANTS")
4979 (org-table-set-constants))
4980 ((equal key "STARTUP")
4981 (let ((opts (org-split-string value splitre))
4982 l var val)
4983 (while (setq l (pop opts))
4984 (when (setq l (assoc l org-startup-options))
4985 (setq var (nth 1 l) val (nth 2 l))
4986 (if (not (nth 3 l))
4987 (set (make-local-variable var) val)
4988 (if (not (listp (symbol-value var)))
4989 (set (make-local-variable var) nil))
4990 (set (make-local-variable var) (symbol-value var))
4991 (add-to-list var val))))))
4992 ((equal key "ARCHIVE")
4993 (setq arch value)
4994 (remove-text-properties 0 (length arch)
4995 '(face t fontified t) arch))
4996 ((equal key "OPTIONS")
4997 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4998 (setq scripts (read (match-string 2 value)))))
4999 ((and (equal key "SETUPFILE")
5000 ;; Prevent checking in Gnus messages
5001 (not buffer-read-only))
5002 (setq setup-contents (org-file-contents
5003 (expand-file-name
5004 (org-remove-double-quotes value))
5005 'noerror))
5006 (if (not ext-setup-or-nil)
5007 (setq ext-setup-or-nil setup-contents start 0)
5008 (setq ext-setup-or-nil
5009 (concat (substring ext-setup-or-nil 0 start)
5010 "\n" setup-contents "\n"
5011 (substring ext-setup-or-nil start)))))))
5012 ;; search for property blocks
5013 (goto-char (point-min))
5014 (while (re-search-forward org-block-regexp nil t)
5015 (when (equal "PROPERTY" (upcase (match-string 1)))
5016 (setq value (replace-regexp-in-string
5017 "[\n\r]" " " (match-string 4)))
5018 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5019 (setq props (org-update-property-plist (match-string 1 value)
5020 (match-string 2 value)
5021 props)))))))
5022 (org-set-local 'org-use-sub-superscripts scripts)
5023 (when cat
5024 (org-set-local 'org-category (intern cat))
5025 (push (cons "CATEGORY" cat) props))
5026 (when prio
5027 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5028 (setq prio (mapcar 'string-to-char prio))
5029 (org-set-local 'org-highest-priority (nth 0 prio))
5030 (org-set-local 'org-lowest-priority (nth 1 prio))
5031 (org-set-local 'org-default-priority (nth 2 prio)))
5032 (and props (org-set-local 'org-file-properties (nreverse props)))
5033 (and drawers (org-set-local 'org-drawers drawers))
5034 (and arch (org-set-local 'org-archive-location arch))
5035 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5036 ;; Process the TODO keywords
5037 (unless kwds
5038 ;; Use the global values as if they had been given locally.
5039 (setq kwds (default-value 'org-todo-keywords))
5040 (if (stringp (car kwds))
5041 (setq kwds (list (cons org-todo-interpretation
5042 (default-value 'org-todo-keywords)))))
5043 (setq kwds (reverse kwds)))
5044 (setq kwds (nreverse kwds))
5045 (let (inter kws kw)
5046 (while (setq kws (pop kwds))
5047 (let ((kws (or
5048 (run-hook-with-args-until-success
5049 'org-todo-setup-filter-hook kws)
5050 kws)))
5051 (setq inter (pop kws) sep (member "|" kws)
5052 kws0 (delete "|" (copy-sequence kws))
5053 kwsa nil
5054 kws1 (mapcar
5055 (lambda (x)
5056 ;; 1 2
5057 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5058 (progn
5059 (setq kw (match-string 1 x)
5060 key (and (match-end 2) (match-string 2 x))
5061 log (org-extract-log-state-settings x))
5062 (push (cons kw (and key (string-to-char key))) kwsa)
5063 (and log (push log org-todo-log-states))
5065 (error "Invalid TODO keyword %s" x)))
5066 kws0)
5067 kwsa (if kwsa (append '((:startgroup))
5068 (nreverse kwsa)
5069 '((:endgroup))))
5070 hw (car kws1)
5071 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5072 tail (list inter hw (car dws) (org-last dws))))
5073 (add-to-list 'org-todo-heads hw 'append)
5074 (push kws1 org-todo-sets)
5075 (setq org-done-keywords (append org-done-keywords dws nil))
5076 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5077 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5078 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5079 (setq org-todo-sets (nreverse org-todo-sets)
5080 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5081 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5082 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5083 ;; Compute the regular expressions and other local variables.
5084 ;; Using `org-outline-regexp-bol' would complicate them much,
5085 ;; because of the fixed white space at the end of that string.
5086 (if (not org-done-keywords)
5087 (setq org-done-keywords (and org-todo-keywords-1
5088 (list (org-last org-todo-keywords-1)))))
5089 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5090 (length org-scheduled-string)
5091 (length org-clock-string)
5092 (length org-closed-string)))
5093 org-drawer-regexp
5094 (concat "^[ \t]*:\\("
5095 (mapconcat 'regexp-quote org-drawers "\\|")
5096 "\\):[ \t]*$")
5097 org-not-done-keywords
5098 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5099 org-todo-regexp
5100 (concat "\\("
5101 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5102 "\\)")
5103 org-not-done-regexp
5104 (concat "\\("
5105 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5106 "\\)")
5107 org-not-done-heading-regexp
5108 (format org-heading-keyword-regexp-format org-not-done-regexp)
5109 org-todo-line-regexp
5110 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5111 org-complex-heading-regexp
5112 (concat "^\\(\\*+\\)"
5113 "\\(?: +" org-todo-regexp "\\)?"
5114 "\\(?: +\\(\\[#.\\]\\)\\)?"
5115 "\\(?: +\\(.*?\\)\\)??"
5116 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5117 "[ \t]*$")
5118 org-complex-heading-regexp-format
5119 (concat "^\\(\\*+\\)"
5120 "\\(?: +" org-todo-regexp "\\)?"
5121 "\\(?: +\\(\\[#.\\]\\)\\)?"
5122 "\\(?: +"
5123 ;; Stats cookies can be stuck to body.
5124 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5125 "\\(%s\\)"
5126 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5127 "\\)"
5128 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5129 "[ \t]*$")
5130 org-todo-line-tags-regexp
5131 (concat "^\\(\\*+\\)"
5132 "\\(?: +" org-todo-regexp "\\)?"
5133 "\\(?: +\\(.*?\\)\\)??"
5134 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5135 "[ \t]*$")
5136 org-deadline-regexp (concat "\\<" org-deadline-string)
5137 org-deadline-time-regexp
5138 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5139 org-deadline-time-hour-regexp
5140 (concat "\\<" org-deadline-string
5141 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5142 org-deadline-line-regexp
5143 (concat "\\<\\(" org-deadline-string "\\).*")
5144 org-scheduled-regexp
5145 (concat "\\<" org-scheduled-string)
5146 org-scheduled-time-regexp
5147 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5148 org-scheduled-time-hour-regexp
5149 (concat "\\<" org-scheduled-string
5150 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5151 org-closed-time-regexp
5152 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5153 org-keyword-time-regexp
5154 (concat "\\<\\(" org-scheduled-string
5155 "\\|" org-deadline-string
5156 "\\|" org-closed-string
5157 "\\|" org-clock-string "\\)"
5158 " *[[<]\\([^]>]+\\)[]>]")
5159 org-keyword-time-not-clock-regexp
5160 (concat "\\<\\(" org-scheduled-string
5161 "\\|" org-deadline-string
5162 "\\|" org-closed-string
5163 "\\)"
5164 " *[[<]\\([^]>]+\\)[]>]")
5165 org-maybe-keyword-time-regexp
5166 (concat "\\(\\<\\(" org-scheduled-string
5167 "\\|" org-deadline-string
5168 "\\|" org-closed-string
5169 "\\|" org-clock-string "\\)\\)?"
5170 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5171 org-all-time-keywords
5172 (mapcar (lambda (w) (substring w 0 -1))
5173 (list org-scheduled-string org-deadline-string
5174 org-clock-string org-closed-string)))
5175 (setq org-ota nil)
5176 (org-compute-latex-and-related-regexp))))
5178 (defun org-file-contents (file &optional noerror)
5179 "Return the contents of FILE, as a string."
5180 (if (or (not file)
5181 (not (file-readable-p file)))
5182 (if noerror
5183 (message "Cannot read file \"%s\"" file)
5184 (error "Cannot read file \"%s\"" file))
5185 (with-temp-buffer
5186 (insert-file-contents file)
5187 (buffer-string))))
5189 (defun org-extract-log-state-settings (x)
5190 "Extract the log state setting from a TODO keyword string.
5191 This will extract info from a string like \"WAIT(w@/!)\"."
5192 (let (kw key log1 log2)
5193 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5194 (setq kw (match-string 1 x)
5195 key (and (match-end 2) (match-string 2 x))
5196 log1 (and (match-end 3) (match-string 3 x))
5197 log2 (and (match-end 4) (match-string 4 x)))
5198 (and (or log1 log2)
5199 (list kw
5200 (and log1 (if (equal log1 "!") 'time 'note))
5201 (and log2 (if (equal log2 "!") 'time 'note)))))))
5203 (defun org-remove-keyword-keys (list)
5204 "Remove a pair of parenthesis at the end of each string in LIST."
5205 (mapcar (lambda (x)
5206 (if (string-match "(.*)$" x)
5207 (substring x 0 (match-beginning 0))
5209 list))
5211 (defun org-assign-fast-keys (alist)
5212 "Assign fast keys to a keyword-key alist.
5213 Respect keys that are already there."
5214 (let (new e (alt ?0))
5215 (while (setq e (pop alist))
5216 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5217 (cdr e)) ;; Key already assigned.
5218 (push e new)
5219 (let ((clist (string-to-list (downcase (car e))))
5220 (used (append new alist)))
5221 (when (= (car clist) ?@)
5222 (pop clist))
5223 (while (and clist (rassoc (car clist) used))
5224 (pop clist))
5225 (unless clist
5226 (while (rassoc alt used)
5227 (incf alt)))
5228 (push (cons (car e) (or (car clist) alt)) new))))
5229 (nreverse new)))
5231 ;;; Some variables used in various places
5233 (defvar org-window-configuration nil
5234 "Used in various places to store a window configuration.")
5235 (defvar org-selected-window nil
5236 "Used in various places to store a window configuration.")
5237 (defvar org-finish-function nil
5238 "Function to be called when `C-c C-c' is used.
5239 This is for getting out of special buffers like capture.")
5242 ;; FIXME: Occasionally check by commenting these, to make sure
5243 ;; no other functions uses these, forgetting to let-bind them.
5244 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5245 (defvar org-last-state)
5246 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5248 ;; Defined somewhere in this file, but used before definition.
5249 (defvar org-entities) ;; defined in org-entities.el
5250 (defvar org-struct-menu)
5251 (defvar org-org-menu)
5252 (defvar org-tbl-menu)
5254 ;;;; Define the Org-mode
5256 ;; We use a before-change function to check if a table might need
5257 ;; an update.
5258 (defvar org-table-may-need-update t
5259 "Indicates that a table might need an update.
5260 This variable is set by `org-before-change-function'.
5261 `org-table-align' sets it back to nil.")
5262 (defun org-before-change-function (beg end)
5263 "Every change indicates that a table might need an update."
5264 (setq org-table-may-need-update t))
5265 (defvar org-mode-map)
5266 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5267 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5268 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5269 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5270 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5271 (defvar org-table-buffer-is-an nil)
5273 (defvar bidi-paragraph-direction)
5274 (defvar buffer-face-mode-face)
5276 (require 'outline)
5277 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5278 (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"))
5279 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5281 ;; Other stuff we need.
5282 (require 'time-date)
5283 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5284 (require 'easymenu)
5285 (require 'overlay)
5287 ;; (require 'org-macs) moved higher up in the file before it is first used
5288 (require 'org-entities)
5289 ;; (require 'org-compat) moved higher up in the file before it is first used
5290 (require 'org-faces)
5291 (require 'org-list)
5292 (require 'org-pcomplete)
5293 (require 'org-src)
5294 (require 'org-footnote)
5295 (require 'org-macro)
5297 ;; babel
5298 (require 'ob)
5300 ;;;###autoload
5301 (define-derived-mode org-mode outline-mode "Org"
5302 "Outline-based notes management and organizer, alias
5303 \"Carsten's outline-mode for keeping track of everything.\"
5305 Org-mode develops organizational tasks around a NOTES file which
5306 contains information about projects as plain text. Org-mode is
5307 implemented on top of outline-mode, which is ideal to keep the content
5308 of large files well structured. It supports ToDo items, deadlines and
5309 time stamps, which magically appear in the diary listing of the Emacs
5310 calendar. Tables are easily created with a built-in table editor.
5311 Plain text URL-like links connect to websites, emails (VM), Usenet
5312 messages (Gnus), BBDB entries, and any files related to the project.
5313 For printing and sharing of notes, an Org-mode file (or a part of it)
5314 can be exported as a structured ASCII or HTML file.
5316 The following commands are available:
5318 \\{org-mode-map}"
5320 ;; Get rid of Outline menus, they are not needed
5321 ;; Need to do this here because define-derived-mode sets up
5322 ;; the keymap so late. Still, it is a waste to call this each time
5323 ;; we switch another buffer into org-mode.
5324 (if (featurep 'xemacs)
5325 (when (boundp 'outline-mode-menu-heading)
5326 ;; Assume this is Greg's port, it uses easymenu
5327 (easy-menu-remove outline-mode-menu-heading)
5328 (easy-menu-remove outline-mode-menu-show)
5329 (easy-menu-remove outline-mode-menu-hide))
5330 (define-key org-mode-map [menu-bar headings] 'undefined)
5331 (define-key org-mode-map [menu-bar hide] 'undefined)
5332 (define-key org-mode-map [menu-bar show] 'undefined))
5334 (org-load-modules-maybe)
5335 (easy-menu-add org-org-menu)
5336 (easy-menu-add org-tbl-menu)
5337 (org-install-agenda-files-menu)
5338 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5339 (add-to-invisibility-spec '(org-cwidth))
5340 (add-to-invisibility-spec '(org-hide-block . t))
5341 (when (featurep 'xemacs)
5342 (org-set-local 'line-move-ignore-invisible t))
5343 (org-set-local 'outline-regexp org-outline-regexp)
5344 (org-set-local 'outline-level 'org-outline-level)
5345 (setq bidi-paragraph-direction 'left-to-right)
5346 (when (and org-ellipsis
5347 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5348 (fboundp 'make-glyph-code))
5349 (unless org-display-table
5350 (setq org-display-table (make-display-table)))
5351 (set-display-table-slot
5352 org-display-table 4
5353 (vconcat (mapcar
5354 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5355 org-ellipsis)))
5356 (if (stringp org-ellipsis) org-ellipsis "..."))))
5357 (setq buffer-display-table org-display-table))
5358 (org-set-regexps-and-options-for-tags)
5359 (org-set-regexps-and-options)
5360 (org-set-font-lock-defaults)
5361 (when (and org-tag-faces (not org-tags-special-faces-re))
5362 ;; tag faces set outside customize.... force initialization.
5363 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5364 ;; Calc embedded
5365 (org-set-local 'calc-embedded-open-mode "# ")
5366 ;; Modify a few syntax entries
5367 (modify-syntax-entry ?@ "w")
5368 (modify-syntax-entry ?\" "\"")
5369 (if org-startup-truncated (setq truncate-lines t))
5370 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5371 (org-set-local 'font-lock-unfontify-region-function
5372 'org-unfontify-region)
5373 ;; Activate before-change-function
5374 (org-set-local 'org-table-may-need-update t)
5375 (org-add-hook 'before-change-functions 'org-before-change-function nil
5376 'local)
5377 ;; Check for running clock before killing a buffer
5378 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5379 ;; Initialize macros templates.
5380 (org-macro-initialize-templates)
5381 ;; Initialize radio targets.
5382 (org-update-radio-target-regexp)
5383 ;; Indentation.
5384 (org-set-local 'indent-line-function 'org-indent-line)
5385 (org-set-local 'indent-region-function 'org-indent-region)
5386 ;; Filling and auto-filling.
5387 (org-setup-filling)
5388 ;; Comments.
5389 (org-setup-comments-handling)
5390 ;; Beginning/end of defun
5391 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5392 (org-set-local 'end-of-defun-function 'org-forward-element)
5393 ;; Next error for sparse trees
5394 (org-set-local 'next-error-function 'org-occur-next-match)
5395 ;; Make sure dependence stuff works reliably, even for users who set it
5396 ;; too late :-(
5397 (if org-enforce-todo-dependencies
5398 (add-hook 'org-blocker-hook
5399 'org-block-todo-from-children-or-siblings-or-parent)
5400 (remove-hook 'org-blocker-hook
5401 'org-block-todo-from-children-or-siblings-or-parent))
5402 (if org-enforce-todo-checkbox-dependencies
5403 (add-hook 'org-blocker-hook
5404 'org-block-todo-from-checkboxes)
5405 (remove-hook 'org-blocker-hook
5406 'org-block-todo-from-checkboxes))
5408 ;; Align options lines
5409 (org-set-local
5410 'align-mode-rules-list
5411 '((org-in-buffer-settings
5412 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5413 (modes . '(org-mode)))))
5415 ;; Imenu
5416 (org-set-local 'imenu-create-index-function
5417 'org-imenu-get-tree)
5419 ;; Make isearch reveal context
5420 (if (or (featurep 'xemacs)
5421 (not (boundp 'outline-isearch-open-invisible-function)))
5422 ;; Emacs 21 and XEmacs make use of the hook
5423 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5424 ;; Emacs 22 deals with this through a special variable
5425 (org-set-local 'outline-isearch-open-invisible-function
5426 (lambda (&rest ignore) (org-show-context 'isearch)))
5427 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5429 ;; Setup the pcomplete hooks
5430 (set (make-local-variable 'pcomplete-command-completion-function)
5431 'org-pcomplete-initial)
5432 (set (make-local-variable 'pcomplete-command-name-function)
5433 'org-command-at-point)
5434 (set (make-local-variable 'pcomplete-default-completion-function)
5435 'ignore)
5436 (set (make-local-variable 'pcomplete-parse-arguments-function)
5437 'org-parse-arguments)
5438 (set (make-local-variable 'pcomplete-termination-string) "")
5439 (when (>= emacs-major-version 23)
5440 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5442 ;; If empty file that did not turn on org-mode automatically, make it to.
5443 (if (and org-insert-mode-line-in-empty-file
5444 (org-called-interactively-p 'any)
5445 (= (point-min) (point-max)))
5446 (insert "# -*- mode: org -*-\n\n"))
5447 (unless org-inhibit-startup
5448 (org-unmodified
5449 (and org-startup-with-beamer-mode (org-beamer-mode))
5450 (when org-startup-align-all-tables
5451 (org-table-map-tables 'org-table-align 'quietly))
5452 (when org-startup-with-inline-images
5453 (org-display-inline-images))
5454 (when org-startup-with-latex-preview
5455 (org-preview-latex-fragment))
5456 (unless org-inhibit-startup-visibility-stuff
5457 (org-set-startup-visibility))))
5458 ;; Try to set org-hide correctly
5459 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5461 ;; Update `customize-package-emacs-version-alist'
5462 (add-to-list 'customize-package-emacs-version-alist
5463 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5464 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5465 ("8.0" . "24.4")))
5467 (defvar org-mode-transpose-word-syntax-table
5468 (let ((st (make-syntax-table)))
5469 (mapc (lambda(c) (modify-syntax-entry
5470 (string-to-char (car c)) "w p" st))
5471 org-emphasis-alist)
5472 st))
5474 (when (fboundp 'abbrev-table-put)
5475 (abbrev-table-put org-mode-abbrev-table
5476 :parents (list text-mode-abbrev-table)))
5478 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5480 (defsubst org-fix-ellipsis-at-bol ()
5481 (save-excursion (goto-char (window-start)) (recenter 0)))
5483 (defun org-find-invisible-foreground ()
5484 (let ((candidates (remove
5485 "unspecified-bg"
5486 (nconc
5487 (list (face-background 'default)
5488 (face-background 'org-default))
5489 (mapcar
5490 (lambda (alist)
5491 (when (boundp alist)
5492 (cdr (assoc 'background-color (symbol-value alist)))))
5493 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5494 (list (face-foreground 'org-hide))))))
5495 (car (remove nil candidates))))
5497 (defun org-current-time (&optional rounding-minutes past)
5498 "Current time, possibly rounded to ROUNDING-MINUTES.
5499 When ROUNDING-MINUTES is not an integer, fall back on the car of
5500 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5501 the rounding returns a past time."
5502 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5503 (car org-time-stamp-rounding-minutes)))
5504 (time (decode-time)) res)
5505 (if (< r 1)
5506 (current-time)
5507 (setq res
5508 (apply 'encode-time
5509 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5510 (nthcdr 2 time))))
5511 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5512 (seconds-to-time (- (org-float-time res) (* r 60)))
5513 res))))
5515 (defun org-today ()
5516 "Return today date, considering `org-extend-today-until'."
5517 (time-to-days
5518 (time-subtract (current-time)
5519 (list 0 (* 3600 org-extend-today-until) 0))))
5521 ;;;; Font-Lock stuff, including the activators
5523 (defvar org-mouse-map (make-sparse-keymap))
5524 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5525 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5526 (when org-mouse-1-follows-link
5527 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5528 (when org-tab-follows-link
5529 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5530 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5532 (require 'font-lock)
5534 (defconst org-non-link-chars "]\t\n\r<>")
5535 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5536 "shell" "elisp" "doi" "message"))
5537 (defvar org-link-types-re nil
5538 "Matches a link that has a url-like prefix like \"http:\"")
5539 (defvar org-link-re-with-space nil
5540 "Matches a link with spaces, optional angular brackets around it.")
5541 (defvar org-link-re-with-space2 nil
5542 "Matches a link with spaces, optional angular brackets around it.")
5543 (defvar org-link-re-with-space3 nil
5544 "Matches a link with spaces, only for internal part in bracket links.")
5545 (defvar org-angle-link-re nil
5546 "Matches link with angular brackets, spaces are allowed.")
5547 (defvar org-plain-link-re nil
5548 "Matches plain link, without spaces.")
5549 (defvar org-bracket-link-regexp nil
5550 "Matches a link in double brackets.")
5551 (defvar org-bracket-link-analytic-regexp nil
5552 "Regular expression used to analyze links.
5553 Here is what the match groups contain after a match:
5554 1: http:
5555 2: http
5556 3: path
5557 4: [desc]
5558 5: desc")
5559 (defvar org-bracket-link-analytic-regexp++ nil
5560 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5561 (defvar org-any-link-re nil
5562 "Regular expression matching any link.")
5564 (defconst org-match-sexp-depth 3
5565 "Number of stacked braces for sub/superscript matching.")
5567 (defun org-create-multibrace-regexp (left right n)
5568 "Create a regular expression which will match a balanced sexp.
5569 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5570 as single character strings.
5571 The regexp returned will match the entire expression including the
5572 delimiters. It will also define a single group which contains the
5573 match except for the outermost delimiters. The maximum depth of
5574 stacked delimiters is N. Escaping delimiters is not possible."
5575 (let* ((nothing (concat "[^" left right "]*?"))
5576 (or "\\|")
5577 (re nothing)
5578 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5579 (while (> n 1)
5580 (setq n (1- n)
5581 re (concat re or next)
5582 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5583 (concat left "\\(" re "\\)" right)))
5585 (defvar org-match-substring-regexp
5586 (concat
5587 "\\(\\S-\\)\\([_^]\\)\\("
5588 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5589 "\\|"
5590 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5591 "\\|"
5592 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5593 "The regular expression matching a sub- or superscript.")
5595 (defvar org-match-substring-with-braces-regexp
5596 (concat
5597 "\\(\\S-\\)\\([_^]\\)\\("
5598 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5599 "\\)")
5600 "The regular expression matching a sub- or superscript, forcing braces.")
5602 (defun org-make-link-regexps ()
5603 "Update the link regular expressions.
5604 This should be called after the variable `org-link-types' has changed."
5605 (setq org-link-types-re
5606 (concat
5607 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5608 org-link-re-with-space
5609 (concat
5610 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5611 "\\([^" org-non-link-chars " ]"
5612 "[^" org-non-link-chars "]*"
5613 "[^" org-non-link-chars " ]\\)>?")
5614 org-link-re-with-space2
5615 (concat
5616 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5617 "\\([^" org-non-link-chars " ]"
5618 "[^\t\n\r]*"
5619 "[^" org-non-link-chars " ]\\)>?")
5620 org-link-re-with-space3
5621 (concat
5622 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5623 "\\([^" org-non-link-chars " ]"
5624 "[^\t\n\r]*\\)")
5625 org-angle-link-re
5626 (concat
5627 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5628 "\\([^" org-non-link-chars " ]"
5629 "[^" org-non-link-chars "]*"
5630 "\\)>")
5631 org-plain-link-re
5632 (concat
5633 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5634 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5635 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5636 org-bracket-link-regexp
5637 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5638 org-bracket-link-analytic-regexp
5639 (concat
5640 "\\[\\["
5641 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5642 "\\([^]]+\\)"
5643 "\\]"
5644 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5645 "\\]")
5646 org-bracket-link-analytic-regexp++
5647 (concat
5648 "\\[\\["
5649 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5650 "\\([^]]+\\)"
5651 "\\]"
5652 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5653 "\\]")
5654 org-any-link-re
5655 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5656 org-angle-link-re "\\)\\|\\("
5657 org-plain-link-re "\\)")))
5659 (org-make-link-regexps)
5661 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5662 "Regular expression for fast time stamp matching.")
5663 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5664 "Regular expression for fast time stamp matching.")
5665 (defconst org-ts-regexp0
5666 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5667 "Regular expression matching time strings for analysis.
5668 This one does not require the space after the date, so it can be used
5669 on a string that terminates immediately after the date.")
5670 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5671 "Regular expression matching time strings for analysis.")
5672 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5673 "Regular expression matching time stamps, with groups.")
5674 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5675 "Regular expression matching time stamps (also [..]), with groups.")
5676 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5677 "Regular expression matching a time stamp range.")
5678 (defconst org-tr-regexp-both
5679 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5680 "Regular expression matching a time stamp range.")
5681 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5682 org-ts-regexp "\\)?")
5683 "Regular expression matching a time stamp or time stamp range.")
5684 (defconst org-tsr-regexp-both
5685 (concat org-ts-regexp-both "\\(--?-?"
5686 org-ts-regexp-both "\\)?")
5687 "Regular expression matching a time stamp or time stamp range.
5688 The time stamps may be either active or inactive.")
5690 (defvar org-emph-face nil)
5692 (defun org-do-emphasis-faces (limit)
5693 "Run through the buffer and add overlays to emphasized strings."
5694 (let (rtn a)
5695 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5696 (if (not (= (char-after (match-beginning 3))
5697 (char-after (match-beginning 4))))
5698 (progn
5699 (setq rtn t)
5700 (setq a (assoc (match-string 3) org-emphasis-alist))
5701 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5702 'face
5703 (nth 1 a))
5704 (and (nth 4 a)
5705 (org-remove-flyspell-overlays-in
5706 (match-beginning 0) (match-end 0)))
5707 (add-text-properties (match-beginning 2) (match-end 2)
5708 '(font-lock-multiline t org-emphasis t))
5709 (when org-hide-emphasis-markers
5710 (add-text-properties (match-end 4) (match-beginning 5)
5711 '(invisible org-link))
5712 (add-text-properties (match-beginning 3) (match-end 3)
5713 '(invisible org-link)))))
5714 (backward-char 1))
5715 rtn))
5717 (defun org-emphasize (&optional char)
5718 "Insert or change an emphasis, i.e. a font like bold or italic.
5719 If there is an active region, change that region to a new emphasis.
5720 If there is no region, just insert the marker characters and position
5721 the cursor between them.
5722 CHAR should be the marker character. If it is a space, it means to
5723 remove the emphasis of the selected region.
5724 If CHAR is not given (for example in an interactive call) it will be
5725 prompted for."
5726 (interactive)
5727 (let ((erc org-emphasis-regexp-components)
5728 (prompt "")
5729 (string "") beg end move c s)
5730 (if (org-region-active-p)
5731 (setq beg (region-beginning) end (region-end)
5732 string (buffer-substring beg end))
5733 (setq move t))
5735 (unless char
5736 (message "Emphasis marker or tag: [%s]"
5737 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5738 (setq char (read-char-exclusive)))
5739 (if (equal char ?\ )
5740 (setq s "" move nil)
5741 (unless (assoc (char-to-string char) org-emphasis-alist)
5742 (user-error "No such emphasis marker: \"%c\"" char))
5743 (setq s (char-to-string char)))
5744 (while (and (> (length string) 1)
5745 (equal (substring string 0 1) (substring string -1))
5746 (assoc (substring string 0 1) org-emphasis-alist))
5747 (setq string (substring string 1 -1)))
5748 (setq string (concat s string s))
5749 (if beg (delete-region beg end))
5750 (unless (or (bolp)
5751 (string-match (concat "[" (nth 0 erc) "\n]")
5752 (char-to-string (char-before (point)))))
5753 (insert " "))
5754 (unless (or (eobp)
5755 (string-match (concat "[" (nth 1 erc) "\n]")
5756 (char-to-string (char-after (point)))))
5757 (insert " ") (backward-char 1))
5758 (insert string)
5759 (and move (backward-char 1))))
5761 (defconst org-nonsticky-props
5762 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5764 (defsubst org-rear-nonsticky-at (pos)
5765 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5767 (defun org-activate-plain-links (limit)
5768 "Run through the buffer and add overlays to links."
5769 (let (f hl)
5770 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5771 (not (org-in-src-block-p)))
5772 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5773 (setq f (get-text-property (match-beginning 0) 'face))
5774 (setq hl (org-match-string-no-properties 0))
5775 (if (or (eq f 'org-tag)
5776 (and (listp f) (memq 'org-tag f)))
5778 (add-text-properties (match-beginning 0) (match-end 0)
5779 (list 'mouse-face 'highlight
5780 'face 'org-link
5781 'htmlize-link `(:uri ,hl)
5782 'keymap org-mouse-map))
5783 (org-rear-nonsticky-at (match-end 0)))
5784 t)))
5786 (defun org-activate-code (limit)
5787 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5788 (progn
5789 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5790 (remove-text-properties (match-beginning 0) (match-end 0)
5791 '(display t invisible t intangible t))
5792 t)))
5794 (defcustom org-src-fontify-natively nil
5795 "When non-nil, fontify code in code blocks."
5796 :type 'boolean
5797 :version "24.1"
5798 :group 'org-appearance
5799 :group 'org-babel)
5801 (defcustom org-allow-promoting-top-level-subtree nil
5802 "When non-nil, allow promoting a top level subtree.
5803 The leading star of the top level headline will be replaced
5804 by a #."
5805 :type 'boolean
5806 :version "24.1"
5807 :group 'org-appearance)
5809 (defun org-fontify-meta-lines-and-blocks (limit)
5810 (condition-case nil
5811 (org-fontify-meta-lines-and-blocks-1 limit)
5812 (error (message "org-mode fontification error"))))
5814 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5815 "Fontify #+ lines and blocks."
5816 (let ((case-fold-search t))
5817 (if (re-search-forward
5818 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5819 limit t)
5820 (let ((beg (match-beginning 0))
5821 (block-start (match-end 0))
5822 (block-end nil)
5823 (lang (match-string 7))
5824 (beg1 (line-beginning-position 2))
5825 (dc1 (downcase (match-string 2)))
5826 (dc3 (downcase (match-string 3)))
5827 end end1 quoting block-type ovl)
5828 (cond
5829 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5830 ;; a single line of backend-specific content
5831 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5832 (remove-text-properties (match-beginning 0) (match-end 0)
5833 '(display t invisible t intangible t))
5834 (add-text-properties (match-beginning 1) (match-end 3)
5835 '(font-lock-fontified t face org-meta-line))
5836 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5837 '(font-lock-fontified t face org-block))
5838 ; for backend-specific code
5840 ((and (match-end 4) (equal dc3 "+begin"))
5841 ;; Truly a block
5842 (setq block-type (downcase (match-string 5))
5843 quoting (member block-type org-protecting-blocks))
5844 (when (re-search-forward
5845 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5846 nil t) ;; on purpose, we look further than LIMIT
5847 (setq end (min (point-max) (match-end 0))
5848 end1 (min (point-max) (1- (match-beginning 0))))
5849 (setq block-end (match-beginning 0))
5850 (when quoting
5851 (remove-text-properties beg end
5852 '(display t invisible t intangible t)))
5853 (add-text-properties
5854 beg end
5855 '(font-lock-fontified t font-lock-multiline t))
5856 (add-text-properties beg beg1 '(face org-meta-line))
5857 (add-text-properties end1 (min (point-max) (1+ end))
5858 '(face org-meta-line)) ; for end_src
5859 (cond
5860 ((and lang (not (string= lang "")) org-src-fontify-natively)
5861 (org-src-font-lock-fontify-block lang block-start block-end)
5862 ;; remove old background overlays
5863 (mapc (lambda (ov)
5864 (if (eq (overlay-get ov 'face) 'org-block-background)
5865 (delete-overlay ov)))
5866 (overlays-at (/ (+ beg1 block-end) 2)))
5867 ;; add a background overlay
5868 (setq ovl (make-overlay beg1 block-end))
5869 (overlay-put ovl 'face 'org-block-background)
5870 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5871 (quoting
5872 (add-text-properties beg1 (min (point-max) (1+ end1))
5873 '(face org-block))) ; end of source block
5874 ((not org-fontify-quote-and-verse-blocks))
5875 ((string= block-type "quote")
5876 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5877 ((string= block-type "verse")
5878 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5879 (add-text-properties beg beg1 '(face org-block-begin-line))
5880 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5881 '(face org-block-end-line))
5883 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5884 (add-text-properties
5885 beg (match-end 3)
5886 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5887 '(font-lock-fontified t invisible t)
5888 '(font-lock-fontified t face org-document-info-keyword)))
5889 (add-text-properties
5890 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5891 (if (string-equal dc1 "+title:")
5892 '(font-lock-fontified t face org-document-title)
5893 '(font-lock-fontified t face org-document-info))))
5894 ((or (equal dc1 "+results")
5895 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5896 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5897 "+call:" "+header:" "+headers:" "+name:"))
5898 (and (match-end 4) (equal dc3 "+attr")))
5899 (add-text-properties
5900 beg (match-end 0)
5901 '(font-lock-fontified t face org-meta-line))
5903 ((member dc3 '(" " ""))
5904 (add-text-properties
5905 beg (match-end 0)
5906 '(font-lock-fontified t face font-lock-comment-face)))
5907 ((not (member (char-after beg) '(?\ ?\t)))
5908 ;; just any other in-buffer setting, but not indented
5909 (add-text-properties
5910 beg (match-end 0)
5911 '(font-lock-fontified t face org-meta-line))
5913 (t nil))))))
5915 (defun org-activate-angle-links (limit)
5916 "Run through the buffer and add overlays to links."
5917 (if (and (re-search-forward org-angle-link-re limit t)
5918 (not (org-in-src-block-p)))
5919 (progn
5920 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5921 (add-text-properties (match-beginning 0) (match-end 0)
5922 (list 'mouse-face 'highlight
5923 'keymap org-mouse-map))
5924 (org-rear-nonsticky-at (match-end 0))
5925 t)))
5927 (defun org-activate-footnote-links (limit)
5928 "Run through the buffer and add overlays to footnotes."
5929 (let ((fn (org-footnote-next-reference-or-definition limit)))
5930 (when fn
5931 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5932 (org-remove-flyspell-overlays-in beg end)
5933 (add-text-properties beg end
5934 (list 'mouse-face 'highlight
5935 'keymap org-mouse-map
5936 'help-echo
5937 (if (= (point-at-bol) beg)
5938 "Footnote definition"
5939 "Footnote reference")
5940 'font-lock-fontified t
5941 'font-lock-multiline t
5942 'face 'org-footnote))))))
5944 (defun org-activate-bracket-links (limit)
5945 "Run through the buffer and add overlays to bracketed links."
5946 (if (and (re-search-forward org-bracket-link-regexp limit t)
5947 (not (org-in-src-block-p)))
5948 (let* ((hl (org-match-string-no-properties 1))
5949 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5950 (ip (org-maybe-intangible
5951 (list 'invisible 'org-link
5952 'keymap org-mouse-map 'mouse-face 'highlight
5953 'font-lock-multiline t 'help-echo help
5954 'htmlize-link `(:uri ,hl))))
5955 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5956 'font-lock-multiline t 'help-echo help
5957 'htmlize-link `(:uri ,hl))))
5958 ;; We need to remove the invisible property here. Table narrowing
5959 ;; may have made some of this invisible.
5960 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5961 (remove-text-properties (match-beginning 0) (match-end 0)
5962 '(invisible nil))
5963 (if (match-end 3)
5964 (progn
5965 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5966 (org-rear-nonsticky-at (match-beginning 3))
5967 (add-text-properties (match-beginning 3) (match-end 3) vp)
5968 (org-rear-nonsticky-at (match-end 3))
5969 (add-text-properties (match-end 3) (match-end 0) ip)
5970 (org-rear-nonsticky-at (match-end 0)))
5971 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5972 (org-rear-nonsticky-at (match-beginning 1))
5973 (add-text-properties (match-beginning 1) (match-end 1) vp)
5974 (org-rear-nonsticky-at (match-end 1))
5975 (add-text-properties (match-end 1) (match-end 0) ip)
5976 (org-rear-nonsticky-at (match-end 0)))
5977 t)))
5979 (defun org-activate-dates (limit)
5980 "Run through the buffer and add overlays to dates."
5981 (if (and (re-search-forward org-tsr-regexp-both limit t)
5982 (not (equal (char-before (match-beginning 0)) 91)))
5983 (progn
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (add-text-properties (match-beginning 0) (match-end 0)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map))
5988 (org-rear-nonsticky-at (match-end 0))
5989 (when org-display-custom-times
5990 (if (match-end 3)
5991 (org-display-custom-time (match-beginning 3) (match-end 3)))
5992 (org-display-custom-time (match-beginning 1) (match-end 1)))
5993 t)))
5995 (defvar org-target-link-regexp nil
5996 "Regular expression matching radio targets in plain text.")
5997 (make-variable-buffer-local 'org-target-link-regexp)
5998 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5999 "Regular expression matching a link target.")
6000 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
6001 "Regular expression matching a radio target.")
6002 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
6003 "Regular expression matching any target.")
6005 (defun org-activate-target-links (limit)
6006 "Run through the buffer and add overlays to target matches."
6007 (when org-target-link-regexp
6008 (let ((case-fold-search t))
6009 (if (re-search-forward org-target-link-regexp limit t)
6010 (progn
6011 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6012 (add-text-properties (match-beginning 0) (match-end 0)
6013 (list 'mouse-face 'highlight
6014 'keymap org-mouse-map
6015 'help-echo "Radio target link"
6016 'org-linked-text t))
6017 (org-rear-nonsticky-at (match-end 0))
6018 t)))))
6020 (defun org-update-radio-target-regexp ()
6021 "Find all radio targets in this file and update the regular expression."
6022 (interactive)
6023 (when (memq 'radio org-activate-links)
6024 (setq org-target-link-regexp
6025 (org-make-target-link-regexp (org-all-targets 'radio)))
6026 (org-restart-font-lock)))
6028 (defun org-hide-wide-columns (limit)
6029 (let (s e)
6030 (setq s (text-property-any (point) (or limit (point-max))
6031 'org-cwidth t))
6032 (when s
6033 (setq e (next-single-property-change s 'org-cwidth))
6034 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6035 (goto-char e)
6036 t)))
6038 (defvar org-latex-and-related-regexp nil
6039 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6040 (defvar org-match-substring-regexp)
6041 (defvar org-match-substring-with-braces-regexp)
6043 (defun org-compute-latex-and-related-regexp ()
6044 "Compute regular expression for LaTeX, entities and sub/superscript.
6045 Result depends on variable `org-highlight-latex-and-related'."
6046 (org-set-local
6047 'org-latex-and-related-regexp
6048 (let* ((re-sub
6049 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6050 ((eq org-use-sub-superscripts '{})
6051 (list org-match-substring-with-braces-regexp))
6052 (org-use-sub-superscripts (list org-match-substring-regexp))))
6053 (re-latex
6054 (when (memq 'latex org-highlight-latex-and-related)
6055 (let ((matchers (plist-get org-format-latex-options :matchers)))
6056 (delq nil
6057 (mapcar (lambda (x)
6058 (and (member (car x) matchers) (nth 1 x)))
6059 org-latex-regexps)))))
6060 (re-entities
6061 (when (memq 'entities org-highlight-latex-and-related)
6062 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6063 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6065 (defun org-do-latex-and-related (limit)
6066 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6067 LIMIT bounds the search for syntax to highlight. Stop at first
6068 highlighted object, if any. Return t if some highlighting was
6069 done, nil otherwise."
6070 (when (org-string-nw-p org-latex-and-related-regexp)
6071 (catch 'found
6072 (while (re-search-forward org-latex-and-related-regexp limit t)
6073 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6074 'face))
6075 '(org-code org-verbatim underline))
6076 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6077 '(?_ ?^))
6079 0)))
6080 (font-lock-prepend-text-property
6081 (+ offset (match-beginning 0)) (match-end 0)
6082 'face 'org-latex-and-related)
6083 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6084 '(font-lock-multiline t)))
6085 (throw 'found t)))
6086 nil)))
6088 (defun org-restart-font-lock ()
6089 "Restart `font-lock-mode', to force refontification."
6090 (when (and (boundp 'font-lock-mode) font-lock-mode)
6091 (font-lock-mode -1)
6092 (font-lock-mode 1)))
6094 (defun org-all-targets (&optional radio)
6095 "Return a list of all targets in this file.
6096 When optional argument RADIO is non-nil, only find radio
6097 targets."
6098 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6099 (save-excursion
6100 (goto-char (point-min))
6101 (while (re-search-forward re nil t)
6102 ;; Make sure point is really within the object.
6103 (backward-char)
6104 (let ((obj (org-element-context)))
6105 (when (memq (org-element-type obj) '(radio-target target))
6106 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6107 rtn)))
6109 (defun org-make-target-link-regexp (targets)
6110 "Make regular expression matching all strings in TARGETS.
6111 The regular expression finds the targets also if there is a line break
6112 between words."
6113 (and targets
6114 (concat
6115 "\\<\\("
6116 (mapconcat
6117 (lambda (x)
6118 (setq x (regexp-quote x))
6119 (while (string-match " +" x)
6120 (setq x (replace-match "\\s-+" t t x)))
6122 targets
6123 "\\|")
6124 "\\)\\>")))
6126 (defun org-activate-tags (limit)
6127 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6128 (progn
6129 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6130 (add-text-properties (match-beginning 1) (match-end 1)
6131 (list 'mouse-face 'highlight
6132 'keymap org-mouse-map))
6133 (org-rear-nonsticky-at (match-end 1))
6134 t)))
6136 (defun org-outline-level ()
6137 "Compute the outline level of the heading at point.
6138 If this is called at a normal headline, the level is the number of stars.
6139 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6140 (save-excursion
6141 (if (not (condition-case nil
6142 (org-back-to-heading t)
6143 (error nil)))
6145 (looking-at org-outline-regexp)
6146 (1- (- (match-end 0) (match-beginning 0))))))
6148 (defvar org-font-lock-keywords nil)
6150 (defsubst org-re-property (property &optional literal)
6151 "Return a regexp matching a PROPERTY line.
6152 Match group 3 will be set to the value if it exists."
6153 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6154 (if literal property (regexp-quote property))
6155 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6157 (defconst org-property-re
6158 (org-re-property ".*?" 'literal)
6159 "Regular expression matching a property line.
6160 There are four matching groups:
6161 1: :PROPKEY: including the leading and trailing colon,
6162 2: PROPKEY without the leading and trailing colon,
6163 3: PROPVAL without leading or trailing spaces,
6164 4: the indentation of the current line,
6165 5: trailing whitespace.")
6167 (defvar org-font-lock-hook nil
6168 "Functions to be called for special font lock stuff.")
6170 (defvar org-font-lock-set-keywords-hook nil
6171 "Functions that can manipulate `org-font-lock-extra-keywords'.
6172 This is called after `org-font-lock-extra-keywords' is defined, but before
6173 it is installed to be used by font lock. This can be useful if something
6174 needs to be inserted at a specific position in the font-lock sequence.")
6176 (defun org-font-lock-hook (limit)
6177 "Run `org-font-lock-hook' within LIMIT."
6178 (run-hook-with-args 'org-font-lock-hook limit))
6180 (defun org-set-font-lock-defaults ()
6181 "Set font lock defaults for the current buffer."
6182 (let* ((em org-fontify-emphasized-text)
6183 (lk org-activate-links)
6184 (org-font-lock-extra-keywords
6185 (list
6186 ;; Call the hook
6187 '(org-font-lock-hook)
6188 ;; Headlines
6189 `(,(if org-fontify-whole-heading-line
6190 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6191 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6192 (1 (org-get-level-face 1))
6193 (2 (org-get-level-face 2))
6194 (3 (org-get-level-face 3)))
6195 ;; Table lines
6196 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6197 (1 'org-table t))
6198 ;; Table internals
6199 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6200 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6201 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6202 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6203 ;; Drawers
6204 (list org-drawer-regexp '(0 'org-special-keyword t))
6205 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6206 ;; Properties
6207 (list org-property-re
6208 '(1 'org-special-keyword t)
6209 '(3 'org-property-value t))
6210 ;; Links
6211 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6212 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6213 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6214 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6215 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6216 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6217 (if (memq 'footnote lk) '(org-activate-footnote-links))
6218 ;; Targets.
6219 (list org-any-target-regexp '(0 'org-target t))
6220 ;; Diary sexps.
6221 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6222 ;; Macro
6223 '("{{{.+}}}" (0 'org-macro t))
6224 '(org-hide-wide-columns (0 nil append))
6225 ;; TODO keyword
6226 (list (format org-heading-keyword-regexp-format
6227 org-todo-regexp)
6228 '(2 (org-get-todo-face 2) t))
6229 ;; DONE
6230 (if org-fontify-done-headline
6231 (list (format org-heading-keyword-regexp-format
6232 (concat
6233 "\\(?:"
6234 (mapconcat 'regexp-quote org-done-keywords "\\|")
6235 "\\)"))
6236 '(2 'org-headline-done t))
6237 nil)
6238 ;; Priorities
6239 '(org-font-lock-add-priority-faces)
6240 ;; Tags
6241 '(org-font-lock-add-tag-faces)
6242 ;; Tags groups
6243 (if (and org-group-tags org-tag-groups-alist)
6244 (list (concat org-outline-regexp-bol ".+\\(:"
6245 (regexp-opt (mapcar 'car org-tag-groups-alist))
6246 ":\\).*$")
6247 '(1 'org-tag-group prepend)))
6248 ;; Special keywords
6249 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6250 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6251 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6252 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6253 ;; Emphasis
6254 (if em
6255 (if (featurep 'xemacs)
6256 '(org-do-emphasis-faces (0 nil append))
6257 '(org-do-emphasis-faces)))
6258 ;; Checkboxes
6259 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6260 1 'org-checkbox prepend)
6261 (if (cdr (assq 'checkbox org-list-automatic-rules))
6262 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6263 (0 (org-get-checkbox-statistics-face) t)))
6264 ;; Description list items
6265 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6266 1 'org-list-dt prepend)
6267 ;; ARCHIVEd headings
6268 (list (concat
6269 org-outline-regexp-bol
6270 "\\(.*:" org-archive-tag ":.*\\)")
6271 '(1 'org-archived prepend))
6272 ;; Specials
6273 '(org-do-latex-and-related)
6274 '(org-fontify-entities)
6275 '(org-raise-scripts)
6276 ;; Code
6277 '(org-activate-code (1 'org-code t))
6278 ;; COMMENT
6279 (list (format org-heading-keyword-regexp-format
6280 (concat "\\("
6281 org-comment-string "\\|" org-quote-string
6282 "\\)"))
6283 '(2 'org-special-keyword t))
6284 ;; Blocks and meta lines
6285 '(org-fontify-meta-lines-and-blocks))))
6286 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6287 (run-hooks 'org-font-lock-set-keywords-hook)
6288 ;; Now set the full font-lock-keywords
6289 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6290 (org-set-local 'font-lock-defaults
6291 '(org-font-lock-keywords t nil nil backward-paragraph))
6292 (kill-local-variable 'font-lock-keywords) nil))
6294 (defun org-toggle-pretty-entities ()
6295 "Toggle the composition display of entities as UTF8 characters."
6296 (interactive)
6297 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6298 (org-restart-font-lock)
6299 (if org-pretty-entities
6300 (message "Entities are now displayed as UTF8 characters")
6301 (save-restriction
6302 (widen)
6303 (org-decompose-region (point-min) (point-max))
6304 (message "Entities are now displayed as plain text"))))
6306 (defvar org-custom-properties-overlays nil
6307 "List of overlays used for custom properties.")
6308 (make-variable-buffer-local 'org-custom-properties-overlays)
6310 (defun org-toggle-custom-properties-visibility ()
6311 "Display or hide properties in `org-custom-properties'."
6312 (interactive)
6313 (if org-custom-properties-overlays
6314 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6315 (setq org-custom-properties-overlays nil))
6316 (unless (not org-custom-properties)
6317 (save-excursion
6318 (save-restriction
6319 (widen)
6320 (goto-char (point-min))
6321 (while (re-search-forward org-property-re nil t)
6322 (mapc (lambda(p)
6323 (when (equal p (substring (match-string 1) 1 -1))
6324 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6325 (overlay-put o 'invisible t)
6326 (overlay-put o 'org-custom-property t)
6327 (push o org-custom-properties-overlays))))
6328 org-custom-properties)))))))
6330 (defun org-fontify-entities (limit)
6331 "Find an entity to fontify."
6332 (let (ee)
6333 (when org-pretty-entities
6334 (catch 'match
6335 (while (re-search-forward
6336 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6337 limit t)
6338 (if (and (not (org-in-indented-comment-line))
6339 (setq ee (org-entity-get (match-string 1)))
6340 (= (length (nth 6 ee)) 1))
6341 (let*
6342 ((end (if (equal (match-string 2) "{}")
6343 (match-end 2)
6344 (match-end 1))))
6345 (add-text-properties
6346 (match-beginning 0) end
6347 (list 'font-lock-fontified t))
6348 (compose-region (match-beginning 0) end
6349 (nth 6 ee) nil)
6350 (backward-char 1)
6351 (throw 'match t))))
6352 nil))))
6354 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6355 "Fontify string S like in Org-mode."
6356 (with-temp-buffer
6357 (insert s)
6358 (let ((org-odd-levels-only odd-levels))
6359 (org-mode)
6360 (font-lock-fontify-buffer)
6361 (buffer-string))))
6363 (defvar org-m nil)
6364 (defvar org-l nil)
6365 (defvar org-f nil)
6366 (defun org-get-level-face (n)
6367 "Get the right face for match N in font-lock matching of headlines."
6368 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6369 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6370 (if org-cycle-level-faces
6371 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6372 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6373 (cond
6374 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6375 ((eq n 2) org-f)
6376 (t (if org-level-color-stars-only nil org-f))))
6379 (defun org-get-todo-face (kwd)
6380 "Get the right face for a TODO keyword KWD.
6381 If KWD is a number, get the corresponding match group."
6382 (if (numberp kwd) (setq kwd (match-string kwd)))
6383 (or (org-face-from-face-or-color
6384 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6385 (and (member kwd org-done-keywords) 'org-done)
6386 'org-todo))
6388 (defun org-face-from-face-or-color (context inherit face-or-color)
6389 "Create a face list that inherits INHERIT, but sets the foreground color.
6390 When FACE-OR-COLOR is not a string, just return it."
6391 (if (stringp face-or-color)
6392 (list :inherit inherit
6393 (cdr (assoc context org-faces-easy-properties))
6394 face-or-color)
6395 face-or-color))
6397 (defun org-font-lock-add-tag-faces (limit)
6398 "Add the special tag faces."
6399 (when (and org-tag-faces org-tags-special-faces-re)
6400 (while (re-search-forward org-tags-special-faces-re limit t)
6401 (add-text-properties (match-beginning 1) (match-end 1)
6402 (list 'face (org-get-tag-face 1)
6403 'font-lock-fontified t))
6404 (backward-char 1))))
6406 (defun org-font-lock-add-priority-faces (limit)
6407 "Add the special priority faces."
6408 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6409 (when (save-match-data (org-at-heading-p))
6410 (add-text-properties
6411 (match-beginning 0) (match-end 0)
6412 (list 'face (or (org-face-from-face-or-color
6413 'priority 'org-priority
6414 (cdr (assoc (char-after (match-beginning 1))
6415 org-priority-faces)))
6416 'org-priority)
6417 'font-lock-fontified t)))))
6419 (defun org-get-tag-face (kwd)
6420 "Get the right face for a TODO keyword KWD.
6421 If KWD is a number, get the corresponding match group."
6422 (if (numberp kwd) (setq kwd (match-string kwd)))
6423 (or (org-face-from-face-or-color
6424 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6425 'org-tag))
6427 (defun org-unfontify-region (beg end &optional maybe_loudly)
6428 "Remove fontification and activation overlays from links."
6429 (font-lock-default-unfontify-region beg end)
6430 (let* ((buffer-undo-list t)
6431 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6432 (inhibit-modification-hooks t)
6433 deactivate-mark buffer-file-name buffer-file-truename)
6434 (org-decompose-region beg end)
6435 (remove-text-properties beg end
6436 '(mouse-face t keymap t org-linked-text t
6437 invisible t intangible t
6438 org-no-flyspell t org-emphasis t))
6439 (org-remove-font-lock-display-properties beg end)))
6441 (defconst org-script-display '(((raise -0.3) (height 0.7))
6442 ((raise 0.3) (height 0.7))
6443 ((raise -0.5))
6444 ((raise 0.5)))
6445 "Display properties for showing superscripts and subscripts.")
6447 (defun org-remove-font-lock-display-properties (beg end)
6448 "Remove specific display properties that have been added by font lock.
6449 The will remove the raise properties that are used to show superscripts
6450 and subscripts."
6451 (let (next prop)
6452 (while (< beg end)
6453 (setq next (next-single-property-change beg 'display nil end)
6454 prop (get-text-property beg 'display))
6455 (if (member prop org-script-display)
6456 (put-text-property beg next 'display nil))
6457 (setq beg next))))
6459 (defun org-raise-scripts (limit)
6460 "Add raise properties to sub/superscripts."
6461 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6462 (if (re-search-forward
6463 (if (eq org-use-sub-superscripts t)
6464 org-match-substring-regexp
6465 org-match-substring-with-braces-regexp)
6466 limit t)
6467 (let* ((pos (point)) table-p comment-p
6468 (mpos (match-beginning 3))
6469 (emph-p (get-text-property mpos 'org-emphasis))
6470 (link-p (get-text-property mpos 'mouse-face))
6471 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6472 (goto-char (point-at-bol))
6473 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6474 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6475 (goto-char pos)
6476 ;; Handle a_b^c
6477 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6478 (if (or comment-p emph-p link-p keyw-p)
6480 (put-text-property (match-beginning 3) (match-end 0)
6481 'display
6482 (if (equal (char-after (match-beginning 2)) ?^)
6483 (nth (if table-p 3 1) org-script-display)
6484 (nth (if table-p 2 0) org-script-display)))
6485 (add-text-properties (match-beginning 2) (match-end 2)
6486 (list 'invisible t
6487 'org-dwidth t 'org-dwidth-n 1))
6488 (if (and (eq (char-after (match-beginning 3)) ?{)
6489 (eq (char-before (match-end 3)) ?}))
6490 (progn
6491 (add-text-properties
6492 (match-beginning 3) (1+ (match-beginning 3))
6493 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6494 (add-text-properties
6495 (1- (match-end 3)) (match-end 3)
6496 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6497 t)))))
6499 ;;;; Visibility cycling, including org-goto and indirect buffer
6501 ;;; Cycling
6503 (defvar org-cycle-global-status nil)
6504 (make-variable-buffer-local 'org-cycle-global-status)
6505 (put 'org-cycle-global-status 'org-state t)
6506 (defvar org-cycle-subtree-status nil)
6507 (make-variable-buffer-local 'org-cycle-subtree-status)
6508 (put 'org-cycle-subtree-status 'org-state t)
6510 (defvar org-inlinetask-min-level)
6512 ;;;###autoload
6513 (defun org-cycle (&optional arg)
6514 "TAB-action and visibility cycling for Org-mode.
6516 This is the command invoked in Org-mode by the TAB key. Its main purpose
6517 is outline visibility cycling, but it also invokes other actions
6518 in special contexts.
6520 - When this function is called with a prefix argument, rotate the entire
6521 buffer through 3 states (global cycling)
6522 1. OVERVIEW: Show only top-level headlines.
6523 2. CONTENTS: Show all headlines of all levels, but no body text.
6524 3. SHOW ALL: Show everything.
6525 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6526 determined by the variable `org-startup-folded', and by any VISIBILITY
6527 properties in the buffer.
6528 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6529 including any drawers.
6531 - When inside a table, re-align the table and move to the next field.
6533 - When point is at the beginning of a headline, rotate the subtree started
6534 by this line through 3 different states (local cycling)
6535 1. FOLDED: Only the main headline is shown.
6536 2. CHILDREN: The main headline and the direct children are shown.
6537 From this state, you can move to one of the children
6538 and zoom in further.
6539 3. SUBTREE: Show the entire subtree, including body text.
6540 If there is no subtree, switch directly from CHILDREN to FOLDED.
6542 - When point is at the beginning of an empty headline and the variable
6543 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6544 of the headline by demoting and promoting it to likely levels. This
6545 speeds up creation document structure by pressing TAB once or several
6546 times right after creating a new headline.
6548 - When there is a numeric prefix, go up to a heading with level ARG, do
6549 a `show-subtree' and return to the previous cursor position. If ARG
6550 is negative, go up that many levels.
6552 - When point is not at the beginning of a headline, execute the global
6553 binding for TAB, which is re-indenting the line. See the option
6554 `org-cycle-emulate-tab' for details.
6556 - Special case: if point is at the beginning of the buffer and there is
6557 no headline in line 1, this function will act as if called with prefix arg
6558 (C-u TAB, same as S-TAB) also when called without prefix arg.
6559 But only if also the variable `org-cycle-global-at-bob' is t."
6560 (interactive "P")
6561 (org-load-modules-maybe)
6562 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6563 (and org-cycle-level-after-item/entry-creation
6564 (or (org-cycle-level)
6565 (org-cycle-item-indentation))))
6566 (let* (message-log-max ; Don't populate the *Messages* buffer
6567 (limit-level
6568 (or org-cycle-max-level
6569 (and (boundp 'org-inlinetask-min-level)
6570 org-inlinetask-min-level
6571 (1- org-inlinetask-min-level))))
6572 (nstars (and limit-level
6573 (if org-odd-levels-only
6574 (and limit-level (1- (* limit-level 2)))
6575 limit-level)))
6576 (org-outline-regexp
6577 (if (not (derived-mode-p 'org-mode))
6578 outline-regexp
6579 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6580 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6581 (not (looking-at org-outline-regexp))))
6582 (org-cycle-hook
6583 (if bob-special
6584 (delq 'org-optimize-window-after-visibility-change
6585 (copy-sequence org-cycle-hook))
6586 org-cycle-hook))
6587 (pos (point)))
6589 (if (or bob-special (equal arg '(4)))
6590 ;; special case: use global cycling
6591 (setq arg t))
6593 (cond
6595 ((equal arg '(16))
6596 (setq last-command 'dummy)
6597 (org-set-startup-visibility)
6598 (message "Startup visibility, plus VISIBILITY properties"))
6600 ((equal arg '(64))
6601 (show-all)
6602 (message "Entire buffer visible, including drawers"))
6604 ;; Table: enter it or move to the next field.
6605 ((org-at-table-p 'any)
6606 (if (org-at-table.el-p)
6607 (message "Use C-c ' to edit table.el tables")
6608 (if arg (org-table-edit-field t)
6609 (org-table-justify-field-maybe)
6610 (call-interactively 'org-table-next-field))))
6612 ((run-hook-with-args-until-success
6613 'org-tab-after-check-for-table-hook))
6615 ;; Global cycling: delegate to `org-cycle-internal-global'.
6616 ((eq arg t) (org-cycle-internal-global))
6618 ;; Drawers: delegate to `org-flag-drawer'.
6619 ((and org-drawers org-drawer-regexp
6620 (save-excursion
6621 (beginning-of-line 1)
6622 (looking-at org-drawer-regexp)))
6623 (org-flag-drawer ; toggle block visibility
6624 (not (get-char-property (match-end 0) 'invisible))))
6626 ;; Show-subtree, ARG levels up from here.
6627 ((integerp arg)
6628 (save-excursion
6629 (org-back-to-heading)
6630 (outline-up-heading (if (< arg 0) (- arg)
6631 (- (funcall outline-level) arg)))
6632 (org-show-subtree)))
6634 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6635 ((and (featurep 'org-inlinetask)
6636 (org-inlinetask-at-task-p)
6637 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6638 (org-inlinetask-toggle-visibility))
6640 ((org-try-cdlatex-tab))
6642 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6643 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6644 (save-excursion (beginning-of-line 1)
6645 (looking-at org-outline-regexp)))
6646 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6647 (org-cycle-internal-local))
6649 ;; From there: TAB emulation and template completion.
6650 (buffer-read-only (org-back-to-heading))
6652 ((run-hook-with-args-until-success
6653 'org-tab-after-check-for-cycling-hook))
6655 ((org-try-structure-completion))
6657 ((run-hook-with-args-until-success
6658 'org-tab-before-tab-emulation-hook))
6660 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6661 (or (not (bolp))
6662 (not (looking-at org-outline-regexp))))
6663 (call-interactively (global-key-binding "\t")))
6665 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6666 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6667 (or (and (eq org-cycle-emulate-tab 'white)
6668 (= (match-end 0) (point-at-eol)))
6669 (and (eq org-cycle-emulate-tab 'whitestart)
6670 (>= (match-end 0) pos))))
6672 (eq org-cycle-emulate-tab t))
6673 (call-interactively (global-key-binding "\t")))
6675 (t (save-excursion
6676 (org-back-to-heading)
6677 (org-cycle)))))))
6679 (defun org-cycle-internal-global ()
6680 "Do the global cycling action."
6681 ;; Hack to avoid display of messages for .org attachments in Gnus
6682 (let (message-log-max ; Don't populate the *Messages* buffer
6683 (ga (string-match "\\*fontification" (buffer-name))))
6684 (cond
6685 ((and (eq last-command this-command)
6686 (eq org-cycle-global-status 'overview))
6687 ;; We just created the overview - now do table of contents
6688 ;; This can be slow in very large buffers, so indicate action
6689 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6690 (unless ga (message "CONTENTS..."))
6691 (org-content)
6692 (unless ga (message "CONTENTS...done"))
6693 (setq org-cycle-global-status 'contents)
6694 (run-hook-with-args 'org-cycle-hook 'contents))
6696 ((and (eq last-command this-command)
6697 (eq org-cycle-global-status 'contents))
6698 ;; We just showed the table of contents - now show everything
6699 (run-hook-with-args 'org-pre-cycle-hook 'all)
6700 (show-all)
6701 (unless ga (message "SHOW ALL"))
6702 (setq org-cycle-global-status 'all)
6703 (run-hook-with-args 'org-cycle-hook 'all))
6706 ;; Default action: go to overview
6707 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6708 (org-overview)
6709 (unless ga (message "OVERVIEW"))
6710 (setq org-cycle-global-status 'overview)
6711 (run-hook-with-args 'org-cycle-hook 'overview)))))
6713 (defun org-cycle-internal-local ()
6714 "Do the local cycling action."
6715 (let (message-log-max ; Don't populate the *Messages* buffer
6716 (goal-column 0) eoh eol eos has-children children-skipped struct)
6717 ;; First, determine end of headline (EOH), end of subtree or item
6718 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6719 (save-excursion
6720 (if (org-at-item-p)
6721 (progn
6722 (beginning-of-line)
6723 (setq struct (org-list-struct))
6724 (setq eoh (point-at-eol))
6725 (setq eos (org-list-get-item-end-before-blank (point) struct))
6726 (setq has-children (org-list-has-child-p (point) struct)))
6727 (org-back-to-heading)
6728 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6729 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6730 (setq has-children
6731 (or (save-excursion
6732 (let ((level (funcall outline-level)))
6733 (outline-next-heading)
6734 (and (org-at-heading-p t)
6735 (> (funcall outline-level) level))))
6736 (save-excursion
6737 (org-list-search-forward (org-item-beginning-re) eos t)))))
6738 ;; Determine end invisible part of buffer (EOL)
6739 (beginning-of-line 2)
6740 ;; XEmacs doesn't have `next-single-char-property-change'
6741 (if (featurep 'xemacs)
6742 (while (and (not (eobp)) ;; this is like `next-line'
6743 (get-char-property (1- (point)) 'invisible))
6744 (beginning-of-line 2))
6745 (while (and (not (eobp)) ;; this is like `next-line'
6746 (get-char-property (1- (point)) 'invisible))
6747 (goto-char (next-single-char-property-change (point) 'invisible))
6748 (and (eolp) (beginning-of-line 2))))
6749 (setq eol (point)))
6750 ;; Find out what to do next and set `this-command'
6751 (cond
6752 ((= eos eoh)
6753 ;; Nothing is hidden behind this heading
6754 (unless (org-before-first-heading-p)
6755 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6756 (message "EMPTY ENTRY")
6757 (setq org-cycle-subtree-status nil)
6758 (save-excursion
6759 (goto-char eos)
6760 (outline-next-heading)
6761 (if (outline-invisible-p) (org-flag-heading nil))))
6762 ((and (or (>= eol eos)
6763 (not (string-match "\\S-" (buffer-substring eol eos))))
6764 (or has-children
6765 (not (setq children-skipped
6766 org-cycle-skip-children-state-if-no-children))))
6767 ;; Entire subtree is hidden in one line: children view
6768 (unless (org-before-first-heading-p)
6769 (run-hook-with-args 'org-pre-cycle-hook 'children))
6770 (if (org-at-item-p)
6771 (org-list-set-item-visibility (point-at-bol) struct 'children)
6772 (org-show-entry)
6773 (org-with-limited-levels (show-children))
6774 ;; FIXME: This slows down the func way too much.
6775 ;; How keep drawers hidden in subtree anyway?
6776 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6777 ;; (org-cycle-hide-drawers 'subtree))
6779 ;; Fold every list in subtree to top-level items.
6780 (when (eq org-cycle-include-plain-lists 'integrate)
6781 (save-excursion
6782 (org-back-to-heading)
6783 (while (org-list-search-forward (org-item-beginning-re) eos t)
6784 (beginning-of-line 1)
6785 (let* ((struct (org-list-struct))
6786 (prevs (org-list-prevs-alist struct))
6787 (end (org-list-get-bottom-point struct)))
6788 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6789 (org-list-get-all-items (point) struct prevs))
6790 (goto-char (if (< end eos) end eos)))))))
6791 (message "CHILDREN")
6792 (save-excursion
6793 (goto-char eos)
6794 (outline-next-heading)
6795 (if (outline-invisible-p) (org-flag-heading nil)))
6796 (setq org-cycle-subtree-status 'children)
6797 (unless (org-before-first-heading-p)
6798 (run-hook-with-args 'org-cycle-hook 'children)))
6799 ((or children-skipped
6800 (and (eq last-command this-command)
6801 (eq org-cycle-subtree-status 'children)))
6802 ;; We just showed the children, or no children are there,
6803 ;; now show everything.
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6806 (outline-flag-region eoh eos nil)
6807 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6808 (setq org-cycle-subtree-status 'subtree)
6809 (unless (org-before-first-heading-p)
6810 (run-hook-with-args 'org-cycle-hook 'subtree)))
6812 ;; Default action: hide the subtree.
6813 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6814 (outline-flag-region eoh eos t)
6815 (message "FOLDED")
6816 (setq org-cycle-subtree-status 'folded)
6817 (unless (org-before-first-heading-p)
6818 (run-hook-with-args 'org-cycle-hook 'folded))))))
6820 ;;;###autoload
6821 (defun org-global-cycle (&optional arg)
6822 "Cycle the global visibility. For details see `org-cycle'.
6823 With \\[universal-argument] prefix arg, switch to startup visibility.
6824 With a numeric prefix, show all headlines up to that level."
6825 (interactive "P")
6826 (let ((org-cycle-include-plain-lists
6827 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6828 (cond
6829 ((integerp arg)
6830 (show-all)
6831 (hide-sublevels arg)
6832 (setq org-cycle-global-status 'contents))
6833 ((equal arg '(4))
6834 (org-set-startup-visibility)
6835 (message "Startup visibility, plus VISIBILITY properties."))
6837 (org-cycle '(4))))))
6839 (defun org-set-startup-visibility ()
6840 "Set the visibility required by startup options and properties."
6841 (cond
6842 ((eq org-startup-folded t)
6843 (org-cycle '(4)))
6844 ((eq org-startup-folded 'content)
6845 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6846 (org-cycle '(4)) (org-cycle '(4)))))
6847 (unless (eq org-startup-folded 'showeverything)
6848 (if org-hide-block-startup (org-hide-block-all))
6849 (org-set-visibility-according-to-property 'no-cleanup)
6850 (org-cycle-hide-archived-subtrees 'all)
6851 (org-cycle-hide-drawers 'all)
6852 (org-cycle-show-empty-lines t)))
6854 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6855 "Switch subtree visibilities according to :VISIBILITY: property."
6856 (interactive)
6857 (let (org-show-entry-below state)
6858 (save-excursion
6859 (goto-char (point-min))
6860 (while (re-search-forward
6861 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6862 nil t)
6863 (setq state (match-string 1))
6864 (save-excursion
6865 (org-back-to-heading t)
6866 (hide-subtree)
6867 (org-reveal)
6868 (cond
6869 ((equal state '("fold" "folded"))
6870 (hide-subtree))
6871 ((equal state "children")
6872 (org-show-hidden-entry)
6873 (show-children))
6874 ((equal state "content")
6875 (save-excursion
6876 (save-restriction
6877 (org-narrow-to-subtree)
6878 (org-content))))
6879 ((member state '("all" "showall"))
6880 (show-subtree)))))
6881 (unless no-cleanup
6882 (org-cycle-hide-archived-subtrees 'all)
6883 (org-cycle-hide-drawers 'all)
6884 (org-cycle-show-empty-lines 'all)))))
6886 ;; This function uses outline-regexp instead of the more fundamental
6887 ;; org-outline-regexp so that org-cycle-global works outside of Org
6888 ;; buffers, where outline-regexp is needed.
6889 (defun org-overview ()
6890 "Switch to overview mode, showing only top-level headlines.
6891 Really, this shows all headlines with level equal or greater than the level
6892 of the first headline in the buffer. This is important, because if the
6893 first headline is not level one, then (hide-sublevels 1) gives confusing
6894 results."
6895 (interactive)
6896 (let ((l (org-current-line))
6897 (level (save-excursion
6898 (goto-char (point-min))
6899 (if (re-search-forward (concat "^" outline-regexp) nil t)
6900 (progn
6901 (goto-char (match-beginning 0))
6902 (funcall outline-level))))))
6903 (and level (hide-sublevels level))
6904 (recenter '(4))
6905 (org-goto-line l)))
6907 (defun org-content (&optional arg)
6908 "Show all headlines in the buffer, like a table of contents.
6909 With numerical argument N, show content up to level N."
6910 (interactive "P")
6911 (save-excursion
6912 ;; Visit all headings and show their offspring
6913 (and (integerp arg) (org-overview))
6914 (goto-char (point-max))
6915 (catch 'exit
6916 (while (and (progn (condition-case nil
6917 (outline-previous-visible-heading 1)
6918 (error (goto-char (point-min))))
6920 (looking-at org-outline-regexp))
6921 (if (integerp arg)
6922 (show-children (1- arg))
6923 (show-branches))
6924 (if (bobp) (throw 'exit nil))))))
6927 (defun org-optimize-window-after-visibility-change (state)
6928 "Adjust the window after a change in outline visibility.
6929 This function is the default value of the hook `org-cycle-hook'."
6930 (when (get-buffer-window (current-buffer))
6931 (cond
6932 ((eq state 'content) nil)
6933 ((eq state 'all) nil)
6934 ((eq state 'folded) nil)
6935 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6936 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6938 (defun org-remove-empty-overlays-at (pos)
6939 "Remove outline overlays that do not contain non-white stuff."
6940 (mapc
6941 (lambda (o)
6942 (and (eq 'outline (overlay-get o 'invisible))
6943 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6944 (overlay-end o))))
6945 (delete-overlay o)))
6946 (overlays-at pos)))
6948 (defun org-clean-visibility-after-subtree-move ()
6949 "Fix visibility issues after moving a subtree."
6950 ;; First, find a reasonable region to look at:
6951 ;; Start two siblings above, end three below
6952 (let* ((beg (save-excursion
6953 (and (org-get-last-sibling)
6954 (org-get-last-sibling))
6955 (point)))
6956 (end (save-excursion
6957 (and (org-get-next-sibling)
6958 (org-get-next-sibling)
6959 (org-get-next-sibling))
6960 (if (org-at-heading-p)
6961 (point-at-eol)
6962 (point))))
6963 (level (looking-at "\\*+"))
6964 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6965 (save-excursion
6966 (save-restriction
6967 (narrow-to-region beg end)
6968 (when re
6969 ;; Properly fold already folded siblings
6970 (goto-char (point-min))
6971 (while (re-search-forward re nil t)
6972 (if (and (not (outline-invisible-p))
6973 (save-excursion
6974 (goto-char (point-at-eol)) (outline-invisible-p)))
6975 (hide-entry))))
6976 (org-cycle-show-empty-lines 'overview)
6977 (org-cycle-hide-drawers 'overview)))))
6979 (defun org-cycle-show-empty-lines (state)
6980 "Show empty lines above all visible headlines.
6981 The region to be covered depends on STATE when called through
6982 `org-cycle-hook'. Lisp program can use t for STATE to get the
6983 entire buffer covered. Note that an empty line is only shown if there
6984 are at least `org-cycle-separator-lines' empty lines before the headline."
6985 (when (not (= org-cycle-separator-lines 0))
6986 (save-excursion
6987 (let* ((n (abs org-cycle-separator-lines))
6988 (re (cond
6989 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6990 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6991 (t (let ((ns (number-to-string (- n 2))))
6992 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6993 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6994 beg end b e)
6995 (cond
6996 ((memq state '(overview contents t))
6997 (setq beg (point-min) end (point-max)))
6998 ((memq state '(children folded))
6999 (setq beg (point) end (progn (org-end-of-subtree t t)
7000 (beginning-of-line 2)
7001 (point)))))
7002 (when beg
7003 (goto-char beg)
7004 (while (re-search-forward re end t)
7005 (unless (get-char-property (match-end 1) 'invisible)
7006 (setq e (match-end 1))
7007 (if (< org-cycle-separator-lines 0)
7008 (setq b (save-excursion
7009 (goto-char (match-beginning 0))
7010 (org-back-over-empty-lines)
7011 (if (save-excursion
7012 (goto-char (max (point-min) (1- (point))))
7013 (org-at-heading-p))
7014 (1- (point))
7015 (point))))
7016 (setq b (match-beginning 1)))
7017 (outline-flag-region b e nil)))))))
7018 ;; Never hide empty lines at the end of the file.
7019 (save-excursion
7020 (goto-char (point-max))
7021 (outline-previous-heading)
7022 (outline-end-of-heading)
7023 (if (and (looking-at "[ \t\n]+")
7024 (= (match-end 0) (point-max)))
7025 (outline-flag-region (point) (match-end 0) nil))))
7027 (defun org-show-empty-lines-in-parent ()
7028 "Move to the parent and re-show empty lines before visible headlines."
7029 (save-excursion
7030 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7031 (org-cycle-show-empty-lines context))))
7033 (defun org-files-list ()
7034 "Return `org-agenda-files' list, plus all open org-mode files.
7035 This is useful for operations that need to scan all of a user's
7036 open and agenda-wise Org files."
7037 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7038 (dolist (buf (buffer-list))
7039 (with-current-buffer buf
7040 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7041 (let ((file (expand-file-name (buffer-file-name))))
7042 (unless (member file files)
7043 (push file files))))))
7044 files))
7046 (defsubst org-entry-beginning-position ()
7047 "Return the beginning position of the current entry."
7048 (save-excursion (outline-back-to-heading t) (point)))
7050 (defsubst org-entry-end-position ()
7051 "Return the end position of the current entry."
7052 (save-excursion (outline-next-heading) (point)))
7054 (defun org-cycle-hide-drawers (state)
7055 "Re-hide all drawers after a visibility state change."
7056 (when (and (derived-mode-p 'org-mode)
7057 (not (memq state '(overview folded contents))))
7058 (save-excursion
7059 (let* ((globalp (memq state '(contents all)))
7060 (beg (if globalp (point-min) (point)))
7061 (end (if globalp (point-max)
7062 (if (eq state 'children)
7063 (save-excursion (outline-next-heading) (point))
7064 (org-end-of-subtree t)))))
7065 (goto-char beg)
7066 (while (re-search-forward org-drawer-regexp end t)
7067 (org-flag-drawer t))))))
7069 (defun org-cycle-hide-inline-tasks (state)
7070 "Re-hide inline task when switching to 'contents visibility state."
7071 (when (and (eq state 'contents)
7072 (boundp 'org-inlinetask-min-level)
7073 org-inlinetask-min-level)
7074 (hide-sublevels (1- org-inlinetask-min-level))))
7076 (defun org-flag-drawer (flag)
7077 "When FLAG is non-nil, hide the drawer we are within.
7078 Otherwise make it visible."
7079 (save-excursion
7080 (beginning-of-line 1)
7081 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7082 (let ((b (match-end 0)))
7083 (if (re-search-forward
7084 "^[ \t]*:END:"
7085 (save-excursion (outline-next-heading) (point)) t)
7086 (outline-flag-region b (point-at-eol) flag)
7087 (user-error ":END: line missing at position %s" b))))))
7089 (defun org-subtree-end-visible-p ()
7090 "Is the end of the current subtree visible?"
7091 (pos-visible-in-window-p
7092 (save-excursion (org-end-of-subtree t) (point))))
7094 (defun org-first-headline-recenter (&optional N)
7095 "Move cursor to the first headline and recenter the headline.
7096 Optional argument N means put the headline into the Nth line of the window."
7097 (goto-char (point-min))
7098 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7099 (beginning-of-line)
7100 (recenter (prefix-numeric-value N))))
7102 ;;; Saving and restoring visibility
7104 (defun org-outline-overlay-data (&optional use-markers)
7105 "Return a list of the locations of all outline overlays.
7106 These are overlays with the `invisible' property value `outline'.
7107 The return value is a list of cons cells, with start and stop
7108 positions for each overlay.
7109 If USE-MARKERS is set, return the positions as markers."
7110 (let (beg end)
7111 (save-excursion
7112 (save-restriction
7113 (widen)
7114 (delq nil
7115 (mapcar (lambda (o)
7116 (when (eq (overlay-get o 'invisible) 'outline)
7117 (setq beg (overlay-start o)
7118 end (overlay-end o))
7119 (and beg end (> end beg)
7120 (if use-markers
7121 (cons (move-marker (make-marker) beg)
7122 (move-marker (make-marker) end))
7123 (cons beg end)))))
7124 (overlays-in (point-min) (point-max))))))))
7126 (defun org-set-outline-overlay-data (data)
7127 "Create visibility overlays for all positions in DATA.
7128 DATA should have been made by `org-outline-overlay-data'."
7129 (let (o)
7130 (save-excursion
7131 (save-restriction
7132 (widen)
7133 (show-all)
7134 (mapc (lambda (c)
7135 (outline-flag-region (car c) (cdr c) t))
7136 data)))))
7138 ;;; Folding of blocks
7140 (defvar org-hide-block-overlays nil
7141 "Overlays hiding blocks.")
7142 (make-variable-buffer-local 'org-hide-block-overlays)
7144 (defun org-block-map (function &optional start end)
7145 "Call FUNCTION at the head of all source blocks in the current buffer.
7146 Optional arguments START and END can be used to limit the range."
7147 (let ((start (or start (point-min)))
7148 (end (or end (point-max))))
7149 (save-excursion
7150 (goto-char start)
7151 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7152 (save-excursion
7153 (save-match-data
7154 (goto-char (match-beginning 0))
7155 (funcall function)))))))
7157 (defun org-hide-block-toggle-all ()
7158 "Toggle the visibility of all blocks in the current buffer."
7159 (org-block-map #'org-hide-block-toggle))
7161 (defun org-hide-block-all ()
7162 "Fold all blocks in the current buffer."
7163 (interactive)
7164 (org-show-block-all)
7165 (org-block-map #'org-hide-block-toggle-maybe))
7167 (defun org-show-block-all ()
7168 "Unfold all blocks in the current buffer."
7169 (interactive)
7170 (mapc 'delete-overlay org-hide-block-overlays)
7171 (setq org-hide-block-overlays nil))
7173 (defun org-hide-block-toggle-maybe ()
7174 "Toggle visibility of block at point."
7175 (interactive)
7176 (let ((case-fold-search t))
7177 (if (save-excursion
7178 (beginning-of-line 1)
7179 (looking-at org-block-regexp))
7180 (progn (org-hide-block-toggle)
7181 t) ;; to signal that we took action
7182 nil))) ;; to signal that we did not
7184 (defun org-hide-block-toggle (&optional force)
7185 "Toggle the visibility of the current block."
7186 (interactive)
7187 (save-excursion
7188 (beginning-of-line)
7189 (if (re-search-forward org-block-regexp nil t)
7190 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7191 (end (match-end 0)) ;; end of entire body
7193 (if (memq t (mapcar (lambda (overlay)
7194 (eq (overlay-get overlay 'invisible)
7195 'org-hide-block))
7196 (overlays-at start)))
7197 (if (or (not force) (eq force 'off))
7198 (mapc (lambda (ov)
7199 (when (member ov org-hide-block-overlays)
7200 (setq org-hide-block-overlays
7201 (delq ov org-hide-block-overlays)))
7202 (when (eq (overlay-get ov 'invisible)
7203 'org-hide-block)
7204 (delete-overlay ov)))
7205 (overlays-at start)))
7206 (setq ov (make-overlay start end))
7207 (overlay-put ov 'invisible 'org-hide-block)
7208 ;; make the block accessible to isearch
7209 (overlay-put
7210 ov 'isearch-open-invisible
7211 (lambda (ov)
7212 (when (member ov org-hide-block-overlays)
7213 (setq org-hide-block-overlays
7214 (delq ov org-hide-block-overlays)))
7215 (when (eq (overlay-get ov 'invisible)
7216 'org-hide-block)
7217 (delete-overlay ov))))
7218 (push ov org-hide-block-overlays)))
7219 (user-error "Not looking at a source block"))))
7221 ;; org-tab-after-check-for-cycling-hook
7222 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7223 ;; Remove overlays when changing major mode
7224 (add-hook 'org-mode-hook
7225 (lambda () (org-add-hook 'change-major-mode-hook
7226 'org-show-block-all 'append 'local)))
7228 ;;; Org-goto
7230 (defvar org-goto-window-configuration nil)
7231 (defvar org-goto-marker nil)
7232 (defvar org-goto-map)
7233 (defun org-goto-map ()
7234 "Set the keymap `org-goto'."
7235 (setq org-goto-map
7236 (let ((map (make-sparse-keymap)))
7237 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7238 mouse-drag-region universal-argument org-occur))
7239 cmd)
7240 (while (setq cmd (pop cmds))
7241 (substitute-key-definition cmd cmd map global-map)))
7242 (suppress-keymap map)
7243 (org-defkey map "\C-m" 'org-goto-ret)
7244 (org-defkey map [(return)] 'org-goto-ret)
7245 (org-defkey map [(left)] 'org-goto-left)
7246 (org-defkey map [(right)] 'org-goto-right)
7247 (org-defkey map [(control ?g)] 'org-goto-quit)
7248 (org-defkey map "\C-i" 'org-cycle)
7249 (org-defkey map [(tab)] 'org-cycle)
7250 (org-defkey map [(down)] 'outline-next-visible-heading)
7251 (org-defkey map [(up)] 'outline-previous-visible-heading)
7252 (if org-goto-auto-isearch
7253 (if (fboundp 'define-key-after)
7254 (define-key-after map [t] 'org-goto-local-auto-isearch)
7255 nil)
7256 (org-defkey map "q" 'org-goto-quit)
7257 (org-defkey map "n" 'outline-next-visible-heading)
7258 (org-defkey map "p" 'outline-previous-visible-heading)
7259 (org-defkey map "f" 'outline-forward-same-level)
7260 (org-defkey map "b" 'outline-backward-same-level)
7261 (org-defkey map "u" 'outline-up-heading))
7262 (org-defkey map "/" 'org-occur)
7263 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7264 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7265 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7266 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7267 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7268 map)))
7270 (defconst org-goto-help
7271 "Browse buffer copy, to find location or copy text.%s
7272 RET=jump to location C-g=quit and return to previous location
7273 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7275 (defvar org-goto-start-pos) ; dynamically scoped parameter
7277 (defun org-goto (&optional alternative-interface)
7278 "Look up a different location in the current file, keeping current visibility.
7280 When you want look-up or go to a different location in a
7281 document, the fastest way is often to fold the entire buffer and
7282 then dive into the tree. This method has the disadvantage, that
7283 the previous location will be folded, which may not be what you
7284 want.
7286 This command works around this by showing a copy of the current
7287 buffer in an indirect buffer, in overview mode. You can dive
7288 into the tree in that copy, use org-occur and incremental search
7289 to find a location. When pressing RET or `Q', the command
7290 returns to the original buffer in which the visibility is still
7291 unchanged. After RET it will also jump to the location selected
7292 in the indirect buffer and expose the headline hierarchy above.
7294 With a prefix argument, use the alternative interface: e.g. if
7295 `org-goto-interface' is 'outline use 'outline-path-completion."
7296 (interactive "P")
7297 (org-goto-map)
7298 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7299 (org-refile-use-outline-path t)
7300 (org-refile-target-verify-function nil)
7301 (interface
7302 (if (not alternative-interface)
7303 org-goto-interface
7304 (if (eq org-goto-interface 'outline)
7305 'outline-path-completion
7306 'outline)))
7307 (org-goto-start-pos (point))
7308 (selected-point
7309 (if (eq interface 'outline)
7310 (car (org-get-location (current-buffer) org-goto-help))
7311 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7312 (org-refile-check-position pa)
7313 (nth 3 pa)))))
7314 (if selected-point
7315 (progn
7316 (org-mark-ring-push org-goto-start-pos)
7317 (goto-char selected-point)
7318 (if (or (outline-invisible-p) (org-invisible-p2))
7319 (org-show-context 'org-goto)))
7320 (message "Quit"))))
7322 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7323 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7324 (defvar org-goto-local-auto-isearch-map) ; defined below
7326 (defun org-get-location (buf help)
7327 "Let the user select a location in the Org-mode buffer BUF.
7328 This function uses a recursive edit. It returns the selected position
7329 or nil."
7330 (org-no-popups
7331 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7332 (isearch-hide-immediately nil)
7333 (isearch-search-fun-function
7334 (lambda () 'org-goto-local-search-headings))
7335 (org-goto-selected-point org-goto-exit-command))
7336 (save-excursion
7337 (save-window-excursion
7338 (delete-other-windows)
7339 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7340 (org-pop-to-buffer-same-window
7341 (condition-case nil
7342 (make-indirect-buffer (current-buffer) "*org-goto*")
7343 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7344 (with-output-to-temp-buffer "*Org Help*"
7345 (princ (format help (if org-goto-auto-isearch
7346 " Just type for auto-isearch."
7347 " n/p/f/b/u to navigate, q to quit."))))
7348 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7349 (setq buffer-read-only nil)
7350 (let ((org-startup-truncated t)
7351 (org-startup-folded nil)
7352 (org-startup-align-all-tables nil))
7353 (org-mode)
7354 (org-overview))
7355 (setq buffer-read-only t)
7356 (if (and (boundp 'org-goto-start-pos)
7357 (integer-or-marker-p org-goto-start-pos))
7358 (let ((org-show-hierarchy-above t)
7359 (org-show-siblings t)
7360 (org-show-following-heading t))
7361 (goto-char org-goto-start-pos)
7362 (and (outline-invisible-p) (org-show-context)))
7363 (goto-char (point-min)))
7364 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7365 (message "Select location and press RET")
7366 (use-local-map org-goto-map)
7367 (recursive-edit)))
7368 (kill-buffer "*org-goto*")
7369 (cons org-goto-selected-point org-goto-exit-command))))
7371 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7372 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7373 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7374 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7376 (defun org-goto-local-search-headings (string bound noerror)
7377 "Search and make sure that any matches are in headlines."
7378 (catch 'return
7379 (while (if isearch-forward
7380 (search-forward string bound noerror)
7381 (search-backward string bound noerror))
7382 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7383 (and (member :headline context)
7384 (not (member :tags context))))
7385 (throw 'return (point))))))
7387 (defun org-goto-local-auto-isearch ()
7388 "Start isearch."
7389 (interactive)
7390 (goto-char (point-min))
7391 (let ((keys (this-command-keys)))
7392 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7393 (isearch-mode t)
7394 (isearch-process-search-char (string-to-char keys)))))
7396 (defun org-goto-ret (&optional arg)
7397 "Finish `org-goto' by going to the new location."
7398 (interactive "P")
7399 (setq org-goto-selected-point (point)
7400 org-goto-exit-command 'return)
7401 (throw 'exit nil))
7403 (defun org-goto-left ()
7404 "Finish `org-goto' by going to the new location."
7405 (interactive)
7406 (if (org-at-heading-p)
7407 (progn
7408 (beginning-of-line 1)
7409 (setq org-goto-selected-point (point)
7410 org-goto-exit-command 'left)
7411 (throw 'exit nil))
7412 (user-error "Not on a heading")))
7414 (defun org-goto-right ()
7415 "Finish `org-goto' by going to the new location."
7416 (interactive)
7417 (if (org-at-heading-p)
7418 (progn
7419 (setq org-goto-selected-point (point)
7420 org-goto-exit-command 'right)
7421 (throw 'exit nil))
7422 (user-error "Not on a heading")))
7424 (defun org-goto-quit ()
7425 "Finish `org-goto' without cursor motion."
7426 (interactive)
7427 (setq org-goto-selected-point nil)
7428 (setq org-goto-exit-command 'quit)
7429 (throw 'exit nil))
7431 ;;; Indirect buffer display of subtrees
7433 (defvar org-indirect-dedicated-frame nil
7434 "This is the frame being used for indirect tree display.")
7435 (defvar org-last-indirect-buffer nil)
7437 (defun org-tree-to-indirect-buffer (&optional arg)
7438 "Create indirect buffer and narrow it to current subtree.
7439 With a numerical prefix ARG, go up to this level and then take that tree.
7440 If ARG is negative, go up that many levels.
7442 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7443 indirect buffer previously made with this command, to avoid proliferation of
7444 indirect buffers. However, when you call the command with a \
7445 \\[universal-argument] prefix, or
7446 when `org-indirect-buffer-display' is `new-frame', the last buffer
7447 is kept so that you can work with several indirect buffers at the same time.
7448 If `org-indirect-buffer-display' is `dedicated-frame', the \
7449 \\[universal-argument] prefix also
7450 requests that a new frame be made for the new buffer, so that the dedicated
7451 frame is not changed."
7452 (interactive "P")
7453 (let ((cbuf (current-buffer))
7454 (cwin (selected-window))
7455 (pos (point))
7456 beg end level heading ibuf)
7457 (save-excursion
7458 (org-back-to-heading t)
7459 (when (numberp arg)
7460 (setq level (org-outline-level))
7461 (if (< arg 0) (setq arg (+ level arg)))
7462 (while (> (setq level (org-outline-level)) arg)
7463 (org-up-heading-safe)))
7464 (setq beg (point)
7465 heading (org-get-heading))
7466 (org-end-of-subtree t t)
7467 (if (org-at-heading-p) (backward-char 1))
7468 (setq end (point)))
7469 (if (and (buffer-live-p org-last-indirect-buffer)
7470 (not (eq org-indirect-buffer-display 'new-frame))
7471 (not arg))
7472 (kill-buffer org-last-indirect-buffer))
7473 (setq ibuf (org-get-indirect-buffer cbuf)
7474 org-last-indirect-buffer ibuf)
7475 (cond
7476 ((or (eq org-indirect-buffer-display 'new-frame)
7477 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7478 (select-frame (make-frame))
7479 (delete-other-windows)
7480 (org-pop-to-buffer-same-window ibuf)
7481 (org-set-frame-title heading))
7482 ((eq org-indirect-buffer-display 'dedicated-frame)
7483 (raise-frame
7484 (select-frame (or (and org-indirect-dedicated-frame
7485 (frame-live-p org-indirect-dedicated-frame)
7486 org-indirect-dedicated-frame)
7487 (setq org-indirect-dedicated-frame (make-frame)))))
7488 (delete-other-windows)
7489 (org-pop-to-buffer-same-window ibuf)
7490 (org-set-frame-title (concat "Indirect: " heading)))
7491 ((eq org-indirect-buffer-display 'current-window)
7492 (org-pop-to-buffer-same-window ibuf))
7493 ((eq org-indirect-buffer-display 'other-window)
7494 (pop-to-buffer ibuf))
7495 (t (error "Invalid value")))
7496 (if (featurep 'xemacs)
7497 (save-excursion (org-mode) (turn-on-font-lock)))
7498 (narrow-to-region beg end)
7499 (show-all)
7500 (goto-char pos)
7501 (run-hook-with-args 'org-cycle-hook 'all)
7502 (and (window-live-p cwin) (select-window cwin))))
7504 (defun org-get-indirect-buffer (&optional buffer)
7505 (setq buffer (or buffer (current-buffer)))
7506 (let ((n 1) (base (buffer-name buffer)) bname)
7507 (while (buffer-live-p
7508 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7509 (setq n (1+ n)))
7510 (condition-case nil
7511 (make-indirect-buffer buffer bname 'clone)
7512 (error (make-indirect-buffer buffer bname)))))
7514 (defun org-set-frame-title (title)
7515 "Set the title of the current frame to the string TITLE."
7516 ;; FIXME: how to name a single frame in XEmacs???
7517 (unless (featurep 'xemacs)
7518 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7520 ;;;; Structure editing
7522 ;;; Inserting headlines
7524 (defun org-previous-line-empty-p (&optional next)
7525 "Is the previous line a blank line?
7526 When NEXT is non-nil, check the next line instead."
7527 (save-excursion
7528 (and (not (bobp))
7529 (or (beginning-of-line (if next 2 0)) t)
7530 (save-match-data
7531 (looking-at "[ \t]*$")))))
7533 (defun org-insert-heading (&optional arg invisible-ok)
7534 "Insert a new heading or item with same depth at point.
7535 If point is in a plain list and ARG is nil, create a new list item.
7536 With one universal prefix argument, insert a heading even in lists.
7537 With two universal prefix arguments, insert the heading at the end
7538 of the parent subtree.
7540 If point is at the beginning of a headline, insert a sibling before
7541 the current headline. If point is not at the beginning, split the line
7542 and create a new headline with the text in the current line after point
7543 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7545 If point is at the beginning of a normal line, turn this line into
7546 a heading.
7548 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7549 This is important for non-interactive uses of the command."
7550 (interactive "P")
7551 (if (org-called-interactively-p 'any) (org-reveal))
7552 (let ((itemp (org-in-item-p))
7553 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7554 (respect-content (or org-insert-heading-respect-content
7555 (equal arg '(16))))
7556 (initial-content "")
7557 (adjust-empty-lines t))
7559 (cond
7561 ((or (= (buffer-size) 0)
7562 (and (not (save-excursion
7563 (and (ignore-errors (org-back-to-heading invisible-ok))
7564 (org-at-heading-p))))
7565 (or arg (not itemp))))
7566 ;; At beginning of buffer or so hight up that only a heading makes sense.
7567 (insert
7568 (if (org-previous-line-empty-p) "" "\n")
7569 (if (org-in-src-block-p) ",* " "* "))
7570 (run-hooks 'org-insert-heading-hook))
7572 ((and itemp (not (equal arg '(4))))
7573 ;; Insert an item
7574 (org-insert-item))
7577 ;; Insert a heading
7578 (save-restriction
7579 (widen)
7580 (let* ((empty-line-p nil)
7581 (level nil)
7582 (on-heading (org-at-heading-p))
7583 ;; Get a level to fall back on
7584 (fix-level
7585 (save-excursion
7586 (org-back-to-heading t)
7587 (looking-at org-outline-regexp)
7588 (make-string (1- (length (match-string 0))) ?*)))
7589 (stars
7590 (save-excursion
7591 (condition-case nil
7592 (progn
7593 (org-back-to-heading invisible-ok)
7594 (when (and (not on-heading)
7595 (featurep 'org-inlinetask)
7596 (integerp org-inlinetask-min-level)
7597 (>= (length (match-string 0))
7598 org-inlinetask-min-level))
7599 ;; Find a heading level before the inline task
7600 (while (and (setq level (org-up-heading-safe))
7601 (>= level org-inlinetask-min-level)))
7602 (if (org-at-heading-p)
7603 (org-back-to-heading invisible-ok)
7604 (error "This should not happen")))
7605 (unless (and (save-excursion
7606 (save-match-data
7607 (org-backward-heading-same-level 1 invisible-ok))
7608 (= (point) (match-beginning 0)))
7609 (not (org-previous-line-empty-p t)))
7610 (setq empty-line-p (org-previous-line-empty-p)))
7611 (match-string 0))
7612 (error (or fix-level "* ")))))
7613 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7614 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7615 pos hide-previous previous-pos)
7617 ;; If we insert after content, move there and clean up whitespace
7618 (when respect-content
7619 (org-end-of-subtree nil t)
7620 (when (looking-at "^\\*")
7621 (backward-char 1)
7622 (insert "\n")))
7624 ;; If we are splitting, grab the text that should be moved to the new headline
7625 (when may-split
7626 (if (org-on-heading-p)
7627 ;; This is a heading, we split intelligently (keeping tags)
7628 (let ((pos (point)))
7629 (goto-char (point-at-bol))
7630 (unless (looking-at org-complex-heading-regexp)
7631 (error "This should not happen"))
7632 (when (and (match-beginning 4)
7633 (> pos (match-beginning 4))
7634 (< pos (match-end 4)))
7635 (setq initial-content (buffer-substring pos (match-end 4)))
7636 (goto-char pos)
7637 (delete-region (point) (match-end 4))
7638 (if (looking-at "[ \t]*$")
7639 (replace-match "")
7640 (insert (make-string (length initial-content) ?\ )))
7641 (setq initial-content (org-trim initial-content)))
7642 (goto-char pos))
7643 ;; a normal line
7644 (setq initial-content (buffer-substring (point) (point-at-eol)))
7645 (delete-region (point) (point-at-eol))
7646 (setq initial-content (org-trim initial-content))))
7648 ;; If we are at the beginning of the line, insert before it. Else after
7649 (cond
7650 ((and (bolp) (looking-at "[ \t]*$")))
7651 ((and (bolp) (not (looking-at "[ \t]*$")))
7652 (open-line 1))
7654 (goto-char (point-at-eol))
7655 (insert "\n")))
7657 ;; Insert the new heading
7658 (insert stars)
7659 (just-one-space)
7660 (insert initial-content)
7661 (if adjust-empty-lines (org-N-empty-lines-before-current (if empty-line-p 1 0)))
7662 (run-hooks 'org-insert-heading-hook)))))))
7664 (defun org-N-empty-lines-before-current (N)
7665 "Make the number of empty lines before current exactly N.
7666 So this will delete or add empty lines."
7667 (save-excursion
7668 (goto-char (point-at-bol))
7669 (if (looking-back "\\s-+" nil 'greedy)
7670 (replace-match ""))
7671 (or (bobp) (insert "\n"))
7672 (while (> N 0)
7673 (insert "\n")
7674 (setq N (1- N)))))
7676 (defun org-get-heading (&optional no-tags no-todo)
7677 "Return the heading of the current entry, without the stars.
7678 When NO-TAGS is non-nil, don't include tags.
7679 When NO-TODO is non-nil, don't include TODO keywords."
7680 (save-excursion
7681 (org-back-to-heading t)
7682 (cond
7683 ((and no-tags no-todo)
7684 (looking-at org-complex-heading-regexp)
7685 (match-string 4))
7686 (no-tags
7687 (looking-at (concat org-outline-regexp
7688 "\\(.*?\\)"
7689 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7690 (match-string 1))
7691 (no-todo
7692 (looking-at org-todo-line-regexp)
7693 (match-string 3))
7694 (t (looking-at org-heading-regexp)
7695 (match-string 2)))))
7697 (defvar orgstruct-mode) ; defined below
7699 (defun org-heading-components ()
7700 "Return the components of the current heading.
7701 This is a list with the following elements:
7702 - the level as an integer
7703 - the reduced level, different if `org-odd-levels-only' is set.
7704 - the TODO keyword, or nil
7705 - the priority character, like ?A, or nil if no priority is given
7706 - the headline text itself, or the tags string if no headline text
7707 - the tags string, or nil."
7708 (save-excursion
7709 (org-back-to-heading t)
7710 (if (let (case-fold-search)
7711 (looking-at
7712 (if orgstruct-mode
7713 org-heading-regexp
7714 org-complex-heading-regexp)))
7715 (if orgstruct-mode
7716 (list (length (match-string 1))
7717 (org-reduced-level (length (match-string 1)))
7720 (match-string 2)
7721 nil)
7722 (list (length (match-string 1))
7723 (org-reduced-level (length (match-string 1)))
7724 (org-match-string-no-properties 2)
7725 (and (match-end 3) (aref (match-string 3) 2))
7726 (org-match-string-no-properties 4)
7727 (org-match-string-no-properties 5))))))
7729 (defun org-get-entry ()
7730 "Get the entry text, after heading, entire subtree."
7731 (save-excursion
7732 (org-back-to-heading t)
7733 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7735 (defun org-insert-heading-after-current ()
7736 "Insert a new heading with same level as current, after current subtree."
7737 (interactive)
7738 (org-back-to-heading)
7739 (org-insert-heading)
7740 (org-move-subtree-down)
7741 (end-of-line 1))
7743 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7744 "Insert heading with `org-insert-heading-respect-content' set to t."
7745 (interactive "P")
7746 (let ((org-insert-heading-respect-content t))
7747 (org-insert-heading '(4) invisible-ok)))
7749 (defun org-insert-todo-heading-respect-content (&optional force-state)
7750 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7751 (interactive "P")
7752 (let ((org-insert-heading-respect-content t))
7753 (org-insert-todo-heading force-state t)))
7755 (defun org-insert-todo-heading (arg &optional force-heading)
7756 "Insert a new heading with the same level and TODO state as current heading.
7757 If the heading has no TODO state, or if the state is DONE, use the first
7758 state (TODO by default). Also one prefix arg, force first state. With two
7759 prefix args, force inserting at the end of the parent subtree."
7760 (interactive "P")
7761 (when (or force-heading (not (org-insert-item 'checkbox)))
7762 (org-insert-heading (or (and (equal arg '(16)) '(16))
7763 force-heading))
7764 (save-excursion
7765 (org-back-to-heading)
7766 (outline-previous-heading)
7767 (looking-at org-todo-line-regexp))
7768 (let*
7769 ((new-mark-x
7770 (if (or arg
7771 (not (match-beginning 2))
7772 (member (match-string 2) org-done-keywords))
7773 (car org-todo-keywords-1)
7774 (match-string 2)))
7775 (new-mark
7777 (run-hook-with-args-until-success
7778 'org-todo-get-default-hook new-mark-x nil)
7779 new-mark-x)))
7780 (beginning-of-line 1)
7781 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7782 (if org-treat-insert-todo-heading-as-state-change
7783 (org-todo new-mark)
7784 (insert new-mark " "))))
7785 (when org-provide-todo-statistics
7786 (org-update-parent-todo-statistics))))
7788 (defun org-insert-subheading (arg)
7789 "Insert a new subheading and demote it.
7790 Works for outline headings and for plain lists alike."
7791 (interactive "P")
7792 (org-insert-heading arg)
7793 (cond
7794 ((org-at-heading-p) (org-do-demote))
7795 ((org-at-item-p) (org-indent-item))))
7797 (defun org-insert-todo-subheading (arg)
7798 "Insert a new subheading with TODO keyword or checkbox and demote it.
7799 Works for outline headings and for plain lists alike."
7800 (interactive "P")
7801 (org-insert-todo-heading arg)
7802 (cond
7803 ((org-at-heading-p) (org-do-demote))
7804 ((org-at-item-p) (org-indent-item))))
7806 ;;; Promotion and Demotion
7808 (defvar org-after-demote-entry-hook nil
7809 "Hook run after an entry has been demoted.
7810 The cursor will be at the beginning of the entry.
7811 When a subtree is being demoted, the hook will be called for each node.")
7813 (defvar org-after-promote-entry-hook nil
7814 "Hook run after an entry has been promoted.
7815 The cursor will be at the beginning of the entry.
7816 When a subtree is being promoted, the hook will be called for each node.")
7818 (defun org-promote-subtree ()
7819 "Promote the entire subtree.
7820 See also `org-promote'."
7821 (interactive)
7822 (save-excursion
7823 (org-with-limited-levels (org-map-tree 'org-promote)))
7824 (org-fix-position-after-promote))
7826 (defun org-demote-subtree ()
7827 "Demote the entire subtree. See `org-demote'.
7828 See also `org-promote'."
7829 (interactive)
7830 (save-excursion
7831 (org-with-limited-levels (org-map-tree 'org-demote)))
7832 (org-fix-position-after-promote))
7835 (defun org-do-promote ()
7836 "Promote the current heading higher up the tree.
7837 If the region is active in `transient-mark-mode', promote all headings
7838 in the region."
7839 (interactive)
7840 (save-excursion
7841 (if (org-region-active-p)
7842 (org-map-region 'org-promote (region-beginning) (region-end))
7843 (org-promote)))
7844 (org-fix-position-after-promote))
7846 (defun org-do-demote ()
7847 "Demote the current heading lower down the tree.
7848 If the region is active in `transient-mark-mode', demote all headings
7849 in the region."
7850 (interactive)
7851 (save-excursion
7852 (if (org-region-active-p)
7853 (org-map-region 'org-demote (region-beginning) (region-end))
7854 (org-demote)))
7855 (org-fix-position-after-promote))
7857 (defun org-fix-position-after-promote ()
7858 "Make sure that after pro/demotion cursor position is right."
7859 (let ((pos (point)))
7860 (when (save-excursion
7861 (beginning-of-line 1)
7862 (looking-at org-todo-line-regexp)
7863 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7864 (cond ((eobp) (insert " "))
7865 ((eolp) (insert " "))
7866 ((equal (char-after) ?\ ) (forward-char 1))))))
7868 (defun org-current-level ()
7869 "Return the level of the current entry, or nil if before the first headline.
7870 The level is the number of stars at the beginning of the headline."
7871 (save-excursion
7872 (org-with-limited-levels
7873 (if (ignore-errors (org-back-to-heading t))
7874 (funcall outline-level)))))
7876 (defun org-get-previous-line-level ()
7877 "Return the outline depth of the last headline before the current line.
7878 Returns 0 for the first headline in the buffer, and nil if before the
7879 first headline."
7880 (let ((current-level (org-current-level))
7881 (prev-level (when (> (line-number-at-pos) 1)
7882 (save-excursion
7883 (beginning-of-line 0)
7884 (org-current-level)))))
7885 (cond ((null current-level) nil) ; Before first headline
7886 ((null prev-level) 0) ; At first headline
7887 (prev-level))))
7889 (defun org-reduced-level (l)
7890 "Compute the effective level of a heading.
7891 This takes into account the setting of `org-odd-levels-only'."
7892 (cond
7893 ((zerop l) 0)
7894 (org-odd-levels-only (1+ (floor (/ l 2))))
7895 (t l)))
7897 (defun org-level-increment ()
7898 "Return the number of stars that will be added or removed at a
7899 time to headlines when structure editing, based on the value of
7900 `org-odd-levels-only'."
7901 (if org-odd-levels-only 2 1))
7903 (defun org-get-valid-level (level &optional change)
7904 "Rectify a level change under the influence of `org-odd-levels-only'
7905 LEVEL is a current level, CHANGE is by how much the level should be
7906 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7907 even level numbers will become the next higher odd number."
7908 (if org-odd-levels-only
7909 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7910 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7911 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7912 (max 1 (+ level (or change 0)))))
7914 (if (boundp 'define-obsolete-function-alias)
7915 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7916 (define-obsolete-function-alias 'org-get-legal-level
7917 'org-get-valid-level)
7918 (define-obsolete-function-alias 'org-get-legal-level
7919 'org-get-valid-level "23.1")))
7921 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7922 ;; ̀org-with-limited-levels'
7923 (defun org-promote ()
7924 "Promote the current heading higher up the tree.
7925 If the region is active in `transient-mark-mode', promote all headings
7926 in the region."
7927 (org-back-to-heading t)
7928 (let* ((level (save-match-data (funcall outline-level)))
7929 (after-change-functions (remove 'flyspell-after-change-function
7930 after-change-functions))
7931 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7932 (diff (abs (- level (length up-head) -1))))
7933 (cond ((and (= level 1) org-called-with-limited-levels
7934 org-allow-promoting-top-level-subtree)
7935 (replace-match "# " nil t))
7936 ((= level 1)
7937 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7938 (t (replace-match up-head nil t)))
7939 ;; Fixup tag positioning
7940 (unless (= level 1)
7941 (and org-auto-align-tags (org-set-tags nil t))
7942 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7943 (run-hooks 'org-after-promote-entry-hook)))
7945 (defun org-demote ()
7946 "Demote the current heading lower down the tree.
7947 If the region is active in `transient-mark-mode', demote all headings
7948 in the region."
7949 (org-back-to-heading t)
7950 (let* ((level (save-match-data (funcall outline-level)))
7951 (after-change-functions (remove 'flyspell-after-change-function
7952 after-change-functions))
7953 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7954 (diff (abs (- level (length down-head) -1))))
7955 (replace-match down-head nil t)
7956 ;; Fixup tag positioning
7957 (and org-auto-align-tags (org-set-tags nil t))
7958 (if org-adapt-indentation (org-fixup-indentation diff))
7959 (run-hooks 'org-after-demote-entry-hook)))
7961 (defun org-cycle-level ()
7962 "Cycle the level of an empty headline through possible states.
7963 This goes first to child, then to parent, level, then up the hierarchy.
7964 After top level, it switches back to sibling level."
7965 (interactive)
7966 (let ((org-adapt-indentation nil))
7967 (when (org-point-at-end-of-empty-headline)
7968 (setq this-command 'org-cycle-level) ; Only needed for caching
7969 (let ((cur-level (org-current-level))
7970 (prev-level (org-get-previous-line-level)))
7971 (cond
7972 ;; If first headline in file, promote to top-level.
7973 ((= prev-level 0)
7974 (loop repeat (/ (- cur-level 1) (org-level-increment))
7975 do (org-do-promote)))
7976 ;; If same level as prev, demote one.
7977 ((= prev-level cur-level)
7978 (org-do-demote))
7979 ;; If parent is top-level, promote to top level if not already.
7980 ((= prev-level 1)
7981 (loop repeat (/ (- cur-level 1) (org-level-increment))
7982 do (org-do-promote)))
7983 ;; If top-level, return to prev-level.
7984 ((= cur-level 1)
7985 (loop repeat (/ (- prev-level 1) (org-level-increment))
7986 do (org-do-demote)))
7987 ;; If less than prev-level, promote one.
7988 ((< cur-level prev-level)
7989 (org-do-promote))
7990 ;; If deeper than prev-level, promote until higher than
7991 ;; prev-level.
7992 ((> cur-level prev-level)
7993 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7994 do (org-do-promote))))
7995 t))))
7997 (defun org-map-tree (fun)
7998 "Call FUN for every heading underneath the current one."
7999 (org-back-to-heading)
8000 (let ((level (funcall outline-level)))
8001 (save-excursion
8002 (funcall fun)
8003 (while (and (progn
8004 (outline-next-heading)
8005 (> (funcall outline-level) level))
8006 (not (eobp)))
8007 (funcall fun)))))
8009 (defun org-map-region (fun beg end)
8010 "Call FUN for every heading between BEG and END."
8011 (let ((org-ignore-region t))
8012 (save-excursion
8013 (setq end (copy-marker end))
8014 (goto-char beg)
8015 (if (and (re-search-forward org-outline-regexp-bol nil t)
8016 (< (point) end))
8017 (funcall fun))
8018 (while (and (progn
8019 (outline-next-heading)
8020 (< (point) end))
8021 (not (eobp)))
8022 (funcall fun)))))
8024 (defvar org-property-end-re) ; silence byte-compiler
8025 (defun org-fixup-indentation (diff)
8026 "Change the indentation in the current entry by DIFF.
8027 However, if any line in the current entry has no indentation, or if it
8028 would end up with no indentation after the change, nothing at all is done."
8029 (save-excursion
8030 (let ((end (save-excursion (outline-next-heading)
8031 (point-marker)))
8032 (prohibit (if (> diff 0)
8033 "^\\S-"
8034 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8035 col)
8036 (unless (save-excursion (end-of-line 1)
8037 (re-search-forward prohibit end t))
8038 (while (and (< (point) end)
8039 (re-search-forward "^[ \t]+" end t))
8040 (goto-char (match-end 0))
8041 (setq col (current-column))
8042 (if (< diff 0) (replace-match ""))
8043 (org-indent-to-column (+ diff col))))
8044 (move-marker end nil))))
8046 (defun org-convert-to-odd-levels ()
8047 "Convert an org-mode file with all levels allowed to one with odd levels.
8048 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8049 level 5 etc."
8050 (interactive)
8051 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8052 (let ((outline-level 'org-outline-level)
8053 (org-odd-levels-only nil) n)
8054 (save-excursion
8055 (goto-char (point-min))
8056 (while (re-search-forward "^\\*\\*+ " nil t)
8057 (setq n (- (length (match-string 0)) 2))
8058 (while (>= (setq n (1- n)) 0)
8059 (org-demote))
8060 (end-of-line 1))))))
8062 (defun org-convert-to-oddeven-levels ()
8063 "Convert an org-mode file with only odd levels to one with odd/even levels.
8064 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8065 file contains a section with an even level, conversion would
8066 destroy the structure of the file. An error is signaled in this
8067 case."
8068 (interactive)
8069 (goto-char (point-min))
8070 ;; First check if there are no even levels
8071 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8072 (org-show-context t)
8073 (error "Not all levels are odd in this file. Conversion not possible"))
8074 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8075 (let ((outline-regexp org-outline-regexp)
8076 (outline-level 'org-outline-level)
8077 (org-odd-levels-only nil) n)
8078 (save-excursion
8079 (goto-char (point-min))
8080 (while (re-search-forward "^\\*\\*+ " nil t)
8081 (setq n (/ (1- (length (match-string 0))) 2))
8082 (while (>= (setq n (1- n)) 0)
8083 (org-promote))
8084 (end-of-line 1))))))
8086 (defun org-tr-level (n)
8087 "Make N odd if required."
8088 (if org-odd-levels-only (1+ (/ n 2)) n))
8090 ;;; Vertical tree motion, cutting and pasting of subtrees
8092 (defun org-move-subtree-up (&optional arg)
8093 "Move the current subtree up past ARG headlines of the same level."
8094 (interactive "p")
8095 (org-move-subtree-down (- (prefix-numeric-value arg))))
8097 (defun org-move-subtree-down (&optional arg)
8098 "Move the current subtree down past ARG headlines of the same level."
8099 (interactive "p")
8100 (setq arg (prefix-numeric-value arg))
8101 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8102 'org-get-last-sibling))
8103 (ins-point (make-marker))
8104 (cnt (abs arg))
8105 (col (current-column))
8106 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8107 ;; Select the tree
8108 (org-back-to-heading)
8109 (setq beg0 (point))
8110 (save-excursion
8111 (setq ne-beg (org-back-over-empty-lines))
8112 (setq beg (point)))
8113 (save-match-data
8114 (save-excursion (outline-end-of-heading)
8115 (setq folded (outline-invisible-p)))
8116 (outline-end-of-subtree))
8117 (outline-next-heading)
8118 (setq ne-end (org-back-over-empty-lines))
8119 (setq end (point))
8120 (goto-char beg0)
8121 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8122 ;; include less whitespace
8123 (save-excursion
8124 (goto-char beg)
8125 (forward-line (- ne-beg ne-end))
8126 (setq beg (point))))
8127 ;; Find insertion point, with error handling
8128 (while (> cnt 0)
8129 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8130 (progn (goto-char beg0)
8131 (user-error "Cannot move past superior level or buffer limit")))
8132 (setq cnt (1- cnt)))
8133 (if (> arg 0)
8134 ;; Moving forward - still need to move over subtree
8135 (progn (org-end-of-subtree t t)
8136 (save-excursion
8137 (org-back-over-empty-lines)
8138 (or (bolp) (newline)))))
8139 (setq ne-ins (org-back-over-empty-lines))
8140 (move-marker ins-point (point))
8141 (setq txt (buffer-substring beg end))
8142 (org-save-markers-in-region beg end)
8143 (delete-region beg end)
8144 (org-remove-empty-overlays-at beg)
8145 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8146 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8147 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8148 (let ((bbb (point)))
8149 (insert-before-markers txt)
8150 (org-reinstall-markers-in-region bbb)
8151 (move-marker ins-point bbb))
8152 (or (bolp) (insert "\n"))
8153 (setq ins-end (point))
8154 (goto-char ins-point)
8155 (org-skip-whitespace)
8156 (when (and (< arg 0)
8157 (org-first-sibling-p)
8158 (> ne-ins ne-beg))
8159 ;; Move whitespace back to beginning
8160 (save-excursion
8161 (goto-char ins-end)
8162 (let ((kill-whole-line t))
8163 (kill-line (- ne-ins ne-beg)) (point)))
8164 (insert (make-string (- ne-ins ne-beg) ?\n)))
8165 (move-marker ins-point nil)
8166 (if folded
8167 (hide-subtree)
8168 (org-show-entry)
8169 (show-children)
8170 (org-cycle-hide-drawers 'children))
8171 (org-clean-visibility-after-subtree-move)
8172 ;; move back to the initial column we were at
8173 (move-to-column col)))
8175 (defvar org-subtree-clip ""
8176 "Clipboard for cut and paste of subtrees.
8177 This is actually only a copy of the kill, because we use the normal kill
8178 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8180 (defvar org-subtree-clip-folded nil
8181 "Was the last copied subtree folded?
8182 This is used to fold the tree back after pasting.")
8184 (defun org-cut-subtree (&optional n)
8185 "Cut the current subtree into the clipboard.
8186 With prefix arg N, cut this many sequential subtrees.
8187 This is a short-hand for marking the subtree and then cutting it."
8188 (interactive "p")
8189 (org-copy-subtree n 'cut))
8191 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8192 "Copy the current subtree it in the clipboard.
8193 With prefix arg N, copy this many sequential subtrees.
8194 This is a short-hand for marking the subtree and then copying it.
8195 If CUT is non-nil, actually cut the subtree.
8196 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8197 of some markers in the region, even if CUT is non-nil. This is
8198 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8199 (interactive "p")
8200 (let (beg end folded (beg0 (point)))
8201 (if (org-called-interactively-p 'any)
8202 (org-back-to-heading nil) ; take what looks like a subtree
8203 (org-back-to-heading t)) ; take what is really there
8204 (setq beg (point))
8205 (skip-chars-forward " \t\r\n")
8206 (save-match-data
8207 (if nosubtrees
8208 (outline-next-heading)
8209 (save-excursion (outline-end-of-heading)
8210 (setq folded (outline-invisible-p)))
8211 (condition-case nil
8212 (org-forward-heading-same-level (1- n) t)
8213 (error nil))
8214 (org-end-of-subtree t t)))
8215 (setq end (point))
8216 (goto-char beg0)
8217 (when (> end beg)
8218 (setq org-subtree-clip-folded folded)
8219 (when (or cut force-store-markers)
8220 (org-save-markers-in-region beg end))
8221 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8222 (setq org-subtree-clip (current-kill 0))
8223 (message "%s: Subtree(s) with %d characters"
8224 (if cut "Cut" "Copied")
8225 (length org-subtree-clip)))))
8227 (defun org-paste-subtree (&optional level tree for-yank)
8228 "Paste the clipboard as a subtree, with modification of headline level.
8229 The entire subtree is promoted or demoted in order to match a new headline
8230 level.
8232 If the cursor is at the beginning of a headline, the same level as
8233 that headline is used to paste the tree.
8235 If not, the new level is derived from the *visible* headings
8236 before and after the insertion point, and taken to be the inferior headline
8237 level of the two. So if the previous visible heading is level 3 and the
8238 next is level 4 (or vice versa), level 4 will be used for insertion.
8239 This makes sure that the subtree remains an independent subtree and does
8240 not swallow low level entries.
8242 You can also force a different level, either by using a numeric prefix
8243 argument, or by inserting the heading marker by hand. For example, if the
8244 cursor is after \"*****\", then the tree will be shifted to level 5.
8246 If optional TREE is given, use this text instead of the kill ring.
8248 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8249 move back over whitespace before inserting, and move point to the end of
8250 the inserted text when done."
8251 (interactive "P")
8252 (setq tree (or tree (and kill-ring (current-kill 0))))
8253 (unless (org-kill-is-subtree-p tree)
8254 (user-error "%s"
8255 (substitute-command-keys
8256 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8257 (org-with-limited-levels
8258 (let* ((visp (not (outline-invisible-p)))
8259 (txt tree)
8260 (^re_ "\\(\\*+\\)[ \t]*")
8261 (old-level (if (string-match org-outline-regexp-bol txt)
8262 (- (match-end 0) (match-beginning 0) 1)
8263 -1))
8264 (force-level (cond (level (prefix-numeric-value level))
8265 ((and (looking-at "[ \t]*$")
8266 (string-match
8267 "^\\*+$" (buffer-substring
8268 (point-at-bol) (point))))
8269 (- (match-end 1) (match-beginning 1)))
8270 ((and (bolp)
8271 (looking-at org-outline-regexp))
8272 (- (match-end 0) (point) 1))))
8273 (previous-level (save-excursion
8274 (condition-case nil
8275 (progn
8276 (outline-previous-visible-heading 1)
8277 (if (looking-at ^re_)
8278 (- (match-end 0) (match-beginning 0) 1)
8280 (error 1))))
8281 (next-level (save-excursion
8282 (condition-case nil
8283 (progn
8284 (or (looking-at org-outline-regexp)
8285 (outline-next-visible-heading 1))
8286 (if (looking-at ^re_)
8287 (- (match-end 0) (match-beginning 0) 1)
8289 (error 1))))
8290 (new-level (or force-level (max previous-level next-level)))
8291 (shift (if (or (= old-level -1)
8292 (= new-level -1)
8293 (= old-level new-level))
8295 (- new-level old-level)))
8296 (delta (if (> shift 0) -1 1))
8297 (func (if (> shift 0) 'org-demote 'org-promote))
8298 (org-odd-levels-only nil)
8299 beg end newend)
8300 ;; Remove the forced level indicator
8301 (if force-level
8302 (delete-region (point-at-bol) (point)))
8303 ;; Paste
8304 (beginning-of-line (if (bolp) 1 2))
8305 (setq beg (point))
8306 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8307 (insert-before-markers txt)
8308 (unless (string-match "\n\\'" txt) (insert "\n"))
8309 (setq newend (point))
8310 (org-reinstall-markers-in-region beg)
8311 (setq end (point))
8312 (goto-char beg)
8313 (skip-chars-forward " \t\n\r")
8314 (setq beg (point))
8315 (if (and (outline-invisible-p) visp)
8316 (save-excursion (outline-show-heading)))
8317 ;; Shift if necessary
8318 (unless (= shift 0)
8319 (save-restriction
8320 (narrow-to-region beg end)
8321 (while (not (= shift 0))
8322 (org-map-region func (point-min) (point-max))
8323 (setq shift (+ delta shift)))
8324 (goto-char (point-min))
8325 (setq newend (point-max))))
8326 (when (or (org-called-interactively-p 'interactive) for-yank)
8327 (message "Clipboard pasted as level %d subtree" new-level))
8328 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8329 kill-ring
8330 (eq org-subtree-clip (current-kill 0))
8331 org-subtree-clip-folded)
8332 ;; The tree was folded before it was killed/copied
8333 (hide-subtree))
8334 (and for-yank (goto-char newend)))))
8336 (defun org-kill-is-subtree-p (&optional txt)
8337 "Check if the current kill is an outline subtree, or a set of trees.
8338 Returns nil if kill does not start with a headline, or if the first
8339 headline level is not the largest headline level in the tree.
8340 So this will actually accept several entries of equal levels as well,
8341 which is OK for `org-paste-subtree'.
8342 If optional TXT is given, check this string instead of the current kill."
8343 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8344 (re (org-get-limited-outline-regexp))
8345 (^re (concat "^" re))
8346 (start-level (and kill
8347 (string-match
8348 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8349 kill)
8350 (- (match-end 2) (match-beginning 2) 1)))
8351 (start (1+ (or (match-beginning 2) -1))))
8352 (if (not start-level)
8353 (progn
8354 nil) ;; does not even start with a heading
8355 (catch 'exit
8356 (while (setq start (string-match ^re kill (1+ start)))
8357 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8358 (throw 'exit nil)))
8359 t))))
8361 (defvar org-markers-to-move nil
8362 "Markers that should be moved with a cut-and-paste operation.
8363 Those markers are stored together with their positions relative to
8364 the start of the region.")
8366 (defun org-save-markers-in-region (beg end)
8367 "Check markers in region.
8368 If these markers are between BEG and END, record their position relative
8369 to BEG, so that after moving the block of text, we can put the markers back
8370 into place.
8371 This function gets called just before an entry or tree gets cut from the
8372 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8373 called immediately, to move the markers with the entries."
8374 (setq org-markers-to-move nil)
8375 (when (featurep 'org-clock)
8376 (org-clock-save-markers-for-cut-and-paste beg end))
8377 (when (featurep 'org-agenda)
8378 (org-agenda-save-markers-for-cut-and-paste beg end)))
8380 (defun org-check-and-save-marker (marker beg end)
8381 "Check if MARKER is between BEG and END.
8382 If yes, remember the marker and the distance to BEG."
8383 (when (and (marker-buffer marker)
8384 (equal (marker-buffer marker) (current-buffer)))
8385 (if (and (>= marker beg) (< marker end))
8386 (push (cons marker (- marker beg)) org-markers-to-move))))
8388 (defun org-reinstall-markers-in-region (beg)
8389 "Move all remembered markers to their position relative to BEG."
8390 (mapc (lambda (x)
8391 (move-marker (car x) (+ beg (cdr x))))
8392 org-markers-to-move)
8393 (setq org-markers-to-move nil))
8395 (defun org-narrow-to-subtree ()
8396 "Narrow buffer to the current subtree."
8397 (interactive)
8398 (save-excursion
8399 (save-match-data
8400 (org-with-limited-levels
8401 (narrow-to-region
8402 (progn (org-back-to-heading t) (point))
8403 (progn (org-end-of-subtree t t)
8404 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8405 (point)))))))
8407 (defun org-narrow-to-block ()
8408 "Narrow buffer to the current block."
8409 (interactive)
8410 (let* ((case-fold-search t)
8411 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8412 "^[ \t]*#\\+end_.*")))
8413 (if blockp
8414 (narrow-to-region (car blockp) (cdr blockp))
8415 (user-error "Not in a block"))))
8417 (eval-when-compile
8418 (defvar org-property-drawer-re))
8420 (defvar org-property-start-re) ;; defined below
8421 (defun org-clone-subtree-with-time-shift (n &optional shift)
8422 "Clone the task (subtree) at point N times.
8423 The clones will be inserted as siblings.
8425 In interactive use, the user will be prompted for the number of
8426 clones to be produced. If the entry has a timestamp, the user
8427 will also be prompted for a time shift, which may be a repeater
8428 as used in time stamps, for example `+3d'. To disable this,
8429 you can call the function with a universal prefix argument.
8431 When a valid repeater is given and the entry contains any time
8432 stamps, the clones will become a sequence in time, with time
8433 stamps in the subtree shifted for each clone produced. If SHIFT
8434 is nil or the empty string, time stamps will be left alone. The
8435 ID property of the original subtree is removed.
8437 If the original subtree did contain time stamps with a repeater,
8438 the following will happen:
8439 - the repeater will be removed in each clone
8440 - an additional clone will be produced, with the current, unshifted
8441 date(s) in the entry.
8442 - the original entry will be placed *after* all the clones, with
8443 repeater intact.
8444 - the start days in the repeater in the original entry will be shifted
8445 to past the last clone.
8446 In this way you can spell out a number of instances of a repeating task,
8447 and still retain the repeater to cover future instances of the task."
8448 (interactive "nNumber of clones to produce: ")
8449 (let ((shift
8450 (or shift
8451 (if (and (not (equal current-prefix-arg '(4)))
8452 (save-excursion
8453 (re-search-forward org-ts-regexp-both
8454 (save-excursion
8455 (org-end-of-subtree t)
8456 (point)) t)))
8457 (read-from-minibuffer
8458 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8459 ""))) ;; No time shift
8460 (n-no-remove -1)
8461 (drawer-re org-drawer-regexp)
8462 beg end template task idprop
8463 shift-n shift-what doshift nmin nmax)
8464 (if (not (and (integerp n) (> n 0)))
8465 (error "Invalid number of replications %s" n))
8466 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8467 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8468 shift)))
8469 (error "Invalid shift specification %s" shift))
8470 (when doshift
8471 (setq shift-n (string-to-number (match-string 1 shift))
8472 shift-what (cdr (assoc (match-string 2 shift)
8473 '(("d" . day) ("w" . week)
8474 ("m" . month) ("y" . year))))))
8475 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8476 (setq nmin 1 nmax n)
8477 (org-back-to-heading t)
8478 (setq beg (point))
8479 (setq idprop (org-entry-get nil "ID"))
8480 (org-end-of-subtree t t)
8481 (or (bolp) (insert "\n"))
8482 (setq end (point))
8483 (setq template (buffer-substring beg end))
8484 (when (and doshift
8485 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8486 (delete-region beg end)
8487 (setq end beg)
8488 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8489 (goto-char end)
8490 (loop for n from nmin to nmax do
8491 ;; prepare clone
8492 (with-temp-buffer
8493 (insert template)
8494 (org-mode)
8495 (goto-char (point-min))
8496 (org-show-subtree)
8497 (and idprop (if org-clone-delete-id
8498 (org-entry-delete nil "ID")
8499 (org-id-get-create t)))
8500 (unless (= n 0)
8501 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8502 (kill-whole-line))
8503 (goto-char (point-min))
8504 (while (re-search-forward drawer-re nil t)
8505 (mapc (lambda (d)
8506 (org-remove-empty-drawer-at d (point))) org-drawers)))
8507 (goto-char (point-min))
8508 (when doshift
8509 (while (re-search-forward org-ts-regexp-both nil t)
8510 (org-timestamp-change (* n shift-n) shift-what))
8511 (unless (= n n-no-remove)
8512 (goto-char (point-min))
8513 (while (re-search-forward org-ts-regexp nil t)
8514 (save-excursion
8515 (goto-char (match-beginning 0))
8516 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8517 (delete-region (match-beginning 1) (match-end 1)))))))
8518 (setq task (buffer-string)))
8519 (insert task))
8520 (goto-char beg)))
8522 ;;; Outline Sorting
8524 (defun org-sort (with-case)
8525 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8526 Optional argument WITH-CASE means sort case-sensitively."
8527 (interactive "P")
8528 (cond
8529 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8530 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8532 (org-call-with-arg 'org-sort-entries with-case))))
8534 (defun org-sort-remove-invisible (s)
8535 "Remove invisible links from string S."
8536 (remove-text-properties 0 (length s) org-rm-props s)
8537 (while (string-match org-bracket-link-regexp s)
8538 (setq s (replace-match (if (match-end 2)
8539 (match-string 3 s)
8540 (match-string 1 s)) t t s)))
8541 (let ((st (format " %s " s)))
8542 (while (string-match org-emph-re st)
8543 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8544 (setq s (substring st 1 -1)))
8547 (defvar org-priority-regexp) ; defined later in the file
8549 (defvar org-after-sorting-entries-or-items-hook nil
8550 "Hook that is run after a bunch of entries or items have been sorted.
8551 When children are sorted, the cursor is in the parent line when this
8552 hook gets called. When a region or a plain list is sorted, the cursor
8553 will be in the first entry of the sorted region/list.")
8555 (defun org-sort-entries
8556 (&optional with-case sorting-type getkey-func compare-func property)
8557 "Sort entries on a certain level of an outline tree.
8558 If there is an active region, the entries in the region are sorted.
8559 Else, if the cursor is before the first entry, sort the top-level items.
8560 Else, the children of the entry at point are sorted.
8562 Sorting can be alphabetically, numerically, by date/time as given by
8563 a time stamp, by a property, by priority order, or by a custom function.
8565 The command prompts for the sorting type unless it has been given to the
8566 function through the SORTING-TYPE argument, which needs to be a character,
8567 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8568 precise meaning of each character:
8570 n Numerically, by converting the beginning of the entry/item to a number.
8571 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8572 o By order of TODO keywords.
8573 t By date/time, either the first active time stamp in the entry, or, if
8574 none exist, by the first inactive one.
8575 s By the scheduled date/time.
8576 d By deadline date/time.
8577 c By creation time, which is assumed to be the first inactive time stamp
8578 at the beginning of a line.
8579 p By priority according to the cookie.
8580 r By the value of a property.
8582 Capital letters will reverse the sort order.
8584 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8585 called with point at the beginning of the record. It must return either
8586 a string or a number that should serve as the sorting key for that record.
8588 Comparing entries ignores case by default. However, with an optional argument
8589 WITH-CASE, the sorting considers case as well.
8591 Sorting is done against the visible part of the headlines, it ignores hidden
8592 links."
8593 (interactive "P")
8594 (let ((case-func (if with-case 'identity 'downcase))
8595 (cmstr
8596 ;; The clock marker is lost when using `sort-subr', let's
8597 ;; store the clocking string.
8598 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8599 (save-excursion
8600 (goto-char org-clock-marker)
8601 (looking-back "^.*") (match-string-no-properties 0))))
8602 start beg end stars re re2
8603 txt what tmp)
8604 ;; Find beginning and end of region to sort
8605 (cond
8606 ((org-region-active-p)
8607 ;; we will sort the region
8608 (setq end (region-end)
8609 what "region")
8610 (goto-char (region-beginning))
8611 (if (not (org-at-heading-p)) (outline-next-heading))
8612 (setq start (point)))
8613 ((or (org-at-heading-p)
8614 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8615 ;; we will sort the children of the current headline
8616 (org-back-to-heading)
8617 (setq start (point)
8618 end (progn (org-end-of-subtree t t)
8619 (or (bolp) (insert "\n"))
8620 (org-back-over-empty-lines)
8621 (point))
8622 what "children")
8623 (goto-char start)
8624 (show-subtree)
8625 (outline-next-heading))
8627 ;; we will sort the top-level entries in this file
8628 (goto-char (point-min))
8629 (or (org-at-heading-p) (outline-next-heading))
8630 (setq start (point))
8631 (goto-char (point-max))
8632 (beginning-of-line 1)
8633 (when (looking-at ".*?\\S-")
8634 ;; File ends in a non-white line
8635 (end-of-line 1)
8636 (insert "\n"))
8637 (setq end (point-max))
8638 (setq what "top-level")
8639 (goto-char start)
8640 (show-all)))
8642 (setq beg (point))
8643 (if (>= beg end) (user-error "Nothing to sort"))
8645 (looking-at "\\(\\*+\\)")
8646 (setq stars (match-string 1)
8647 re (concat "^" (regexp-quote stars) " +")
8648 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8649 txt (buffer-substring beg end))
8650 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8651 (if (and (not (equal stars "*")) (string-match re2 txt))
8652 (user-error "Region to sort contains a level above the first entry"))
8654 (unless sorting-type
8655 (message
8656 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8657 [t]ime [s]cheduled [d]eadline [c]reated
8658 A/N/P/R/O/F/T/S/D/C means reversed:"
8659 what)
8660 (setq sorting-type (read-char-exclusive))
8662 (unless getkey-func
8663 (and (= (downcase sorting-type) ?f)
8664 (setq getkey-func
8665 (org-icompleting-read "Sort using function: "
8666 obarray 'fboundp t nil nil))
8667 (setq getkey-func (intern getkey-func))))
8669 (and (= (downcase sorting-type) ?r)
8670 (not property)
8671 (setq property
8672 (org-icompleting-read "Property: "
8673 (mapcar 'list (org-buffer-property-keys t))
8674 nil t))))
8676 (message "Sorting entries...")
8678 (save-restriction
8679 (narrow-to-region start end)
8680 (let ((dcst (downcase sorting-type))
8681 (case-fold-search nil)
8682 (now (current-time)))
8683 (sort-subr
8684 (/= dcst sorting-type)
8685 ;; This function moves to the beginning character of the "record" to
8686 ;; be sorted.
8687 (lambda nil
8688 (if (re-search-forward re nil t)
8689 (goto-char (match-beginning 0))
8690 (goto-char (point-max))))
8691 ;; This function moves to the last character of the "record" being
8692 ;; sorted.
8693 (lambda nil
8694 (save-match-data
8695 (condition-case nil
8696 (outline-forward-same-level 1)
8697 (error
8698 (goto-char (point-max))))))
8699 ;; This function returns the value that gets sorted against.
8700 (lambda nil
8701 (cond
8702 ((= dcst ?n)
8703 (if (looking-at org-complex-heading-regexp)
8704 (string-to-number (org-sort-remove-invisible (match-string 4)))
8705 nil))
8706 ((= dcst ?a)
8707 (if (looking-at org-complex-heading-regexp)
8708 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8709 nil))
8710 ((= dcst ?t)
8711 (let ((end (save-excursion (outline-next-heading) (point))))
8712 (if (or (re-search-forward org-ts-regexp end t)
8713 (re-search-forward org-ts-regexp-both end t))
8714 (org-time-string-to-seconds (match-string 0))
8715 (org-float-time now))))
8716 ((= dcst ?c)
8717 (let ((end (save-excursion (outline-next-heading) (point))))
8718 (if (re-search-forward
8719 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8720 end t)
8721 (org-time-string-to-seconds (match-string 0))
8722 (org-float-time now))))
8723 ((= dcst ?s)
8724 (let ((end (save-excursion (outline-next-heading) (point))))
8725 (if (re-search-forward org-scheduled-time-regexp end t)
8726 (org-time-string-to-seconds (match-string 1))
8727 (org-float-time now))))
8728 ((= dcst ?d)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (re-search-forward org-deadline-time-regexp end t)
8731 (org-time-string-to-seconds (match-string 1))
8732 (org-float-time now))))
8733 ((= dcst ?p)
8734 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8735 (string-to-char (match-string 2))
8736 org-default-priority))
8737 ((= dcst ?r)
8738 (or (org-entry-get nil property) ""))
8739 ((= dcst ?o)
8740 (if (looking-at org-complex-heading-regexp)
8741 (- 9999 (length (member (match-string 2)
8742 org-todo-keywords-1)))))
8743 ((= dcst ?f)
8744 (if getkey-func
8745 (progn
8746 (setq tmp (funcall getkey-func))
8747 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8748 tmp)
8749 (error "Invalid key function `%s'" getkey-func)))
8750 (t (error "Invalid sorting type `%c'" sorting-type))))
8752 (cond
8753 ((= dcst ?a) 'string<)
8754 ((= dcst ?f) compare-func)
8755 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8756 (run-hooks 'org-after-sorting-entries-or-items-hook)
8757 ;; Reset the clock marker if needed
8758 (when cmstr
8759 (save-excursion
8760 (goto-char start)
8761 (search-forward cmstr nil t)
8762 (move-marker org-clock-marker (point))))
8763 (message "Sorting entries...done")))
8765 (defun org-do-sort (table what &optional with-case sorting-type)
8766 "Sort TABLE of WHAT according to SORTING-TYPE.
8767 The user will be prompted for the SORTING-TYPE if the call to this
8768 function does not specify it. WHAT is only for the prompt, to indicate
8769 what is being sorted. The sorting key will be extracted from
8770 the car of the elements of the table.
8771 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8772 (unless sorting-type
8773 (message
8774 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8775 what)
8776 (setq sorting-type (read-char-exclusive)))
8777 (let ((dcst (downcase sorting-type))
8778 extractfun comparefun)
8779 ;; Define the appropriate functions
8780 (cond
8781 ((= dcst ?n)
8782 (setq extractfun 'string-to-number
8783 comparefun (if (= dcst sorting-type) '< '>)))
8784 ((= dcst ?a)
8785 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8786 (lambda(x) (downcase (org-sort-remove-invisible x))))
8787 comparefun (if (= dcst sorting-type)
8788 'string<
8789 (lambda (a b) (and (not (string< a b))
8790 (not (string= a b)))))))
8791 ((= dcst ?t)
8792 (setq extractfun
8793 (lambda (x)
8794 (if (or (string-match org-ts-regexp x)
8795 (string-match org-ts-regexp-both x))
8796 (org-float-time
8797 (org-time-string-to-time (match-string 0 x)))
8799 comparefun (if (= dcst sorting-type) '< '>)))
8800 (t (error "Invalid sorting type `%c'" sorting-type)))
8802 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8803 table)
8804 (lambda (a b) (funcall comparefun (car a) (car b))))))
8807 ;;; The orgstruct minor mode
8809 ;; Define a minor mode which can be used in other modes in order to
8810 ;; integrate the org-mode structure editing commands.
8812 ;; This is really a hack, because the org-mode structure commands use
8813 ;; keys which normally belong to the major mode. Here is how it
8814 ;; works: The minor mode defines all the keys necessary to operate the
8815 ;; structure commands, but wraps the commands into a function which
8816 ;; tests if the cursor is currently at a headline or a plain list
8817 ;; item. If that is the case, the structure command is used,
8818 ;; temporarily setting many Org-mode variables like regular
8819 ;; expressions for filling etc. However, when any of those keys is
8820 ;; used at a different location, function uses `key-binding' to look
8821 ;; up if the key has an associated command in another currently active
8822 ;; keymap (minor modes, major mode, global), and executes that
8823 ;; command. There might be problems if any of the keys is otherwise
8824 ;; used as a prefix key.
8826 (defcustom orgstruct-heading-prefix-regexp nil
8827 "Regexp that matches the custom prefix of Org headlines in
8828 orgstruct(++)-mode."
8829 :group 'org
8830 :version "24.4"
8831 :package-version '(Org . "8.0")
8832 :type 'string)
8833 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8835 (defcustom orgstruct-setup-hook nil
8836 "Hook run after orgstruct-mode-map is filled."
8837 :group 'org
8838 :version "24.4"
8839 :package-version '(Org . "8.0")
8840 :type 'hook)
8842 (defvar orgstruct-initialized nil)
8844 (defvar org-local-vars nil
8845 "List of local variables, for use by `orgstruct-mode'.")
8847 ;;;###autoload
8848 (define-minor-mode orgstruct-mode
8849 "Toggle the minor mode `orgstruct-mode'.
8850 This mode is for using Org-mode structure commands in other
8851 modes. The following keys behave as if Org-mode were active, if
8852 the cursor is on a headline, or on a plain list item (both as
8853 defined by Org-mode)."
8854 nil " OrgStruct" (make-sparse-keymap)
8855 (funcall (if orgstruct-mode
8856 'add-to-invisibility-spec
8857 'remove-from-invisibility-spec)
8858 '(outline . t))
8859 (when orgstruct-mode
8860 (org-load-modules-maybe)
8861 (unless orgstruct-initialized
8862 (orgstruct-setup)
8863 (setq orgstruct-initialized t))))
8865 ;;;###autoload
8866 (defun turn-on-orgstruct ()
8867 "Unconditionally turn on `orgstruct-mode'."
8868 (orgstruct-mode 1))
8870 (defvar org-fb-vars nil)
8871 (make-variable-buffer-local 'org-fb-vars)
8872 (defun orgstruct++-mode (&optional arg)
8873 "Toggle `orgstruct-mode', the enhanced version of it.
8874 In addition to setting orgstruct-mode, this also exports all
8875 indentation and autofilling variables from org-mode into the
8876 buffer. It will also recognize item context in multiline items."
8877 (interactive "P")
8878 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8879 (if (< arg 1)
8880 (progn (orgstruct-mode -1)
8881 (mapc (lambda(v)
8882 (org-set-local (car v)
8883 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8884 org-fb-vars))
8885 (orgstruct-mode 1)
8886 (setq org-fb-vars nil)
8887 (unless org-local-vars
8888 (setq org-local-vars (org-get-local-variables)))
8889 (let (var val)
8890 (mapc
8891 (lambda (x)
8892 (when (string-match
8893 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8894 (symbol-name (car x)))
8895 (setq var (car x) val (nth 1 x))
8896 (push (list var `(quote ,(eval var))) org-fb-vars)
8897 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8898 org-local-vars)
8899 (org-set-local 'orgstruct-is-++ t))))
8901 (defvar orgstruct-is-++ nil
8902 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8903 (make-variable-buffer-local 'orgstruct-is-++)
8905 ;;;###autoload
8906 (defun turn-on-orgstruct++ ()
8907 "Unconditionally turn on `orgstruct++-mode'."
8908 (orgstruct++-mode 1))
8910 (defun orgstruct-error ()
8911 "Error when there is no default binding for a structure key."
8912 (interactive)
8913 (funcall (if (fboundp 'user-error)
8914 'user-error
8915 'error)
8916 "This key has no function outside structure elements"))
8918 (defun orgstruct-setup ()
8919 "Setup orgstruct keymap."
8920 (dolist (cell '((org-demote . t)
8921 (org-metaleft . t)
8922 (org-metaright . t)
8923 (org-promote . t)
8924 (org-shiftmetaleft . t)
8925 (org-shiftmetaright . t)
8926 org-backward-element
8927 org-backward-heading-same-level
8928 org-ctrl-c-ret
8929 org-ctrl-c-minus
8930 org-ctrl-c-star
8931 org-cycle
8932 org-forward-heading-same-level
8933 org-insert-heading
8934 org-insert-heading-respect-content
8935 org-kill-note-or-show-branches
8936 org-mark-subtree
8937 org-meta-return
8938 org-metadown
8939 org-metaup
8940 org-narrow-to-subtree
8941 org-promote-subtree
8942 org-reveal
8943 org-shiftdown
8944 org-shiftleft
8945 org-shiftmetadown
8946 org-shiftmetaup
8947 org-shiftright
8948 org-shifttab
8949 org-shifttab
8950 org-shiftup
8951 org-show-subtree
8952 org-sort
8953 org-up-element
8954 outline-demote
8955 outline-next-visible-heading
8956 outline-previous-visible-heading
8957 outline-promote
8958 outline-up-heading
8959 show-children))
8960 (let ((f (or (car-safe cell) cell))
8961 (disable-when-heading-prefix (cdr-safe cell)))
8962 (when (fboundp f)
8963 (let ((new-bindings))
8964 (dolist (binding (nconc (where-is-internal f org-mode-map)
8965 (where-is-internal f outline-mode-map)))
8966 (push binding new-bindings)
8967 ;; TODO use local-function-key-map
8968 (dolist (rep '(("<tab>" . "TAB")
8969 ("<return>" . "RET")
8970 ("<escape>" . "ESC")
8971 ("<delete>" . "DEL")))
8972 (setq binding (read-kbd-macro
8973 (let ((case-fold-search))
8974 (replace-regexp-in-string
8975 (regexp-quote (cdr rep))
8976 (car rep)
8977 (key-description binding)))))
8978 (pushnew binding new-bindings :test 'equal)))
8979 (dolist (binding new-bindings)
8980 (let ((key (lookup-key orgstruct-mode-map binding)))
8981 (when (or (not key) (numberp key))
8982 (condition-case nil
8983 (org-defkey orgstruct-mode-map
8984 binding
8985 (orgstruct-make-binding f binding disable-when-heading-prefix))
8986 (error nil)))))))))
8987 (run-hooks 'orgstruct-setup-hook))
8989 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8990 "Create a function for binding in the structure minor mode.
8991 FUN is the command to call inside a table. KEY is the key that
8992 should be checked in for a command to execute outside of tables.
8993 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8994 if `orgstruct-heading-prefix-regexp' is non-nil."
8995 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8996 (let ((nname name)
8997 (i 0))
8998 (while (fboundp (intern nname))
8999 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9000 (setq name (intern nname)))
9001 (eval
9002 (let ((bindings '((org-heading-regexp
9003 (concat "^"
9004 orgstruct-heading-prefix-regexp
9005 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9006 (org-outline-regexp
9007 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9008 (org-outline-regexp-bol
9009 (concat "^" org-outline-regexp))
9010 (outline-regexp org-outline-regexp)
9011 (outline-heading-end-regexp "\n")
9012 (outline-level 'org-outline-level)
9013 (outline-heading-alist))))
9014 `(defun ,name (arg)
9015 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9016 "Outside of structure, run the binding of `"
9017 (key-description key) "'."
9018 (when disable-when-heading-prefix
9019 (concat
9020 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9021 "back to the default binding due to limitations of Org's implementation of\n"
9022 "`" (symbol-name fun) "'.")))
9023 (interactive "p")
9024 (let* ((disable
9025 ,(when disable-when-heading-prefix
9026 '(and orgstruct-heading-prefix-regexp
9027 (not (string= orgstruct-heading-prefix-regexp "")))))
9028 (fallback
9029 (or disable
9030 (not
9031 (let* ,bindings
9032 (org-context-p 'headline 'item
9033 ,(when (memq fun
9034 '(org-insert-heading
9035 org-insert-heading-respect-content
9036 org-meta-return))
9037 '(when orgstruct-is-++
9038 'item-body))))))))
9039 (if fallback
9040 (let* ((orgstruct-mode)
9041 (binding
9042 (loop with key = ,key
9043 for rep in
9044 '(nil
9045 ("<\\([^>]*\\)tab>" . "\\1TAB")
9046 ("<\\([^>]*\\)return>" . "\\1RET")
9047 ("<\\([^>]*\\)escape>" . "\\1ESC")
9048 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9050 (when rep
9051 (setq key (read-kbd-macro
9052 (let ((case-fold-search))
9053 (replace-regexp-in-string
9054 (car rep)
9055 (cdr rep)
9056 (key-description key))))))
9057 thereis (key-binding key))))
9058 (if (keymapp binding)
9059 (set-temporary-overlay-map binding)
9060 (let ((func (or binding
9061 (unless disable
9062 'orgstruct-error))))
9063 (when func
9064 (call-interactively func)))))
9065 (org-run-like-in-org-mode
9066 (lambda ()
9067 (interactive)
9068 (let* ,bindings
9069 (call-interactively ',fun)))))))))
9070 name))
9072 (defun org-contextualize-keys (alist contexts)
9073 "Return valid elements in ALIST depending on CONTEXTS.
9075 `org-agenda-custom-commands' or `org-capture-templates' are the
9076 values used for ALIST, and `org-agenda-custom-commands-contexts'
9077 or `org-capture-templates-contexts' are the associated contexts
9078 definitions."
9079 (let ((contexts
9080 ;; normalize contexts
9081 (mapcar
9082 (lambda(c) (cond ((listp (cadr c))
9083 (list (car c) (car c) (cadr c)))
9084 ((string= "" (cadr c))
9085 (list (car c) (car c) (caddr c)))
9086 (t c))) contexts))
9087 (a alist) c r s)
9088 ;; loop over all commands or templates
9089 (while (setq c (pop a))
9090 (let (vrules repl)
9091 (cond
9092 ((not (assoc (car c) contexts))
9093 (push c r))
9094 ((and (assoc (car c) contexts)
9095 (setq vrules (org-contextualize-validate-key
9096 (car c) contexts)))
9097 (mapc (lambda (vr)
9098 (when (not (equal (car vr) (cadr vr)))
9099 (setq repl vr))) vrules)
9100 (if (not repl) (push c r)
9101 (push (cadr repl) s)
9102 (push
9103 (cons (car c)
9104 (cdr (or (assoc (cadr repl) alist)
9105 (error "Undefined key `%s' as contextual replacement for `%s'"
9106 (cadr repl) (car c)))))
9107 r))))))
9108 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9109 (delq
9111 (delete-dups
9112 (mapcar (lambda (x)
9113 (let ((tpl (car x)))
9114 (when (not (delq
9116 (mapcar (lambda(y)
9117 (equal y tpl)) s))) x)))
9118 (reverse r))))))
9120 (defun org-contextualize-validate-key (key contexts)
9121 "Check CONTEXTS for agenda or capture KEY."
9122 (let (r rr res)
9123 (while (setq r (pop contexts))
9124 (mapc
9125 (lambda (rr)
9126 (when
9127 (and (equal key (car r))
9128 (if (functionp rr) (funcall rr)
9129 (or (and (eq (car rr) 'in-file)
9130 (buffer-file-name)
9131 (string-match (cdr rr) (buffer-file-name)))
9132 (and (eq (car rr) 'in-mode)
9133 (string-match (cdr rr) (symbol-name major-mode)))
9134 (and (eq (car rr) 'in-buffer)
9135 (string-match (cdr rr) (buffer-name)))
9136 (when (and (eq (car rr) 'not-in-file)
9137 (buffer-file-name))
9138 (not (string-match (cdr rr) (buffer-file-name))))
9139 (when (eq (car rr) 'not-in-mode)
9140 (not (string-match (cdr rr) (symbol-name major-mode))))
9141 (when (eq (car rr) 'not-in-buffer)
9142 (not (string-match (cdr rr) (buffer-name)))))))
9143 (push r res)))
9144 (car (last r))))
9145 (delete-dups (delq nil res))))
9147 (defun org-context-p (&rest contexts)
9148 "Check if local context is any of CONTEXTS.
9149 Possible values in the list of contexts are `table', `headline', and `item'."
9150 (let ((pos (point)))
9151 (goto-char (point-at-bol))
9152 (prog1 (or (and (memq 'table contexts)
9153 (looking-at "[ \t]*|"))
9154 (and (memq 'headline contexts)
9155 (looking-at org-outline-regexp))
9156 (and (memq 'item contexts)
9157 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9158 (and (memq 'item-body contexts)
9159 (org-in-item-p)))
9160 (goto-char pos))))
9162 (defun org-get-local-variables ()
9163 "Return a list of all local variables in an Org mode buffer."
9164 (let (varlist)
9165 (with-current-buffer (get-buffer-create "*Org tmp*")
9166 (erase-buffer)
9167 (org-mode)
9168 (setq varlist (buffer-local-variables)))
9169 (kill-buffer "*Org tmp*")
9170 (delq nil
9171 (mapcar
9172 (lambda (x)
9173 (setq x
9174 (if (symbolp x)
9175 (list x)
9176 (list (car x) (cdr x))))
9177 (if (and (not (get (car x) 'org-state))
9178 (string-match
9179 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9180 (symbol-name (car x))))
9181 x nil))
9182 varlist))))
9184 (defun org-clone-local-variables (from-buffer &optional regexp)
9185 "Clone local variables from FROM-BUFFER.
9186 Optional argument REGEXP selects variables to clone."
9187 (mapc
9188 (lambda (pair)
9189 (and (symbolp (car pair))
9190 (or (null regexp)
9191 (string-match regexp (symbol-name (car pair))))
9192 (set (make-local-variable (car pair))
9193 (cdr pair))))
9194 (buffer-local-variables from-buffer)))
9196 ;;;###autoload
9197 (defun org-run-like-in-org-mode (cmd)
9198 "Run a command, pretending that the current buffer is in Org-mode.
9199 This will temporarily bind local variables that are typically bound in
9200 Org-mode to the values they have in Org-mode, and then interactively
9201 call CMD."
9202 (org-load-modules-maybe)
9203 (unless org-local-vars
9204 (setq org-local-vars (org-get-local-variables)))
9205 (let (binds)
9206 (dolist (var org-local-vars)
9207 (when (or (not (boundp (car var)))
9208 (eq (symbol-value (car var))
9209 (default-value (car var))))
9210 (push (list (car var) `(quote ,(cadr var))) binds)))
9211 (eval `(let ,binds
9212 (call-interactively (quote ,cmd))))))
9214 ;;;; Archiving
9216 (defun org-get-category (&optional pos force-refresh)
9217 "Get the category applying to position POS."
9218 (save-match-data
9219 (if force-refresh (org-refresh-category-properties))
9220 (let ((pos (or pos (point))))
9221 (or (get-text-property pos 'org-category)
9222 (progn (org-refresh-category-properties)
9223 (get-text-property pos 'org-category))))))
9225 (defun org-refresh-category-properties ()
9226 "Refresh category text properties in the buffer."
9227 (let ((case-fold-search t)
9228 (inhibit-read-only t)
9229 (def-cat (cond
9230 ((null org-category)
9231 (if buffer-file-name
9232 (file-name-sans-extension
9233 (file-name-nondirectory buffer-file-name))
9234 "???"))
9235 ((symbolp org-category) (symbol-name org-category))
9236 (t org-category)))
9237 beg end cat pos optionp)
9238 (org-with-silent-modifications
9239 (save-excursion
9240 (save-restriction
9241 (widen)
9242 (goto-char (point-min))
9243 (put-text-property (point) (point-max) 'org-category def-cat)
9244 (while (re-search-forward
9245 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9246 (setq pos (match-end 0)
9247 optionp (equal (char-after (match-beginning 0)) ?#)
9248 cat (org-trim (match-string 2)))
9249 (if optionp
9250 (setq beg (point-at-bol) end (point-max))
9251 (org-back-to-heading t)
9252 (setq beg (point) end (org-end-of-subtree t t)))
9253 (put-text-property beg end 'org-category cat)
9254 (put-text-property beg end 'org-category-position beg)
9255 (goto-char pos)))))))
9257 (defun org-refresh-properties (dprop tprop)
9258 "Refresh buffer text properties.
9259 DPROP is the drawer property and TPROP is the corresponding text
9260 property to set."
9261 (let ((case-fold-search t)
9262 (inhibit-read-only t) p)
9263 (org-with-silent-modifications
9264 (save-excursion
9265 (save-restriction
9266 (widen)
9267 (goto-char (point-min))
9268 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9269 (setq p (org-match-string-no-properties 1))
9270 (save-excursion
9271 (org-back-to-heading t)
9272 (put-text-property
9273 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9276 ;;;; Link Stuff
9278 ;;; Link abbreviations
9280 (defun org-link-expand-abbrev (link)
9281 "Apply replacements as defined in `org-link-abbrev-alist'."
9282 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9283 (let* ((key (match-string 1 link))
9284 (as (or (assoc key org-link-abbrev-alist-local)
9285 (assoc key org-link-abbrev-alist)))
9286 (tag (and (match-end 2) (match-string 3 link)))
9287 rpl)
9288 (if (not as)
9289 link
9290 (setq rpl (cdr as))
9291 (cond
9292 ((symbolp rpl) (funcall rpl tag))
9293 ((string-match "%(\\([^)]+\\))" rpl)
9294 (replace-match
9295 (save-match-data
9296 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9297 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9298 ((string-match "%h" rpl)
9299 (replace-match (url-hexify-string (or tag "")) t t rpl))
9300 (t (concat rpl tag)))))
9301 link))
9303 ;;; Storing and inserting links
9305 (defvar org-insert-link-history nil
9306 "Minibuffer history for links inserted with `org-insert-link'.")
9308 (defvar org-stored-links nil
9309 "Contains the links stored with `org-store-link'.")
9311 (defvar org-store-link-plist nil
9312 "Plist with info about the most recently link created with `org-store-link'.")
9314 (defvar org-link-protocols nil
9315 "Link protocols added to Org-mode using `org-add-link-type'.")
9317 (defvar org-store-link-functions nil
9318 "List of functions that are called to create and store a link.
9319 Each function will be called in turn until one returns a non-nil
9320 value. Each function should check if it is responsible for creating
9321 this link (for example by looking at the major mode).
9322 If not, it must exit and return nil.
9323 If yes, it should return a non-nil value after a calling
9324 `org-store-link-props' with a list of properties and values.
9325 Special properties are:
9327 :type The link prefix, like \"http\". This must be given.
9328 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9329 This is obligatory as well.
9330 :description Optional default description for the second pair
9331 of brackets in an Org-mode link. The user can still change
9332 this when inserting this link into an Org-mode buffer.
9334 In addition to these, any additional properties can be specified
9335 and then used in capture templates.")
9337 (defun org-add-link-type (type &optional follow export)
9338 "Add TYPE to the list of `org-link-types'.
9339 Re-compute all regular expressions depending on `org-link-types'
9341 FOLLOW and EXPORT are two functions.
9343 FOLLOW should take the link path as the single argument and do whatever
9344 is necessary to follow the link, for example find a file or display
9345 a mail message.
9347 EXPORT should format the link path for export to one of the export formats.
9348 It should be a function accepting three arguments:
9350 path the path of the link, the text after the prefix (like \"http:\")
9351 desc the description of the link, if any, or a description added by
9352 org-export-normalize-links if there is none
9353 format the export format, a symbol like `html' or `latex' or `ascii'..
9355 The function may use the FORMAT information to return different values
9356 depending on the format. The return value will be put literally into
9357 the exported file. If the return value is nil, this means Org should
9358 do what it normally does with links which do not have EXPORT defined.
9360 Org-mode has a built-in default for exporting links. If you are happy with
9361 this default, there is no need to define an export function for the link
9362 type. For a simple example of an export function, see `org-bbdb.el'."
9363 (add-to-list 'org-link-types type t)
9364 (org-make-link-regexps)
9365 (if (assoc type org-link-protocols)
9366 (setcdr (assoc type org-link-protocols) (list follow export))
9367 (push (list type follow export) org-link-protocols)))
9369 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9370 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9372 ;;;###autoload
9373 (defun org-store-link (arg)
9374 "\\<org-mode-map>Store an org-link to the current location.
9375 This link is added to `org-stored-links' and can later be inserted
9376 into an org-buffer with \\[org-insert-link].
9378 For some link types, a prefix arg is interpreted.
9379 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9380 For file links, arg negates `org-context-in-file-links'.
9382 A double prefix arg force skipping storing functions that are not
9383 part of Org's core.
9385 A triple prefix arg force storing a link for each line in the
9386 active region."
9387 (interactive "P")
9388 (org-load-modules-maybe)
9389 (if (and (equal arg '(64)) (org-region-active-p))
9390 (save-excursion
9391 (let ((end (region-end)))
9392 (goto-char (region-beginning))
9393 (set-mark (point))
9394 (while (< (point-at-eol) end)
9395 (move-end-of-line 1) (activate-mark)
9396 (let (current-prefix-arg)
9397 (call-interactively 'org-store-link))
9398 (move-beginning-of-line 2)
9399 (set-mark (point)))))
9400 (org-with-limited-levels
9401 (setq org-store-link-plist nil)
9402 (let (link cpltxt desc description search
9403 txt custom-id agenda-link sfuns sfunsn)
9404 (cond
9406 ;; Store a link using an external link type
9407 ((and (not (equal arg '(16)))
9408 (setq sfuns
9409 (delq
9410 nil (mapcar (lambda (f)
9411 (let (fs) (if (funcall f) (push f fs))))
9412 org-store-link-functions))
9413 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9414 (or (and (cdr sfuns)
9415 (funcall (intern
9416 (completing-read
9417 "Which function for creating the link? "
9418 sfunsn t (car sfunsn)))))
9419 (funcall (caar sfuns)))
9420 (setq link (plist-get org-store-link-plist :link)
9421 desc (or (plist-get org-store-link-plist
9422 :description) link))))
9424 ;; Store a link from a source code buffer
9425 ((org-src-edit-buffer-p)
9426 (let (label gc)
9427 (while (or (not label)
9428 (save-excursion
9429 (save-restriction
9430 (widen)
9431 (goto-char (point-min))
9432 (re-search-forward
9433 (regexp-quote (format org-coderef-label-format label))
9434 nil t))))
9435 (when label (message "Label exists already") (sit-for 2))
9436 (setq label (read-string "Code line label: " label)))
9437 (end-of-line 1)
9438 (setq link (format org-coderef-label-format label))
9439 (setq gc (- 79 (length link)))
9440 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9441 (insert link)
9442 (setq link (concat "(" label ")") desc nil)))
9444 ;; We are in the agenda, link to referenced location
9445 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9446 (let ((m (or (get-text-property (point) 'org-hd-marker)
9447 (get-text-property (point) 'org-marker))))
9448 (when m
9449 (org-with-point-at m
9450 (setq agenda-link
9451 (if (org-called-interactively-p 'any)
9452 (call-interactively 'org-store-link)
9453 (org-store-link nil)))))))
9455 ((eq major-mode 'calendar-mode)
9456 (let ((cd (calendar-cursor-to-date)))
9457 (setq link
9458 (format-time-string
9459 (car org-time-stamp-formats)
9460 (apply 'encode-time
9461 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9462 nil nil nil))))
9463 (org-store-link-props :type "calendar" :date cd)))
9465 ((eq major-mode 'help-mode)
9466 (setq link (concat "help:" (save-excursion
9467 (goto-char (point-min))
9468 (looking-at "^[^ ]+")
9469 (match-string 0))))
9470 (org-store-link-props :type "help"))
9472 ((eq major-mode 'w3-mode)
9473 (setq cpltxt (if (and (buffer-name)
9474 (not (string-match "Untitled" (buffer-name))))
9475 (buffer-name)
9476 (url-view-url t))
9477 link (url-view-url t))
9478 (org-store-link-props :type "w3" :url (url-view-url t)))
9480 ((eq major-mode 'image-mode)
9481 (setq cpltxt (concat "file:"
9482 (abbreviate-file-name buffer-file-name))
9483 link cpltxt)
9484 (org-store-link-props :type "image" :file buffer-file-name))
9486 ;; In dired, store a link to the file of the current line
9487 ((eq major-mode 'dired-mode)
9488 (let ((file (dired-get-filename nil t)))
9489 (setq file (if file
9490 (abbreviate-file-name
9491 (expand-file-name (dired-get-filename nil t)))
9492 ;; otherwise, no file so use current directory.
9493 default-directory))
9494 (setq cpltxt (concat "file:" file)
9495 link cpltxt)))
9497 ((setq search (run-hook-with-args-until-success
9498 'org-create-file-search-functions))
9499 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9500 "::" search))
9501 (setq cpltxt (or description link)))
9503 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9504 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9505 (cond
9506 ;; Store a link using the target at point
9507 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9508 (setq cpltxt
9509 (concat "file:"
9510 (abbreviate-file-name
9511 (buffer-file-name (buffer-base-buffer)))
9512 "::" (match-string 1))
9513 link cpltxt))
9514 ((and (featurep 'org-id)
9515 (or (eq org-id-link-to-org-use-id t)
9516 (and (org-called-interactively-p 'any)
9517 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9518 (and (eq org-id-link-to-org-use-id
9519 'create-if-interactive-and-no-custom-id)
9520 (not custom-id))))
9521 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9522 ;; Store a link using the ID at point
9523 (setq link (condition-case nil
9524 (prog1 (org-id-store-link)
9525 (setq desc (plist-get org-store-link-plist
9526 :description)))
9527 (error
9528 ;; Probably before first headline, link only to file
9529 (concat "file:"
9530 (abbreviate-file-name
9531 (buffer-file-name (buffer-base-buffer))))))))
9533 ;; Just link to current headline
9534 (setq cpltxt (concat "file:"
9535 (abbreviate-file-name
9536 (buffer-file-name (buffer-base-buffer)))))
9537 ;; Add a context search string
9538 (when (org-xor org-context-in-file-links arg)
9539 (let* ((ee (org-element-at-point))
9540 (et (org-element-type ee))
9541 (ev (plist-get (cadr ee) :value))
9542 (ek (plist-get (cadr ee) :key))
9543 (eok (and (stringp ek) (string-match "name" ek))))
9544 (setq txt (cond
9545 ((org-at-heading-p) nil)
9546 ((and (eq et 'keyword) eok) ev)
9547 ((org-region-active-p)
9548 (buffer-substring (region-beginning) (region-end)))))
9549 (when (or (null txt) (string-match "\\S-" txt))
9550 (setq cpltxt
9551 (concat cpltxt "::"
9552 (condition-case nil
9553 (org-make-org-heading-search-string txt)
9554 (error "")))
9555 desc (or (and (eq et 'keyword) eok ev)
9556 (nth 4 (ignore-errors (org-heading-components)))
9557 "NONE")))))
9558 (if (string-match "::\\'" cpltxt)
9559 (setq cpltxt (substring cpltxt 0 -2)))
9560 (setq link cpltxt))))
9562 ((buffer-file-name (buffer-base-buffer))
9563 ;; Just link to this file here.
9564 (setq cpltxt (concat "file:"
9565 (abbreviate-file-name
9566 (buffer-file-name (buffer-base-buffer)))))
9567 ;; Add a context string.
9568 (when (org-xor org-context-in-file-links arg)
9569 (setq txt (if (org-region-active-p)
9570 (buffer-substring (region-beginning) (region-end))
9571 (buffer-substring (point-at-bol) (point-at-eol))))
9572 ;; Only use search option if there is some text.
9573 (when (string-match "\\S-" txt)
9574 (setq cpltxt
9575 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9576 desc "NONE")))
9577 (setq link cpltxt))
9579 ((org-called-interactively-p 'interactive)
9580 (user-error "No method for storing a link from this buffer"))
9582 (t (setq link nil)))
9584 ;; We're done setting link and desc, clean up
9585 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9586 (setq link (or link cpltxt)
9587 desc (or desc cpltxt))
9588 (cond ((equal desc "NONE") (setq desc nil))
9589 ((string-match org-bracket-link-analytic-regexp desc)
9590 (let ((d0 (match-string 3 desc))
9591 (p0 (match-string 5 desc)))
9592 (setq desc
9593 (replace-regexp-in-string
9594 org-bracket-link-regexp
9595 (concat (or p0 d0)
9596 (if (equal (length (match-string 0 desc))
9597 (length desc)) "*" "")) desc)))))
9599 ;; Return the link
9600 (if (not (and (or (org-called-interactively-p 'any)
9601 executing-kbd-macro) link))
9602 (or agenda-link (and link (org-make-link-string link desc)))
9603 (push (list link desc) org-stored-links)
9604 (message "Stored: %s" (or desc link))
9605 (when custom-id
9606 (setq link (concat "file:" (abbreviate-file-name
9607 (buffer-file-name)) "::#" custom-id))
9608 (push (list link desc) org-stored-links)))))))
9610 (defun org-store-link-props (&rest plist)
9611 "Store link properties, extract names and addresses."
9612 (let (x adr)
9613 (when (setq x (plist-get plist :from))
9614 (setq adr (mail-extract-address-components x))
9615 (setq plist (plist-put plist :fromname (car adr)))
9616 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9617 (when (setq x (plist-get plist :to))
9618 (setq adr (mail-extract-address-components x))
9619 (setq plist (plist-put plist :toname (car adr)))
9620 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9621 (let ((from (plist-get plist :from))
9622 (to (plist-get plist :to)))
9623 (when (and from to org-from-is-user-regexp)
9624 (setq plist
9625 (plist-put plist :fromto
9626 (if (string-match org-from-is-user-regexp from)
9627 (concat "to %t")
9628 (concat "from %f"))))))
9629 (setq org-store-link-plist plist))
9631 (defun org-add-link-props (&rest plist)
9632 "Add these properties to the link property list."
9633 (let (key value)
9634 (while plist
9635 (setq key (pop plist) value (pop plist))
9636 (setq org-store-link-plist
9637 (plist-put org-store-link-plist key value)))))
9639 (defun org-email-link-description (&optional fmt)
9640 "Return the description part of an email link.
9641 This takes information from `org-store-link-plist' and formats it
9642 according to FMT (default from `org-email-link-description-format')."
9643 (setq fmt (or fmt org-email-link-description-format))
9644 (let* ((p org-store-link-plist)
9645 (to (plist-get p :toaddress))
9646 (from (plist-get p :fromaddress))
9647 (table
9648 (list
9649 (cons "%c" (plist-get p :fromto))
9650 (cons "%F" (plist-get p :from))
9651 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9652 (cons "%T" (plist-get p :to))
9653 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9654 (cons "%s" (plist-get p :subject))
9655 (cons "%d" (plist-get p :date))
9656 (cons "%m" (plist-get p :message-id)))))
9657 (when (string-match "%c" fmt)
9658 ;; Check if the user wrote this message
9659 (if (and org-from-is-user-regexp from to
9660 (save-match-data (string-match org-from-is-user-regexp from)))
9661 (setq fmt (replace-match "to %t" t t fmt))
9662 (setq fmt (replace-match "from %f" t t fmt))))
9663 (org-replace-escapes fmt table)))
9665 (defun org-make-org-heading-search-string (&optional string)
9666 "Make search string for the current headline or STRING."
9667 (let ((s (or string
9668 (and (derived-mode-p 'org-mode)
9669 (save-excursion
9670 (org-back-to-heading t)
9671 (org-element-property :raw-value (org-element-at-point))))))
9672 (lines org-context-in-file-links))
9673 (or string (setq s (concat "*" s))) ; Add * for headlines
9674 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9675 (when (and string (integerp lines) (> lines 0))
9676 (let ((slines (org-split-string s "\n")))
9677 (when (< lines (length slines))
9678 (setq s (mapconcat
9679 'identity
9680 (reverse (nthcdr (- (length slines) lines)
9681 (reverse slines))) "\n")))))
9682 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9684 (defun org-make-link-string (link &optional description)
9685 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9686 (unless (string-match "\\S-" link)
9687 (error "Empty link"))
9688 (when (and description
9689 (stringp description)
9690 (not (string-match "\\S-" description)))
9691 (setq description nil))
9692 (when (stringp description)
9693 ;; Remove brackets from the description, they are fatal.
9694 (while (string-match "\\[" description)
9695 (setq description (replace-match "{" t t description)))
9696 (while (string-match "\\]" description)
9697 (setq description (replace-match "}" t t description))))
9698 (when (equal link description)
9699 ;; No description needed, it is identical
9700 (setq description nil))
9701 (when (and (not description)
9702 (not (string-match (org-image-file-name-regexp) link))
9703 (not (equal link (org-link-escape link))))
9704 (setq description (org-extract-attributes link)))
9705 (setq link
9706 (cond ((string-match (org-image-file-name-regexp) link) link)
9707 ((string-match org-link-types-re link)
9708 (concat (match-string 1 link)
9709 (org-link-escape (substring link (match-end 1)))))
9710 (t (org-link-escape link))))
9711 (concat "[[" link "]"
9712 (if description (concat "[" description "]") "")
9713 "]"))
9715 (defconst org-link-escape-chars
9716 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9717 "List of characters that should be escaped in link.
9718 This is the list that is used for internal purposes.")
9720 (defconst org-link-escape-chars-browser
9721 '(?\ ?\")
9722 "List of escapes for characters that are problematic in links.
9723 This is the list that is used before handing over to the browser.")
9725 (defun org-link-escape (text &optional table merge)
9726 "Return percent escaped representation of TEXT.
9727 TEXT is a string with the text to escape.
9728 Optional argument TABLE is a list with characters that should be
9729 escaped. When nil, `org-link-escape-chars' is used.
9730 If optional argument MERGE is set, merge TABLE into
9731 `org-link-escape-chars'."
9732 (cond
9733 ((and table merge)
9734 (mapc (lambda (defchr)
9735 (unless (member defchr table)
9736 (setq table (cons defchr table)))) org-link-escape-chars))
9737 ((null table)
9738 (setq table org-link-escape-chars)))
9739 (mapconcat
9740 (lambda (char)
9741 (if (or (member char table)
9742 (and (or (< char 32) (= char 37) (> char 126))
9743 org-url-hexify-p))
9744 (mapconcat (lambda (sequence-element)
9745 (format "%%%.2X" sequence-element))
9746 (or (encode-coding-char char 'utf-8)
9747 (error "Unable to percent escape character: %s"
9748 (char-to-string char))) "")
9749 (char-to-string char))) text ""))
9751 (defun org-link-unescape (str)
9752 "Unhex hexified Unicode strings as returned from the JavaScript function
9753 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9754 (unless (and (null str) (string= "" str))
9755 (let ((pos 0) (case-fold-search t) unhexed)
9756 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9757 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9758 (setq str (replace-match unhexed t t str))
9759 (setq pos (+ pos (length unhexed))))))
9760 str)
9762 (defun org-link-unescape-compound (hex)
9763 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9764 Note: this function also decodes single byte encodings like
9765 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9766 (save-match-data
9767 (let* ((bytes (cdr (split-string hex "%")))
9768 (ret "")
9769 (eat 0)
9770 (sum 0))
9771 (while bytes
9772 (let* ((val (string-to-number (pop bytes) 16))
9773 (shift-xor
9774 (if (= 0 eat)
9775 (cond
9776 ((>= val 252) (cons 6 252))
9777 ((>= val 248) (cons 5 248))
9778 ((>= val 240) (cons 4 240))
9779 ((>= val 224) (cons 3 224))
9780 ((>= val 192) (cons 2 192))
9781 (t (cons 0 0)))
9782 (cons 6 128))))
9783 (if (>= val 192) (setq eat (car shift-xor)))
9784 (setq val (logxor val (cdr shift-xor)))
9785 (setq sum (+ (lsh sum (car shift-xor)) val))
9786 (if (> eat 0) (setq eat (- eat 1)))
9787 (cond
9788 ((= 0 eat) ;multi byte
9789 (setq ret (concat ret (org-char-to-string sum)))
9790 (setq sum 0))
9791 ((not bytes) ; single byte(s)
9792 (setq ret (org-link-unescape-single-byte-sequence hex))))
9793 )) ;; end (while bytes
9794 ret )))
9796 (defun org-link-unescape-single-byte-sequence (hex)
9797 "Unhexify hex-encoded single byte character sequences."
9798 (mapconcat (lambda (byte)
9799 (char-to-string (string-to-number byte 16)))
9800 (cdr (split-string hex "%")) ""))
9802 (defun org-xor (a b)
9803 "Exclusive or."
9804 (if a (not b) b))
9806 (defun org-fixup-message-id-for-http (s)
9807 "Replace special characters in a message id, so it can be used in an http query."
9808 (when (string-match "%" s)
9809 (setq s (mapconcat (lambda (c)
9810 (if (eq c ?%)
9811 "%25"
9812 (char-to-string c)))
9813 s "")))
9814 (while (string-match "<" s)
9815 (setq s (replace-match "%3C" t t s)))
9816 (while (string-match ">" s)
9817 (setq s (replace-match "%3E" t t s)))
9818 (while (string-match "@" s)
9819 (setq s (replace-match "%40" t t s)))
9822 (defun org-link-prettify (link)
9823 "Return a human-readable representation of LINK.
9824 The car of LINK must be a raw link the cdr of LINK must be either
9825 a link description or nil."
9826 (let ((desc (or (cadr link) "<no description>")))
9827 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9828 "<" (car link) ">")))
9830 ;;;###autoload
9831 (defun org-insert-link-global ()
9832 "Insert a link like Org-mode does.
9833 This command can be called in any mode to insert a link in Org-mode syntax."
9834 (interactive)
9835 (org-load-modules-maybe)
9836 (org-run-like-in-org-mode 'org-insert-link))
9838 (defun org-insert-all-links (&optional keep)
9839 "Insert all links in `org-stored-links'."
9840 (interactive "P")
9841 (let ((links (copy-sequence org-stored-links)) l)
9842 (while (setq l (if keep (pop links) (pop org-stored-links)))
9843 (insert "- ")
9844 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9845 (insert "\n"))))
9847 (defun org-link-fontify-links-to-this-file ()
9848 "Fontify links to the current file in `org-stored-links'."
9849 (let ((f (buffer-file-name)) a b)
9850 (setq a (mapcar (lambda(l)
9851 (let ((ll (car l)))
9852 (when (and (string-match "^file:\\(.+\\)::" ll)
9853 (equal f (expand-file-name (match-string 1 ll))))
9854 ll)))
9855 org-stored-links))
9856 (when (featurep 'org-id)
9857 (setq b (mapcar (lambda(l)
9858 (let ((ll (car l)))
9859 (when (and (string-match "^id:\\(.+\\)$" ll)
9860 (equal f (expand-file-name
9861 (or (org-id-find-id-file
9862 (match-string 1 ll)) ""))))
9863 ll)))
9864 org-stored-links)))
9865 (mapcar (lambda(l)
9866 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9867 (delq nil (append a b)))))
9869 (defvar org-link-links-in-this-file nil)
9870 (defun org-insert-link (&optional complete-file link-location default-description)
9871 "Insert a link. At the prompt, enter the link.
9873 Completion can be used to insert any of the link protocol prefixes like
9874 http or ftp in use.
9876 The history can be used to select a link previously stored with
9877 `org-store-link'. When the empty string is entered (i.e. if you just
9878 press RET at the prompt), the link defaults to the most recently
9879 stored link. As SPC triggers completion in the minibuffer, you need to
9880 use M-SPC or C-q SPC to force the insertion of a space character.
9882 You will also be prompted for a description, and if one is given, it will
9883 be displayed in the buffer instead of the link.
9885 If there is already a link at point, this command will allow you to edit link
9886 and description parts.
9888 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9889 be selected using completion. The path to the file will be relative to the
9890 current directory if the file is in the current directory or a subdirectory.
9891 Otherwise, the link will be the absolute path as completed in the minibuffer
9892 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9893 option `org-link-file-path-type'.
9895 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9896 the current directory or below.
9898 With three \\[universal-argument] prefixes, negate the meaning of
9899 `org-keep-stored-link-after-insertion'.
9901 If `org-make-link-description-function' is non-nil, this function will be
9902 called with the link target, and the result will be the default
9903 link description.
9905 If the LINK-LOCATION parameter is non-nil, this value will be
9906 used as the link location instead of reading one interactively.
9908 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9909 be used as the default description."
9910 (interactive "P")
9911 (let* ((wcf (current-window-configuration))
9912 (origbuf (current-buffer))
9913 (region (if (org-region-active-p)
9914 (buffer-substring (region-beginning) (region-end))))
9915 (remove (and region (list (region-beginning) (region-end))))
9916 (desc region)
9917 tmphist ; byte-compile incorrectly complains about this
9918 (link link-location)
9919 (abbrevs org-link-abbrev-alist-local)
9920 entry file all-prefixes auto-desc)
9921 (cond
9922 (link-location) ; specified by arg, just use it.
9923 ((org-in-regexp org-bracket-link-regexp 1)
9924 ;; We do have a link at point, and we are going to edit it.
9925 (setq remove (list (match-beginning 0) (match-end 0)))
9926 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9927 (setq link (read-string "Link: "
9928 (org-link-unescape
9929 (org-match-string-no-properties 1)))))
9930 ((or (org-in-regexp org-angle-link-re)
9931 (org-in-regexp org-plain-link-re))
9932 ;; Convert to bracket link
9933 (setq remove (list (match-beginning 0) (match-end 0))
9934 link (read-string "Link: "
9935 (org-remove-angle-brackets (match-string 0)))))
9936 ((member complete-file '((4) (16)))
9937 ;; Completing read for file names.
9938 (setq link (org-file-complete-link complete-file)))
9940 ;; Read link, with completion for stored links.
9941 (org-link-fontify-links-to-this-file)
9942 (org-switch-to-buffer-other-window "*Org Links*")
9943 (with-current-buffer "*Org Links*"
9944 (erase-buffer)
9945 (insert "Insert a link.
9946 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9947 (when org-stored-links
9948 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9949 (insert (mapconcat 'org-link-prettify
9950 (reverse org-stored-links) "\n")))
9951 (goto-char (point-min)))
9952 (let ((cw (selected-window)))
9953 (select-window (get-buffer-window "*Org Links*" 'visible))
9954 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9955 (unless (pos-visible-in-window-p (point-max))
9956 (org-fit-window-to-buffer))
9957 (and (window-live-p cw) (select-window cw)))
9958 ;; Fake a link history, containing the stored links.
9959 (setq tmphist (append (mapcar 'car org-stored-links)
9960 org-insert-link-history))
9961 (setq all-prefixes (append (mapcar 'car abbrevs)
9962 (mapcar 'car org-link-abbrev-alist)
9963 org-link-types))
9964 (unwind-protect
9965 (progn
9966 (setq link
9967 (org-completing-read
9968 "Link: "
9969 (append
9970 (mapcar (lambda (x) (concat x ":"))
9971 all-prefixes)
9972 (mapcar 'car org-stored-links))
9973 nil nil nil
9974 'tmphist
9975 (caar org-stored-links)))
9976 (if (not (string-match "\\S-" link))
9977 (user-error "No link selected"))
9978 (mapc (lambda(l)
9979 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9980 org-stored-links)
9981 (if (or (member link all-prefixes)
9982 (and (equal ":" (substring link -1))
9983 (member (substring link 0 -1) all-prefixes)
9984 (setq link (substring link 0 -1))))
9985 (setq link (with-current-buffer origbuf
9986 (org-link-try-special-completion link)))))
9987 (set-window-configuration wcf)
9988 (kill-buffer "*Org Links*"))
9989 (setq entry (assoc link org-stored-links))
9990 (or entry (push link org-insert-link-history))
9991 (setq desc (or desc (nth 1 entry)))))
9993 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9994 (not org-keep-stored-link-after-insertion))
9995 (setq org-stored-links (delq (assoc link org-stored-links)
9996 org-stored-links)))
9998 (if (string-match org-plain-link-re link)
9999 ;; URL-like link, normalize the use of angular brackets.
10000 (setq link (org-remove-angle-brackets link)))
10002 ;; Check if we are linking to the current file with a search
10003 ;; option If yes, simplify the link by using only the search
10004 ;; option.
10005 (when (and buffer-file-name
10006 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10007 (let* ((path (match-string 1 link))
10008 (case-fold-search nil)
10009 (search (match-string 2 link)))
10010 (save-match-data
10011 (if (equal (file-truename buffer-file-name) (file-truename path))
10012 ;; We are linking to this same file, with a search option
10013 (setq link search)))))
10015 ;; Check if we can/should use a relative path. If yes, simplify the link
10016 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10017 (let* ((type (match-string 1 link))
10018 (path (match-string 2 link))
10019 (origpath path)
10020 (case-fold-search nil))
10021 (cond
10022 ((or (eq org-link-file-path-type 'absolute)
10023 (equal complete-file '(16)))
10024 (setq path (abbreviate-file-name (expand-file-name path))))
10025 ((eq org-link-file-path-type 'noabbrev)
10026 (setq path (expand-file-name path)))
10027 ((eq org-link-file-path-type 'relative)
10028 (setq path (file-relative-name path)))
10030 (save-match-data
10031 (if (string-match (concat "^" (regexp-quote
10032 (expand-file-name
10033 (file-name-as-directory
10034 default-directory))))
10035 (expand-file-name path))
10036 ;; We are linking a file with relative path name.
10037 (setq path (substring (expand-file-name path)
10038 (match-end 0)))
10039 (setq path (abbreviate-file-name (expand-file-name path)))))))
10040 (setq link (concat type path))
10041 (if (equal desc origpath)
10042 (setq desc path))))
10044 (if org-make-link-description-function
10045 (setq desc
10046 (or (condition-case nil
10047 (funcall org-make-link-description-function link desc)
10048 (error (progn (message "Can't get link description from `%s'"
10049 (symbol-name org-make-link-description-function))
10050 (sit-for 2) nil)))
10051 (read-string "Description: " default-description)))
10052 (if default-description (setq desc default-description)
10053 (setq desc (or (and auto-desc desc)
10054 (read-string "Description: " desc)))))
10056 (unless (string-match "\\S-" desc) (setq desc nil))
10057 (if remove (apply 'delete-region remove))
10058 (insert (org-make-link-string link desc))))
10060 (defun org-link-try-special-completion (type)
10061 "If there is completion support for link type TYPE, offer it."
10062 (let ((fun (intern (concat "org-" type "-complete-link"))))
10063 (if (functionp fun)
10064 (funcall fun)
10065 (read-string "Link (no completion support): " (concat type ":")))))
10067 (defun org-file-complete-link (&optional arg)
10068 "Create a file link using completion."
10069 (let (file link)
10070 (setq file (org-iread-file-name "File: "))
10071 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10072 (pwd1 (file-name-as-directory (abbreviate-file-name
10073 (expand-file-name ".")))))
10074 (cond
10075 ((equal arg '(16))
10076 (setq link (concat
10077 "file:"
10078 (abbreviate-file-name (expand-file-name file)))))
10079 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10080 (setq link (concat "file:" (match-string 1 file))))
10081 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10082 (expand-file-name file))
10083 (setq link (concat
10084 "file:" (match-string 1 (expand-file-name file)))))
10085 (t (setq link (concat "file:" file)))))
10086 link))
10088 (defun org-iread-file-name (&rest args)
10089 "Read-file-name using `ido-mode' speedup if available.
10090 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10091 See `read-file-name' for a description of parameters."
10092 (org-without-partial-completion
10093 (if (and org-completion-use-ido
10094 (fboundp 'ido-read-file-name)
10095 (boundp 'ido-mode) ido-mode
10096 (listp (second args)))
10097 (let ((ido-enter-matching-directory nil))
10098 (apply 'ido-read-file-name args))
10099 (apply 'read-file-name args))))
10101 (defun org-completing-read (&rest args)
10102 "Completing-read with SPACE being a normal character."
10103 (let ((enable-recursive-minibuffers t)
10104 (minibuffer-local-completion-map
10105 (copy-keymap minibuffer-local-completion-map)))
10106 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10107 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10108 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10109 (apply 'org-icompleting-read args)))
10111 (defun org-completing-read-no-i (&rest args)
10112 (let (org-completion-use-ido org-completion-use-iswitchb)
10113 (apply 'org-completing-read args)))
10115 (defun org-iswitchb-completing-read (prompt choices &rest args)
10116 "Use iswitch as a completing-read replacement to choose from choices.
10117 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10118 from."
10119 (let* ((iswitchb-use-virtual-buffers nil)
10120 (iswitchb-make-buflist-hook
10121 (lambda ()
10122 (setq iswitchb-temp-buflist choices))))
10123 (iswitchb-read-buffer prompt)))
10125 (defun org-icompleting-read (&rest args)
10126 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10127 (org-without-partial-completion
10128 (if (and org-completion-use-ido
10129 (fboundp 'ido-completing-read)
10130 (boundp 'ido-mode) ido-mode
10131 (listp (second args)))
10132 (let ((ido-enter-matching-directory nil))
10133 (apply 'ido-completing-read (concat (car args))
10134 (if (consp (car (nth 1 args)))
10135 (mapcar 'car (nth 1 args))
10136 (nth 1 args))
10137 (cddr args)))
10138 (if (and org-completion-use-iswitchb
10139 (boundp 'iswitchb-mode) iswitchb-mode
10140 (listp (second args)))
10141 (apply 'org-iswitchb-completing-read (concat (car args))
10142 (if (consp (car (nth 1 args)))
10143 (mapcar 'car (nth 1 args))
10144 (nth 1 args))
10145 (cddr args))
10146 (apply 'completing-read args)))))
10148 (defun org-extract-attributes (s)
10149 "Extract the attributes cookie from a string and set as text property."
10150 (let (a attr (start 0) key value)
10151 (save-match-data
10152 (when (string-match "{{\\([^}]+\\)}}$" s)
10153 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10154 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10155 (setq key (match-string 1 a) value (match-string 2 a)
10156 start (match-end 0)
10157 attr (plist-put attr (intern key) value))))
10158 (org-add-props s nil 'org-attr attr))
10161 ;;; Opening/following a link
10163 (defvar org-link-search-failed nil)
10165 (defvar org-open-link-functions nil
10166 "Hook for functions finding a plain text link.
10167 These functions must take a single argument, the link content.
10168 They will be called for links that look like [[link text][description]]
10169 when LINK TEXT does not have a protocol like \"http:\" and does not look
10170 like a filename (e.g. \"./blue.png\").
10172 These functions will be called *before* Org attempts to resolve the
10173 link by doing text searches in the current buffer - so if you want a
10174 link \"[[target]]\" to still find \"<<target>>\", your function should
10175 handle this as a special case.
10177 When the function does handle the link, it must return a non-nil value.
10178 If it decides that it is not responsible for this link, it must return
10179 nil to indicate that that Org-mode can continue with other options
10180 like exact and fuzzy text search.")
10182 (defun org-next-link (&optional search-backward)
10183 "Move forward to the next link.
10184 If the link is in hidden text, expose it."
10185 (interactive "P")
10186 (when (and org-link-search-failed (eq this-command last-command))
10187 (goto-char (point-min))
10188 (message "Link search wrapped back to beginning of buffer"))
10189 (setq org-link-search-failed nil)
10190 (let* ((pos (point))
10191 (ct (org-context))
10192 (a (assoc :link ct))
10193 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10194 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10195 ((looking-at org-any-link-re)
10196 ;; Don't stay stuck at link without an org-link face
10197 (forward-char (if search-backward -1 1))))
10198 (if (funcall srch-fun org-any-link-re nil t)
10199 (progn
10200 (goto-char (match-beginning 0))
10201 (if (outline-invisible-p) (org-show-context)))
10202 (goto-char pos)
10203 (setq org-link-search-failed t)
10204 (message "No further link found"))))
10206 (defun org-previous-link ()
10207 "Move backward to the previous link.
10208 If the link is in hidden text, expose it."
10209 (interactive)
10210 (funcall 'org-next-link t))
10212 (defun org-translate-link (s)
10213 "Translate a link string if a translation function has been defined."
10214 (if (and org-link-translation-function
10215 (fboundp org-link-translation-function)
10216 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10217 (progn
10218 (setq s (funcall org-link-translation-function
10219 (match-string 1 s) (match-string 2 s)))
10220 (concat (car s) ":" (cdr s)))
10223 (defun org-translate-link-from-planner (type path)
10224 "Translate a link from Emacs Planner syntax so that Org can follow it.
10225 This is still an experimental function, your mileage may vary."
10226 (cond
10227 ((member type '("http" "https" "news" "ftp"))
10228 ;; standard Internet links are the same.
10229 nil)
10230 ((and (equal type "irc") (string-match "^//" path))
10231 ;; Planner has two / at the beginning of an irc link, we have 1.
10232 ;; We should have zero, actually....
10233 (setq path (substring path 1)))
10234 ((and (equal type "lisp") (string-match "^/" path))
10235 ;; Planner has a slash, we do not.
10236 (setq type "elisp" path (substring path 1)))
10237 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10238 ;; A typical message link. Planner has the id after the final slash,
10239 ;; we separate it with a hash mark
10240 (setq path (concat (match-string 1 path) "#"
10241 (org-remove-angle-brackets (match-string 2 path))))))
10242 (cons type path))
10244 (defun org-find-file-at-mouse (ev)
10245 "Open file link or URL at mouse."
10246 (interactive "e")
10247 (mouse-set-point ev)
10248 (org-open-at-point 'in-emacs))
10250 (defun org-open-at-mouse (ev)
10251 "Open file link or URL at mouse.
10252 See the docstring of `org-open-file' for details."
10253 (interactive "e")
10254 (mouse-set-point ev)
10255 (if (eq major-mode 'org-agenda-mode)
10256 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10257 (org-open-at-point))
10259 (defvar org-window-config-before-follow-link nil
10260 "The window configuration before following a link.
10261 This is saved in case the need arises to restore it.")
10263 (defvar org-open-link-marker (make-marker)
10264 "Marker pointing to the location where `org-open-at-point; was called.")
10266 ;;;###autoload
10267 (defun org-open-at-point-global ()
10268 "Follow a link like Org-mode does.
10269 This command can be called in any mode to follow a link that has
10270 Org-mode syntax."
10271 (interactive)
10272 (org-run-like-in-org-mode 'org-open-at-point))
10274 ;;;###autoload
10275 (defun org-open-link-from-string (s &optional arg reference-buffer)
10276 "Open a link in the string S, as if it was in Org-mode."
10277 (interactive "sLink: \nP")
10278 (let ((reference-buffer (or reference-buffer (current-buffer))))
10279 (with-temp-buffer
10280 (let ((org-inhibit-startup (not reference-buffer)))
10281 (org-mode)
10282 (insert s)
10283 (goto-char (point-min))
10284 (when reference-buffer
10285 (setq org-link-abbrev-alist-local
10286 (with-current-buffer reference-buffer
10287 org-link-abbrev-alist-local)))
10288 (org-open-at-point arg reference-buffer)))))
10290 (defvar org-open-at-point-functions nil
10291 "Hook that is run when following a link at point.
10293 Functions in this hook must return t if they identify and follow
10294 a link at point. If they don't find anything interesting at point,
10295 they must return nil.")
10297 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10298 (defun org-open-at-point (&optional arg reference-buffer)
10299 "Open link at or after point.
10300 If there is no link at point, this function will search forward up to
10301 the end of the current line.
10302 Normally, files will be opened by an appropriate application. If the
10303 optional prefix argument ARG is non-nil, Emacs will visit the file.
10304 With a double prefix argument, try to open outside of Emacs, in the
10305 application the system uses for this file type."
10306 (interactive "P")
10307 ;; if in a code block, then open the block's results
10308 (unless (call-interactively #'org-babel-open-src-block-result)
10309 (org-load-modules-maybe)
10310 (move-marker org-open-link-marker (point))
10311 (setq org-window-config-before-follow-link (current-window-configuration))
10312 (org-remove-occur-highlights nil nil t)
10313 (cond
10314 ((and (org-at-heading-p)
10315 (not (org-at-timestamp-p t))
10316 (not (org-in-regexp
10317 (concat org-plain-link-re "\\|"
10318 org-bracket-link-regexp "\\|"
10319 org-angle-link-re "\\|"
10320 "[ \t]:[^ \t\n]+:[ \t]*$")))
10321 (not (get-text-property (point) 'org-linked-text)))
10322 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10323 (lk0 (car lkall))
10324 (lk (if (stringp lk0) (list lk0) lk0))
10325 (lkend (cdr lkall)))
10326 (mapcar (lambda(l)
10327 (search-forward l nil lkend)
10328 (goto-char (match-beginning 0))
10329 (org-open-at-point))
10330 lk))
10331 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10332 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10333 ((and (org-at-timestamp-p t)
10334 (not (org-in-regexp org-bracket-link-regexp)))
10335 (org-follow-timestamp-link))
10336 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10337 (not (org-in-regexp org-any-link-re)))
10338 (org-footnote-action))
10340 (let (type path link line search (pos (point)))
10341 (catch 'match
10342 (save-excursion
10343 (skip-chars-forward "^]\n\r")
10344 (when (org-in-regexp org-bracket-link-regexp 1)
10345 (setq link (org-extract-attributes
10346 (org-link-unescape (org-match-string-no-properties 1))))
10347 (while (string-match " *\n *" link)
10348 (setq link (replace-match " " t t link)))
10349 (setq link (org-link-expand-abbrev link))
10350 (cond
10351 ((or (file-name-absolute-p link)
10352 (string-match "^\\.\\.?/" link))
10353 (setq type "file" path link))
10354 ((string-match org-link-re-with-space3 link)
10355 (setq type (match-string 1 link) path (match-string 2 link)))
10356 ((string-match "^help:+\\(.+\\)" link)
10357 (setq type "help" path (match-string 1 link)))
10358 (t (setq type "thisfile" path link)))
10359 (throw 'match t)))
10361 (when (get-text-property (point) 'org-linked-text)
10362 (setq type "thisfile"
10363 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10364 (1+ (point)) (point))
10365 path (buffer-substring
10366 (or (previous-single-property-change pos 'org-linked-text)
10367 (point-min))
10368 (or (next-single-property-change pos 'org-linked-text)
10369 (point-max)))
10370 ;; Ensure we will search for a <<<radio>>> link, not
10371 ;; a simple reference like <<ref>>
10372 path (concat "<" path))
10373 (throw 'match t))
10375 (save-excursion
10376 (when (or (org-in-regexp org-angle-link-re)
10377 (let ((match (org-in-regexp org-plain-link-re)))
10378 ;; Check a plain link is not within a bracket link
10379 (and match
10380 (save-excursion
10381 (progn
10382 (goto-char (car match))
10383 (not (org-in-regexp org-bracket-link-regexp))))))
10384 (let ((line_ending (save-excursion (end-of-line) (point))))
10385 ;; We are in a line before a plain or bracket link
10386 (or (re-search-forward org-plain-link-re line_ending t)
10387 (re-search-forward org-bracket-link-regexp line_ending t))))
10388 (setq type (match-string 1)
10389 path (org-link-unescape (match-string 2)))
10390 (throw 'match t)))
10391 (save-excursion
10392 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10393 (setq type "tags"
10394 path (match-string 1))
10395 (while (string-match ":" path)
10396 (setq path (replace-match "+" t t path)))
10397 (throw 'match t)))
10398 (when (org-in-regexp "<\\([^><\n]+\\)>")
10399 (setq type "tree-match"
10400 path (match-string 1))
10401 (throw 'match t)))
10402 (unless path
10403 (user-error "No link found"))
10405 ;; switch back to reference buffer
10406 ;; needed when if called in a temporary buffer through
10407 ;; org-open-link-from-string
10408 (with-current-buffer (or reference-buffer (current-buffer))
10410 ;; Remove any trailing spaces in path
10411 (if (string-match " +\\'" path)
10412 (setq path (replace-match "" t t path)))
10413 (if (and org-link-translation-function
10414 (fboundp org-link-translation-function))
10415 ;; Check if we need to translate the link
10416 (let ((tmp (funcall org-link-translation-function type path)))
10417 (setq type (car tmp) path (cdr tmp))))
10419 (cond
10421 ((assoc type org-link-protocols)
10422 (funcall (nth 1 (assoc type org-link-protocols)) path))
10424 ((equal type "help")
10425 (let ((f-or-v (intern path)))
10426 (cond ((fboundp f-or-v)
10427 (describe-function f-or-v))
10428 ((boundp f-or-v)
10429 (describe-variable f-or-v))
10430 (t (error "Not a known function or variable")))))
10432 ((equal type "mailto")
10433 (let ((cmd (car org-link-mailto-program))
10434 (args (cdr org-link-mailto-program)) args1
10435 (address path) (subject "") a)
10436 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10437 (setq address (match-string 1 path)
10438 subject (org-link-escape (match-string 2 path))))
10439 (while args
10440 (cond
10441 ((not (stringp (car args))) (push (pop args) args1))
10442 (t (setq a (pop args))
10443 (if (string-match "%a" a)
10444 (setq a (replace-match address t t a)))
10445 (if (string-match "%s" a)
10446 (setq a (replace-match subject t t a)))
10447 (push a args1))))
10448 (apply cmd (nreverse args1))))
10450 ((member type '("http" "https" "ftp" "news"))
10451 (browse-url
10452 (concat type ":"
10453 (if (org-string-match-p
10454 (concat "[[:nonascii:]"
10455 org-link-escape-chars-browser "]")
10456 path)
10457 (org-link-escape path org-link-escape-chars-browser)
10458 path))))
10460 ((string= type "doi")
10461 (browse-url
10462 (concat org-doi-server-url
10463 (if (org-string-match-p
10464 (concat "[[:nonascii:]"
10465 org-link-escape-chars-browser "]")
10466 path)
10467 (org-link-escape path org-link-escape-chars-browser)
10468 path))))
10470 ((member type '("message"))
10471 (browse-url (concat type ":" path)))
10473 ((string= type "tags")
10474 (org-tags-view arg path))
10476 ((string= type "tree-match")
10477 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10479 ((string= type "file")
10480 (if (string-match "::\\([0-9]+\\)\\'" path)
10481 (setq line (string-to-number (match-string 1 path))
10482 path (substring path 0 (match-beginning 0)))
10483 (if (string-match "::\\(.+\\)\\'" path)
10484 (setq search (match-string 1 path)
10485 path (substring path 0 (match-beginning 0)))))
10486 (if (string-match "[*?{]" (file-name-nondirectory path))
10487 (dired path)
10488 (org-open-file path arg line search)))
10490 ((string= type "shell")
10491 (let ((buf (generate-new-buffer "*Org Shell Output"))
10492 (cmd path))
10493 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10494 (string-match org-confirm-shell-link-not-regexp cmd))
10495 (not org-confirm-shell-link-function)
10496 (funcall org-confirm-shell-link-function
10497 (format "Execute \"%s\" in shell? "
10498 (org-add-props cmd nil
10499 'face 'org-warning))))
10500 (progn
10501 (message "Executing %s" cmd)
10502 (shell-command cmd buf)
10503 (if (featurep 'midnight)
10504 (setq clean-buffer-list-kill-buffer-names
10505 (cons buf clean-buffer-list-kill-buffer-names))))
10506 (error "Abort"))))
10508 ((string= type "elisp")
10509 (let ((cmd path))
10510 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10511 (string-match org-confirm-elisp-link-not-regexp cmd))
10512 (not org-confirm-elisp-link-function)
10513 (funcall org-confirm-elisp-link-function
10514 (format "Execute \"%s\" as elisp? "
10515 (org-add-props cmd nil
10516 'face 'org-warning))))
10517 (message "%s => %s" cmd
10518 (if (equal (string-to-char cmd) ?\()
10519 (eval (read cmd))
10520 (call-interactively (read cmd))))
10521 (error "Abort"))))
10523 ((and (string= type "thisfile")
10524 (run-hook-with-args-until-success
10525 'org-open-link-functions path)))
10527 ((string= type "thisfile")
10528 (if arg
10529 (switch-to-buffer-other-window
10530 (org-get-buffer-for-internal-link (current-buffer)))
10531 (org-mark-ring-push))
10532 (let ((cmd `(org-link-search
10533 ,path
10534 ,(cond ((equal arg '(4)) ''occur)
10535 ((equal arg '(16)) ''org-occur))
10536 ,pos)))
10537 (condition-case nil (let ((org-link-search-inhibit-query t))
10538 (eval cmd))
10539 (error (progn (widen) (eval cmd))))))
10541 (t (browse-url-at-point)))))))
10542 (move-marker org-open-link-marker nil)
10543 (run-hook-with-args 'org-follow-link-hook)))
10545 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10546 "Offer links in the current entry and return the selected link.
10547 If there is only one link, return it.
10548 If NTH is an integer, return the NTH link found.
10549 If ZERO is a string, check also this string for a link, and if
10550 there is one, return it."
10551 (with-current-buffer buffer
10552 (save-excursion
10553 (save-restriction
10554 (widen)
10555 (goto-char marker)
10556 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10557 "\\(" org-angle-link-re "\\)\\|"
10558 "\\(" org-plain-link-re "\\)"))
10559 (cnt ?0)
10560 (in-emacs (if (integerp nth) nil nth))
10561 have-zero end links link c)
10562 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10563 (push (match-string 0 zero) links)
10564 (setq cnt (1- cnt) have-zero t))
10565 (save-excursion
10566 (org-back-to-heading t)
10567 (setq end (save-excursion (outline-next-heading) (point)))
10568 (while (re-search-forward re end t)
10569 (push (match-string 0) links))
10570 (setq links (org-uniquify (reverse links))))
10571 (cond
10572 ((null links)
10573 (message "No links"))
10574 ((equal (length links) 1)
10575 (setq link (car links)))
10576 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10577 (setq link (nth (if have-zero nth (1- nth)) links)))
10578 (t ; we have to select a link
10579 (save-excursion
10580 (save-window-excursion
10581 (delete-other-windows)
10582 (with-output-to-temp-buffer "*Select Link*"
10583 (mapc (lambda (l)
10584 (if (not (string-match org-bracket-link-regexp l))
10585 (princ (format "[%c] %s\n" (incf cnt)
10586 (org-remove-angle-brackets l)))
10587 (if (match-end 3)
10588 (princ (format "[%c] %s (%s)\n" (incf cnt)
10589 (match-string 3 l) (match-string 1 l)))
10590 (princ (format "[%c] %s\n" (incf cnt)
10591 (match-string 1 l))))))
10592 links))
10593 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10594 (message "Select link to open, RET to open all:")
10595 (setq c (read-char-exclusive))
10596 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10597 (when (equal c ?q) (error "Abort"))
10598 (if (equal c ?\C-m)
10599 (setq link links)
10600 (setq nth (- c ?0))
10601 (if have-zero (setq nth (1+ nth)))
10602 (unless (and (integerp nth) (>= (length links) nth))
10603 (user-error "Invalid link selection"))
10604 (setq link (nth (1- nth) links)))))
10605 (cons link end))))))
10607 ;; Add special file links that specify the way of opening
10609 (org-add-link-type "file+sys" 'org-open-file-with-system)
10610 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10611 (defun org-open-file-with-system (path)
10612 "Open file at PATH using the system way of opening it."
10613 (org-open-file path 'system))
10614 (defun org-open-file-with-emacs (path)
10615 "Open file at PATH in Emacs."
10616 (org-open-file path 'emacs))
10619 ;;; File search
10621 (defvar org-create-file-search-functions nil
10622 "List of functions to construct the right search string for a file link.
10623 These functions are called in turn with point at the location to
10624 which the link should point.
10626 A function in the hook should first test if it would like to
10627 handle this file type, for example by checking the `major-mode'
10628 or the file extension. If it decides not to handle this file, it
10629 should just return nil to give other functions a chance. If it
10630 does handle the file, it must return the search string to be used
10631 when following the link. The search string will be part of the
10632 file link, given after a double colon, and `org-open-at-point'
10633 will automatically search for it. If special measures must be
10634 taken to make the search successful, another function should be
10635 added to the companion hook `org-execute-file-search-functions',
10636 which see.
10638 A function in this hook may also use `setq' to set the variable
10639 `description' to provide a suggestion for the descriptive text to
10640 be used for this link when it gets inserted into an Org-mode
10641 buffer with \\[org-insert-link].")
10643 (defvar org-execute-file-search-functions nil
10644 "List of functions to execute a file search triggered by a link.
10646 Functions added to this hook must accept a single argument, the
10647 search string that was part of the file link, the part after the
10648 double colon. The function must first check if it would like to
10649 handle this search, for example by checking the `major-mode' or
10650 the file extension. If it decides not to handle this search, it
10651 should just return nil to give other functions a chance. If it
10652 does handle the search, it must return a non-nil value to keep
10653 other functions from trying.
10655 Each function can access the current prefix argument through the
10656 variable `current-prefix-arg'. Note that a single prefix is used
10657 to force opening a link in Emacs, so it may be good to only use a
10658 numeric or double prefix to guide the search function.
10660 In case this is needed, a function in this hook can also restore
10661 the window configuration before `org-open-at-point' was called using:
10663 (set-window-configuration org-window-config-before-follow-link)")
10665 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10666 (defun org-link-search (s &optional type avoid-pos stealth)
10667 "Search for a link search option.
10668 If S is surrounded by forward slashes, it is interpreted as a
10669 regular expression. In org-mode files, this will create an `org-occur'
10670 sparse tree. In ordinary files, `occur' will be used to list matches.
10671 If the current buffer is in `dired-mode', grep will be used to search
10672 in all files. If AVOID-POS is given, ignore matches near that position.
10674 When optional argument STEALTH is non-nil, do not modify
10675 visibility around point, thus ignoring
10676 `org-show-hierarchy-above', `org-show-following-heading' and
10677 `org-show-siblings' variables."
10678 (let ((case-fold-search t)
10679 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10680 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10681 (append '(("") (" ") ("\t") ("\n"))
10682 org-emphasis-alist)
10683 "\\|") "\\)"))
10684 (pos (point))
10685 (pre nil) (post nil)
10686 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10687 (cond
10688 ;; First check if there are any special search functions
10689 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10690 ;; Now try the builtin stuff
10691 ((and (equal (string-to-char s0) ?#)
10692 (> (length s0) 1)
10693 (save-excursion
10694 (goto-char (point-min))
10695 (and
10696 (re-search-forward
10697 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10698 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10699 (setq type 'dedicated
10700 pos (match-beginning 0))))
10701 ;; There is an exact target for this
10702 (goto-char pos)
10703 (org-back-to-heading t)))
10704 ((save-excursion
10705 (goto-char (point-min))
10706 (and
10707 (re-search-forward
10708 (concat "<<" (regexp-quote s0) ">>") nil t)
10709 (setq type 'dedicated
10710 pos (match-beginning 0))))
10711 ;; There is an exact target for this
10712 (goto-char pos))
10713 ((save-excursion
10714 (goto-char (point-min))
10715 (and
10716 (re-search-forward
10717 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10718 (setq type 'dedicated pos (match-beginning 0))))
10719 ;; Found an element with a matching #+name affiliated keyword.
10720 (goto-char pos))
10721 ((and (string-match "^(\\(.*\\))$" s0)
10722 (save-excursion
10723 (goto-char (point-min))
10724 (and
10725 (re-search-forward
10726 (concat "[^[]" (regexp-quote
10727 (format org-coderef-label-format
10728 (match-string 1 s0))))
10729 nil t)
10730 (setq type 'dedicated
10731 pos (1+ (match-beginning 0))))))
10732 ;; There is a coderef target for this
10733 (goto-char pos))
10734 ((string-match "^/\\(.*\\)/$" s)
10735 ;; A regular expression
10736 (cond
10737 ((derived-mode-p 'org-mode)
10738 (org-occur (match-string 1 s)))
10739 (t (org-do-occur (match-string 1 s)))))
10740 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10741 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10742 (goto-char (point-min))
10743 (cond
10744 ((let (case-fold-search)
10745 (re-search-forward (format org-complex-heading-regexp-format
10746 (regexp-quote s))
10747 nil t))
10748 ;; OK, found a match
10749 (setq type 'dedicated)
10750 (goto-char (match-beginning 0)))
10751 ((and (not org-link-search-inhibit-query)
10752 (eq org-link-search-must-match-exact-headline 'query-to-create)
10753 (y-or-n-p "No match - create this as a new heading? "))
10754 (goto-char (point-max))
10755 (or (bolp) (newline))
10756 (insert "* " s "\n")
10757 (beginning-of-line 0))
10759 (goto-char pos)
10760 (error "No match"))))
10762 ;; A normal search string
10763 (when (equal (string-to-char s) ?*)
10764 ;; Anchor on headlines, post may include tags.
10765 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10766 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10767 s (substring s 1)))
10768 (remove-text-properties
10769 0 (length s)
10770 '(face nil mouse-face nil keymap nil fontified nil) s)
10771 ;; Make a series of regular expressions to find a match
10772 (setq words (org-split-string s "[ \n\r\t]+")
10774 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10775 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10776 "\\)" markers)
10777 re2a_ (concat "\\(" (mapconcat 'downcase words
10778 "[ \t\r\n]+") "\\)[ \t\r\n]")
10779 re2a (concat "[ \t\r\n]" re2a_)
10780 re4_ (concat "\\(" (mapconcat 'downcase words
10781 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10782 re4 (concat "[^a-zA-Z_]" re4_)
10784 re1 (concat pre re2 post)
10785 re3 (concat pre (if pre re4_ re4) post)
10786 re5 (concat pre ".*" re4)
10787 re2 (concat pre re2)
10788 re2a (concat pre (if pre re2a_ re2a))
10789 re4 (concat pre (if pre re4_ re4))
10790 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10791 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10792 re5 "\\)"))
10793 (cond
10794 ((eq type 'org-occur) (org-occur reall))
10795 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10796 (t (goto-char (point-min))
10797 (setq type 'fuzzy)
10798 (if (or (and (org-search-not-self 1 re0 nil t)
10799 (setq type 'dedicated))
10800 (org-search-not-self 1 re1 nil t)
10801 (org-search-not-self 1 re2 nil t)
10802 (org-search-not-self 1 re2a nil t)
10803 (org-search-not-self 1 re3 nil t)
10804 (org-search-not-self 1 re4 nil t)
10805 (org-search-not-self 1 re5 nil t))
10806 (goto-char (match-beginning 1))
10807 (goto-char pos)
10808 (error "No match"))))))
10809 (and (derived-mode-p 'org-mode)
10810 (not stealth)
10811 (org-show-context 'link-search))
10812 type))
10814 (defun org-search-not-self (group &rest args)
10815 "Execute `re-search-forward', but only accept matches that do not
10816 enclose the position of `org-open-link-marker'."
10817 (let ((m org-open-link-marker))
10818 (catch 'exit
10819 (while (apply 're-search-forward args)
10820 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10821 (goto-char (match-end group))
10822 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10823 (> (match-beginning 0) (marker-position m))
10824 (< (match-end 0) (marker-position m)))
10825 (save-match-data
10826 (or (not (org-in-regexp
10827 org-bracket-link-analytic-regexp 1))
10828 (not (match-end 4)) ; no description
10829 (and (<= (match-beginning 4) (point))
10830 (>= (match-end 4) (point))))))
10831 (throw 'exit (point))))))))
10833 (defun org-get-buffer-for-internal-link (buffer)
10834 "Return a buffer to be used for displaying the link target of internal links."
10835 (cond
10836 ((not org-display-internal-link-with-indirect-buffer)
10837 buffer)
10838 ((string-match "(Clone)$" (buffer-name buffer))
10839 (message "Buffer is already a clone, not making another one")
10840 ;; we also do not modify visibility in this case
10841 buffer)
10842 (t ; make a new indirect buffer for displaying the link
10843 (let* ((bn (buffer-name buffer))
10844 (ibn (concat bn "(Clone)"))
10845 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10846 (with-current-buffer ib (org-overview))
10847 ib))))
10849 (defun org-do-occur (regexp &optional cleanup)
10850 "Call the Emacs command `occur'.
10851 If CLEANUP is non-nil, remove the printout of the regular expression
10852 in the *Occur* buffer. This is useful if the regex is long and not useful
10853 to read."
10854 (occur regexp)
10855 (when cleanup
10856 (let ((cwin (selected-window)) win beg end)
10857 (when (setq win (get-buffer-window "*Occur*"))
10858 (select-window win))
10859 (goto-char (point-min))
10860 (when (re-search-forward "match[a-z]+" nil t)
10861 (setq beg (match-end 0))
10862 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10863 (setq end (1- (match-beginning 0)))))
10864 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10865 (goto-char (point-min))
10866 (select-window cwin))))
10868 ;;; The mark ring for links jumps
10870 (defvar org-mark-ring nil
10871 "Mark ring for positions before jumps in Org-mode.")
10872 (defvar org-mark-ring-last-goto nil
10873 "Last position in the mark ring used to go back.")
10874 ;; Fill and close the ring
10875 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10876 (loop for i from 1 to org-mark-ring-length do
10877 (push (make-marker) org-mark-ring))
10878 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10879 org-mark-ring)
10881 (defun org-mark-ring-push (&optional pos buffer)
10882 "Put the current position or POS into the mark ring and rotate it."
10883 (interactive)
10884 (setq pos (or pos (point)))
10885 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10886 (move-marker (car org-mark-ring)
10887 (or pos (point))
10888 (or buffer (current-buffer)))
10889 (message "%s"
10890 (substitute-command-keys
10891 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10893 (defun org-mark-ring-goto (&optional n)
10894 "Jump to the previous position in the mark ring.
10895 With prefix arg N, jump back that many stored positions. When
10896 called several times in succession, walk through the entire ring.
10897 Org-mode commands jumping to a different position in the current file,
10898 or to another Org-mode file, automatically push the old position
10899 onto the ring."
10900 (interactive "p")
10901 (let (p m)
10902 (if (eq last-command this-command)
10903 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10904 (setq p org-mark-ring))
10905 (setq org-mark-ring-last-goto p)
10906 (setq m (car p))
10907 (org-pop-to-buffer-same-window (marker-buffer m))
10908 (goto-char m)
10909 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10911 (defun org-remove-angle-brackets (s)
10912 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10913 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10915 (defun org-add-angle-brackets (s)
10916 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10917 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10919 (defun org-remove-double-quotes (s)
10920 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10921 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10924 ;;; Following specific links
10926 (defun org-follow-timestamp-link ()
10927 "Open an agenda view for the time-stamp date/range at point."
10928 (cond
10929 ((org-at-date-range-p t)
10930 (let ((org-agenda-start-on-weekday)
10931 (t1 (match-string 1))
10932 (t2 (match-string 2)) tt1 tt2)
10933 (setq tt1 (time-to-days (org-time-string-to-time t1))
10934 tt2 (time-to-days (org-time-string-to-time t2)))
10935 (let ((org-agenda-buffer-tmp-name
10936 (format "*Org Agenda(a:%s)"
10937 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10938 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10939 ((org-at-timestamp-p t)
10940 (let ((org-agenda-buffer-tmp-name
10941 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10942 (org-agenda-list nil (time-to-days (org-time-string-to-time
10943 (substring (match-string 1) 0 10)))
10944 1)))
10945 (t (error "This should not happen"))))
10948 ;;; Following file links
10949 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10950 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10951 (declare-function mailcap-mime-info
10952 "mailcap" (string &optional request no-decode))
10953 (defvar org-wait nil)
10954 (defun org-open-file (path &optional in-emacs line search)
10955 "Open the file at PATH.
10956 First, this expands any special file name abbreviations. Then the
10957 configuration variable `org-file-apps' is checked if it contains an
10958 entry for this file type, and if yes, the corresponding command is launched.
10960 If no application is found, Emacs simply visits the file.
10962 With optional prefix argument IN-EMACS, Emacs will visit the file.
10963 With a double \\[universal-argument] \\[universal-argument] \
10964 prefix arg, Org tries to avoid opening in Emacs
10965 and to use an external application to visit the file.
10967 Optional LINE specifies a line to go to, optional SEARCH a string
10968 to search for. If LINE or SEARCH is given, the file will be
10969 opened in Emacs, unless an entry from org-file-apps that makes
10970 use of groups in a regexp matches.
10972 If you want to change the way frames are used when following a
10973 link, please customize `org-link-frame-setup'.
10975 If the file does not exist, an error is thrown."
10976 (let* ((file (if (equal path "")
10977 buffer-file-name
10978 (substitute-in-file-name (expand-file-name path))))
10979 (file-apps (append org-file-apps (org-default-apps)))
10980 (apps (org-remove-if
10981 'org-file-apps-entry-match-against-dlink-p file-apps))
10982 (apps-dlink (org-remove-if-not
10983 'org-file-apps-entry-match-against-dlink-p file-apps))
10984 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10985 (dirp (if remp nil (file-directory-p file)))
10986 (file (if (and dirp org-open-directory-means-index-dot-org)
10987 (concat (file-name-as-directory file) "index.org")
10988 file))
10989 (a-m-a-p (assq 'auto-mode apps))
10990 (dfile (downcase file))
10991 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10992 (link (cond ((and (eq line nil)
10993 (eq search nil))
10994 file)
10995 (line
10996 (concat file "::" (number-to-string line)))
10997 (search
10998 (concat file "::" search))))
10999 (dlink (downcase link))
11000 (old-buffer (current-buffer))
11001 (old-pos (point))
11002 (old-mode major-mode)
11003 ext cmd link-match-data)
11004 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11005 (setq ext (match-string 1 dfile))
11006 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11007 (setq ext (match-string 1 dfile))))
11008 (cond
11009 ((member in-emacs '((16) system))
11010 (setq cmd (cdr (assoc 'system apps))))
11011 (in-emacs (setq cmd 'emacs))
11013 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11014 (and dirp (cdr (assoc 'directory apps)))
11015 ; first, try matching against apps-dlink
11016 ; if we get a match here, store the match data for later
11017 (let ((match (assoc-default dlink apps-dlink
11018 'string-match)))
11019 (if match
11020 (progn (setq link-match-data (match-data))
11021 match)
11022 (progn (setq in-emacs (or in-emacs line search))
11023 nil))) ; if we have no match in apps-dlink,
11024 ; always open the file in emacs if line or search
11025 ; is given (for backwards compatibility)
11026 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11027 'string-match)
11028 (cdr (assoc ext apps))
11029 (cdr (assoc t apps))))))
11030 (when (eq cmd 'system)
11031 (setq cmd (cdr (assoc 'system apps))))
11032 (when (eq cmd 'default)
11033 (setq cmd (cdr (assoc t apps))))
11034 (when (eq cmd 'mailcap)
11035 (require 'mailcap)
11036 (mailcap-parse-mailcaps)
11037 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11038 (command (mailcap-mime-info mime-type)))
11039 (if (stringp command)
11040 (setq cmd command)
11041 (setq cmd 'emacs))))
11042 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11043 (not (file-exists-p file))
11044 (not org-open-non-existing-files))
11045 (user-error "No such file: %s" file))
11046 (cond
11047 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11048 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11049 (while (string-match "['\"]%s['\"]" cmd)
11050 (setq cmd (replace-match "%s" t t cmd)))
11051 (while (string-match "%s" cmd)
11052 (setq cmd (replace-match
11053 (save-match-data
11054 (shell-quote-argument
11055 (convert-standard-filename file)))
11056 t t cmd)))
11058 ;; Replace "%1", "%2" etc. in command with group matches from regex
11059 (save-match-data
11060 (let ((match-index 1)
11061 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11062 (set-match-data link-match-data)
11063 (while (<= match-index number-of-groups)
11064 (let ((regex (concat "%" (number-to-string match-index)))
11065 (replace-with (match-string match-index dlink)))
11066 (while (string-match regex cmd)
11067 (setq cmd (replace-match replace-with t t cmd))))
11068 (setq match-index (+ match-index 1)))))
11070 (save-window-excursion
11071 (message "Running %s...done" cmd)
11072 (start-process-shell-command cmd nil cmd)
11073 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11074 ((or (stringp cmd)
11075 (eq cmd 'emacs))
11076 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11077 (widen)
11078 (if line (org-goto-line line)
11079 (if search (org-link-search search))))
11080 ((consp cmd)
11081 (let ((file (convert-standard-filename file)))
11082 (save-match-data
11083 (set-match-data link-match-data)
11084 (eval cmd))))
11085 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11086 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11087 (or (not (equal old-buffer (current-buffer)))
11088 (not (equal old-pos (point))))
11089 (org-mark-ring-push old-pos old-buffer))))
11091 (defun org-file-apps-entry-match-against-dlink-p (entry)
11092 "This function returns non-nil if `entry' uses a regular
11093 expression which should be matched against the whole link by
11094 org-open-file.
11096 It assumes that is the case when the entry uses a regular
11097 expression which has at least one grouping construct and the
11098 action is either a lisp form or a command string containing
11099 '%1', i.e. using at least one subexpression match as a
11100 parameter."
11101 (let ((selector (car entry))
11102 (action (cdr entry)))
11103 (if (stringp selector)
11104 (and (> (regexp-opt-depth selector) 0)
11105 (or (and (stringp action)
11106 (string-match "%[0-9]" action))
11107 (consp action)))
11108 nil)))
11110 (defun org-default-apps ()
11111 "Return the default applications for this operating system."
11112 (cond
11113 ((eq system-type 'darwin)
11114 org-file-apps-defaults-macosx)
11115 ((eq system-type 'windows-nt)
11116 org-file-apps-defaults-windowsnt)
11117 (t org-file-apps-defaults-gnu)))
11119 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11120 "Convert extensions to regular expressions in the cars of LIST.
11121 Also, weed out any non-string entries, because the return value is used
11122 only for regexp matching.
11123 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11124 point to the symbol `emacs', indicating that the file should
11125 be opened in Emacs."
11126 (append
11127 (delq nil
11128 (mapcar (lambda (x)
11129 (if (not (stringp (car x)))
11131 (if (string-match "\\W" (car x))
11133 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11134 list))
11135 (if add-auto-mode
11136 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11138 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11139 (defun org-file-remote-p (file)
11140 "Test whether FILE specifies a location on a remote system.
11141 Return non-nil if the location is indeed remote.
11143 For example, the filename \"/user@host:/foo\" specifies a location
11144 on the system \"/user@host:\"."
11145 (cond ((fboundp 'file-remote-p)
11146 (file-remote-p file))
11147 ((fboundp 'tramp-handle-file-remote-p)
11148 (tramp-handle-file-remote-p file))
11149 ((and (boundp 'ange-ftp-name-format)
11150 (string-match (car ange-ftp-name-format) file))
11151 t)))
11154 ;;;; Refiling
11156 (defun org-get-org-file ()
11157 "Read a filename, with default directory `org-directory'."
11158 (let ((default (or org-default-notes-file remember-data-file)))
11159 (read-file-name (format "File name [%s]: " default)
11160 (file-name-as-directory org-directory)
11161 default)))
11163 (defun org-notes-order-reversed-p ()
11164 "Check if the current file should receive notes in reversed order."
11165 (cond
11166 ((not org-reverse-note-order) nil)
11167 ((eq t org-reverse-note-order) t)
11168 ((not (listp org-reverse-note-order)) nil)
11169 (t (catch 'exit
11170 (let ((all org-reverse-note-order)
11171 entry)
11172 (while (setq entry (pop all))
11173 (if (string-match (car entry) buffer-file-name)
11174 (throw 'exit (cdr entry))))
11175 nil)))))
11177 (defvar org-refile-target-table nil
11178 "The list of refile targets, created by `org-refile'.")
11180 (defvar org-agenda-new-buffers nil
11181 "Buffers created to visit agenda files.")
11183 (defvar org-refile-cache nil
11184 "Cache for refile targets.")
11186 (defvar org-refile-markers nil
11187 "All the markers used for caching refile locations.")
11189 (defun org-refile-marker (pos)
11190 "Get a new refile marker, but only if caching is in use."
11191 (if (not org-refile-use-cache)
11193 (let ((m (make-marker)))
11194 (move-marker m pos)
11195 (push m org-refile-markers)
11196 m)))
11198 (defun org-refile-cache-clear ()
11199 "Clear the refile cache and disable all the markers."
11200 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11201 (setq org-refile-markers nil)
11202 (setq org-refile-cache nil)
11203 (message "Refile cache has been cleared"))
11205 (defun org-refile-cache-check-set (set)
11206 "Check if all the markers in the cache still have live buffers."
11207 (let (marker)
11208 (catch 'exit
11209 (while (and set (setq marker (nth 3 (pop set))))
11210 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11211 (when (and marker (null (marker-buffer marker)))
11212 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11213 (sit-for 3)
11214 (throw 'exit nil)))
11215 t)))
11217 (defun org-refile-cache-put (set &rest identifiers)
11218 "Push the refile targets SET into the cache, under IDENTIFIERS."
11219 (let* ((key (sha1 (prin1-to-string identifiers)))
11220 (entry (assoc key org-refile-cache)))
11221 (if entry
11222 (setcdr entry set)
11223 (push (cons key set) org-refile-cache))))
11225 (defun org-refile-cache-get (&rest identifiers)
11226 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11227 (cond
11228 ((not org-refile-cache) nil)
11229 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11231 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11232 org-refile-cache))))
11233 (and set (org-refile-cache-check-set set) set)))))
11235 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11236 "Produce a table with refile targets."
11237 (let ((case-fold-search nil)
11238 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11239 (entries (or org-refile-targets '((nil . (:level . 1)))))
11240 targets tgs txt re files f desc descre fast-path-p level pos0)
11241 (message "Getting targets...")
11242 (with-current-buffer (or default-buffer (current-buffer))
11243 (while (setq entry (pop entries))
11244 (setq files (car entry) desc (cdr entry))
11245 (setq fast-path-p nil)
11246 (cond
11247 ((null files) (setq files (list (current-buffer))))
11248 ((eq files 'org-agenda-files)
11249 (setq files (org-agenda-files 'unrestricted)))
11250 ((and (symbolp files) (fboundp files))
11251 (setq files (funcall files)))
11252 ((and (symbolp files) (boundp files))
11253 (setq files (symbol-value files))))
11254 (if (stringp files) (setq files (list files)))
11255 (cond
11256 ((eq (car desc) :tag)
11257 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11258 ((eq (car desc) :todo)
11259 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11260 ((eq (car desc) :regexp)
11261 (setq descre (cdr desc)))
11262 ((eq (car desc) :level)
11263 (setq descre (concat "^\\*\\{" (number-to-string
11264 (if org-odd-levels-only
11265 (1- (* 2 (cdr desc)))
11266 (cdr desc)))
11267 "\\}[ \t]")))
11268 ((eq (car desc) :maxlevel)
11269 (setq fast-path-p t)
11270 (setq descre (concat "^\\*\\{1," (number-to-string
11271 (if org-odd-levels-only
11272 (1- (* 2 (cdr desc)))
11273 (cdr desc)))
11274 "\\}[ \t]")))
11275 (t (error "Bad refiling target description %s" desc)))
11276 (while (setq f (pop files))
11277 (with-current-buffer
11278 (if (bufferp f) f (org-get-agenda-file-buffer f))
11280 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11281 (progn
11282 (if (bufferp f) (setq f (buffer-file-name
11283 (buffer-base-buffer f))))
11284 (setq f (and f (expand-file-name f)))
11285 (if (eq org-refile-use-outline-path 'file)
11286 (push (list (file-name-nondirectory f) f nil nil) tgs))
11287 (save-excursion
11288 (save-restriction
11289 (widen)
11290 (goto-char (point-min))
11291 (while (re-search-forward descre nil t)
11292 (goto-char (setq pos0 (point-at-bol)))
11293 (catch 'next
11294 (when org-refile-target-verify-function
11295 (save-match-data
11296 (or (funcall org-refile-target-verify-function)
11297 (throw 'next t))))
11298 (when (and (looking-at org-complex-heading-regexp)
11299 (not (member (match-string 4) excluded-entries))
11300 (match-string 4))
11301 (setq level (org-reduced-level
11302 (- (match-end 1) (match-beginning 1)))
11303 txt (org-link-display-format (match-string 4))
11304 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11305 re (format org-complex-heading-regexp-format
11306 (regexp-quote (match-string 4))))
11307 (when org-refile-use-outline-path
11308 (setq txt (mapconcat
11309 'org-protect-slash
11310 (append
11311 (if (eq org-refile-use-outline-path
11312 'file)
11313 (list (file-name-nondirectory
11314 (buffer-file-name
11315 (buffer-base-buffer))))
11316 (if (eq org-refile-use-outline-path
11317 'full-file-path)
11318 (list (buffer-file-name
11319 (buffer-base-buffer)))))
11320 (org-get-outline-path fast-path-p
11321 level txt)
11322 (list txt))
11323 "/")))
11324 (push (list txt f re (org-refile-marker (point)))
11325 tgs)))
11326 (when (= (point) pos0)
11327 ;; verification function has not moved point
11328 (goto-char (point-at-eol))))))))
11329 (when org-refile-use-cache
11330 (org-refile-cache-put tgs (buffer-file-name) descre))
11331 (setq targets (append tgs targets))))))
11332 (message "Getting targets...done")
11333 (nreverse targets)))
11335 (defun org-protect-slash (s)
11336 (while (string-match "/" s)
11337 (setq s (replace-match "\\" t t s)))
11340 (defvar org-olpa (make-vector 20 nil))
11342 (defun org-get-outline-path (&optional fastp level heading)
11343 "Return the outline path to the current entry, as a list.
11345 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11346 routine which makes outline path derivations for an entire file,
11347 avoiding backtracing. Refile target collection makes use of that."
11348 (if fastp
11349 (progn
11350 (if (> level 19)
11351 (error "Outline path failure, more than 19 levels"))
11352 (loop for i from level upto 19 do
11353 (aset org-olpa i nil))
11354 (prog1
11355 (delq nil (append org-olpa nil))
11356 (aset org-olpa level heading)))
11357 (let (rtn case-fold-search)
11358 (save-excursion
11359 (save-restriction
11360 (widen)
11361 (while (org-up-heading-safe)
11362 (when (looking-at org-complex-heading-regexp)
11363 (push (org-trim
11364 (replace-regexp-in-string
11365 ;; Remove statistical/checkboxes cookies
11366 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11367 (org-match-string-no-properties 4)))
11368 rtn)))
11369 rtn)))))
11371 (defun org-format-outline-path (path &optional width prefix separator)
11372 "Format the outline path PATH for display.
11373 WIDTH is the maximum number of characters that is available.
11374 PREFIX is a prefix to be included in the returned string,
11375 such as the file name.
11376 SEPARATOR is inserted between the different parts of the path,
11377 the default is \"/\"."
11378 (setq width (or width 79))
11379 (if prefix (setq width (- width (length prefix))))
11380 (if (not path)
11381 (or prefix "")
11382 (let* ((nsteps (length path))
11383 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11384 (maxwidth (if (<= total-width width)
11385 10000 ;; everything fits
11386 ;; we need to shorten the level headings
11387 (/ (- width nsteps) nsteps)))
11388 (org-odd-levels-only nil)
11389 (n 0)
11390 (total (1+ (length prefix))))
11391 (setq maxwidth (max maxwidth 10))
11392 (concat prefix
11393 (if prefix (or separator "/"))
11394 (mapconcat
11395 (lambda (h)
11396 (setq n (1+ n))
11397 (if (and (= n nsteps) (< maxwidth 10000))
11398 (setq maxwidth (- total-width total)))
11399 (if (< (length h) maxwidth)
11400 (progn (setq total (+ total (length h) 1)) h)
11401 (setq h (substring h 0 (- maxwidth 2))
11402 total (+ total maxwidth 1))
11403 (if (string-match "[ \t]+\\'" h)
11404 (setq h (substring h 0 (match-beginning 0))))
11405 (setq h (concat h "..")))
11406 (org-add-props h nil 'face
11407 (nth (% (1- n) org-n-level-faces)
11408 org-level-faces))
11410 path (or separator "/"))))))
11412 (defun org-display-outline-path (&optional file current separator just-return-string)
11413 "Display the current outline path in the echo area.
11415 If FILE is non-nil, prepend the output with the file name.
11416 If CURRENT is non-nil, append the current heading to the output.
11417 SEPARATOR is passed through to `org-format-outline-path'. It separates
11418 the different parts of the path and defaults to \"/\".
11419 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11420 (interactive "P")
11421 (let* (case-fold-search
11422 message-log-max ; Don't populate the *Messages* buffer
11423 (bfn (buffer-file-name (buffer-base-buffer)))
11424 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11425 res)
11426 (if current (setq path (append path
11427 (save-excursion
11428 (org-back-to-heading t)
11429 (if (looking-at org-complex-heading-regexp)
11430 (list (match-string 4)))))))
11431 (setq res
11432 (org-format-outline-path
11433 path
11434 (1- (frame-width))
11435 (and file bfn (concat (file-name-nondirectory bfn) separator))
11436 separator))
11437 (if just-return-string
11438 (org-no-properties res)
11439 (message "%s" res))))
11441 (defvar org-refile-history nil
11442 "History for refiling operations.")
11444 (defvar org-after-refile-insert-hook nil
11445 "Hook run after `org-refile' has inserted its stuff at the new location.
11446 Note that this is still *before* the stuff will be removed from
11447 the *old* location.")
11449 (defvar org-capture-last-stored-marker)
11450 (defvar org-refile-keep nil
11451 "Non-nil means `org-refile' will copy instead of refile.")
11453 (defun org-copy ()
11454 "Like `org-refile', but copy."
11455 (interactive)
11456 (let ((org-refile-keep t))
11457 (funcall 'org-refile nil nil nil "Copy")))
11459 (defun org-refile (&optional goto default-buffer rfloc msg)
11460 "Move the entry or entries at point to another heading.
11461 The list of target headings is compiled using the information in
11462 `org-refile-targets', which see.
11464 At the target location, the entry is filed as a subitem of the target
11465 heading. Depending on `org-reverse-note-order', the new subitem will
11466 either be the first or the last subitem.
11468 If there is an active region, all entries in that region will be moved.
11469 However, the region must fulfill the requirement that the first heading
11470 is the first one sets the top-level of the moved text - at most siblings
11471 below it are allowed.
11473 With prefix arg GOTO, the command will only visit the target location
11474 and not actually move anything.
11476 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11477 go to the location where the last refiling operation has put the subtree.
11479 With a numeric prefix argument of `2', refile to the running clock.
11481 With a numeric prefix argument of `3', emulate `org-refile-keep'
11482 being set to `t' and copy to the target location, don't move it.
11483 Beware that keeping refiled entries may result in duplicated ID
11484 properties.
11486 RFLOC can be a refile location obtained in a different way.
11488 MSG is a string to replace \"Refile\" in the default prompt with
11489 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11491 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11493 If you are using target caching (see `org-refile-use-cache'),
11494 you have to clear the target cache in order to find new targets.
11495 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11496 prefix argument (`C-u C-u C-u C-c C-w')."
11498 (interactive "P")
11499 (if (member goto '(0 (64)))
11500 (org-refile-cache-clear)
11501 (let* ((actionmsg (or msg "Refile"))
11502 (cbuf (current-buffer))
11503 (regionp (org-region-active-p))
11504 (region-start (and regionp (region-beginning)))
11505 (region-end (and regionp (region-end)))
11506 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11507 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11508 pos it nbuf file re level reversed)
11509 (setq last-command nil)
11510 (when regionp
11511 (goto-char region-start)
11512 (or (bolp) (goto-char (point-at-bol)))
11513 (setq region-start (point))
11514 (unless (or (org-kill-is-subtree-p
11515 (buffer-substring region-start region-end))
11516 (prog1 org-refile-active-region-within-subtree
11517 (let ((s (point-at-eol)))
11518 (org-toggle-heading)
11519 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11520 (user-error "The region is not a (sequence of) subtree(s)")))
11521 (if (equal goto '(16))
11522 (org-refile-goto-last-stored)
11523 (when (or
11524 (and (equal goto 2)
11525 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11526 (prog1
11527 (setq it (list (or org-clock-heading "running clock")
11528 (buffer-file-name
11529 (marker-buffer org-clock-hd-marker))
11531 (marker-position org-clock-hd-marker)))
11532 (setq goto nil)))
11533 (setq it (or rfloc
11534 (let (heading-text)
11535 (save-excursion
11536 (unless goto
11537 (org-back-to-heading t)
11538 (setq heading-text
11539 (nth 4 (org-heading-components))))
11541 (org-refile-get-location
11542 (cond (goto "Goto")
11543 (regionp (concat actionmsg " region to"))
11544 (t (concat actionmsg " subtree \""
11545 heading-text "\" to")))
11546 default-buffer
11547 (and (not (equal '(4) goto))
11548 org-refile-allow-creating-parent-nodes)
11549 goto))))))
11550 (setq file (nth 1 it)
11551 re (nth 2 it)
11552 pos (nth 3 it))
11553 (if (and (not goto)
11555 (equal (buffer-file-name) file)
11556 (if regionp
11557 (and (>= pos region-start)
11558 (<= pos region-end))
11559 (and (>= pos (point))
11560 (< pos (save-excursion
11561 (org-end-of-subtree t t))))))
11562 (error "Cannot refile to position inside the tree or region"))
11564 (setq nbuf (or (find-buffer-visiting file)
11565 (find-file-noselect file)))
11566 (if (and goto (not (equal goto 3)))
11567 (progn
11568 (org-pop-to-buffer-same-window nbuf)
11569 (goto-char pos)
11570 (org-show-context 'org-goto))
11571 (if regionp
11572 (progn
11573 (org-kill-new (buffer-substring region-start region-end))
11574 (org-save-markers-in-region region-start region-end))
11575 (org-copy-subtree 1 nil t))
11576 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11577 (find-file-noselect file)))
11578 (setq reversed (org-notes-order-reversed-p))
11579 (save-excursion
11580 (save-restriction
11581 (widen)
11582 (if pos
11583 (progn
11584 (goto-char pos)
11585 (looking-at org-outline-regexp)
11586 (setq level (org-get-valid-level (funcall outline-level) 1))
11587 (goto-char
11588 (if reversed
11589 (or (outline-next-heading) (point-max))
11590 (or (save-excursion (org-get-next-sibling))
11591 (org-end-of-subtree t t)
11592 (point-max)))))
11593 (setq level 1)
11594 (if (not reversed)
11595 (goto-char (point-max))
11596 (goto-char (point-min))
11597 (or (outline-next-heading) (goto-char (point-max)))))
11598 (if (not (bolp)) (newline))
11599 (org-paste-subtree level)
11600 (when org-log-refile
11601 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11602 (unless (eq org-log-refile 'note)
11603 (save-excursion (org-add-log-note))))
11604 (and org-auto-align-tags
11605 (let ((org-loop-over-headlines-in-active-region nil))
11606 (org-set-tags nil t)))
11607 (let ((bookmark-name (plist-get org-bookmark-names-plist
11608 :last-refile)))
11609 (when bookmark-name
11610 (with-demoted-errors
11611 (bookmark-set bookmark-name))))
11612 ;; If we are refiling for capture, make sure that the
11613 ;; last-capture pointers point here
11614 (when (org-bound-and-true-p org-refile-for-capture)
11615 (let ((bookmark-name (plist-get org-bookmark-names-plist
11616 :last-capture-marker)))
11617 (when bookmark-name
11618 (with-demoted-errors
11619 (bookmark-set bookmark-name))))
11620 (move-marker org-capture-last-stored-marker (point)))
11621 (if (fboundp 'deactivate-mark) (deactivate-mark))
11622 (run-hooks 'org-after-refile-insert-hook))))
11623 (unless org-refile-keep
11624 (if regionp
11625 (delete-region (point) (+ (point) (- region-end region-start)))
11626 (delete-region
11627 (and (org-back-to-heading t) (point))
11628 (min (buffer-size) (org-end-of-subtree t t) (point)))))
11629 (when (featurep 'org-inlinetask)
11630 (org-inlinetask-remove-END-maybe))
11631 (setq org-markers-to-move nil)
11632 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11634 (defun org-refile-goto-last-stored ()
11635 "Go to the location where the last refile was stored."
11636 (interactive)
11637 (bookmark-jump "org-refile-last-stored")
11638 (message "This is the location of the last refile"))
11640 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11641 no-exclude)
11642 "Prompt the user for a refile location, using PROMPT.
11643 PROMPT should not be suffixed with a colon and a space, because
11644 this function appends the default value from
11645 `org-refile-history' automatically, if that is not empty.
11646 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11647 this is used for the GOTO interface."
11648 (let ((org-refile-targets org-refile-targets)
11649 (org-refile-use-outline-path org-refile-use-outline-path)
11650 excluded-entries)
11651 (when (and (derived-mode-p 'org-mode)
11652 (not org-refile-use-cache)
11653 (not no-exclude))
11654 (org-map-tree
11655 (lambda()
11656 (setq excluded-entries
11657 (append excluded-entries (list (org-get-heading t t)))))))
11658 (setq org-refile-target-table
11659 (org-refile-get-targets default-buffer excluded-entries)))
11660 (unless org-refile-target-table
11661 (user-error "No refile targets"))
11662 (let* ((cbuf (current-buffer))
11663 (partial-completion-mode nil)
11664 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11665 (cfunc (if (and org-refile-use-outline-path
11666 org-outline-path-complete-in-steps)
11667 'org-olpath-completing-read
11668 'org-icompleting-read))
11669 (extra (if org-refile-use-outline-path "/" ""))
11670 (cbnex (concat (buffer-name) extra))
11671 (filename (and cfn (expand-file-name cfn)))
11672 (tbl (mapcar
11673 (lambda (x)
11674 (if (and (not (member org-refile-use-outline-path
11675 '(file full-file-path)))
11676 (not (equal filename (nth 1 x))))
11677 (cons (concat (car x) extra " ("
11678 (file-name-nondirectory (nth 1 x)) ")")
11679 (cdr x))
11680 (cons (concat (car x) extra) (cdr x))))
11681 org-refile-target-table))
11682 (completion-ignore-case t)
11683 cdef
11684 (prompt (concat prompt
11685 (or (and (car org-refile-history)
11686 (concat " (default " (car org-refile-history) ")"))
11687 (and (assoc cbnex tbl) (setq cdef cbnex)
11688 (concat " (default " cbnex ")"))) ": "))
11689 pa answ parent-target child parent old-hist)
11690 (setq old-hist org-refile-history)
11691 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11692 nil 'org-refile-history (or cdef (car org-refile-history))))
11693 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11694 (org-refile-check-position pa)
11695 (if pa
11696 (progn
11697 (when (or (not org-refile-history)
11698 (not (eq old-hist org-refile-history))
11699 (not (equal (car pa) (car org-refile-history))))
11700 (setq org-refile-history
11701 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11702 org-refile-history
11703 (cdr org-refile-history))))
11704 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11705 (pop org-refile-history)))
11707 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11708 (progn
11709 (setq parent (match-string 1 answ)
11710 child (match-string 2 answ))
11711 (setq parent-target (or (assoc parent tbl)
11712 (assoc (concat parent "/") tbl)))
11713 (when (and parent-target
11714 (or (eq new-nodes t)
11715 (and (eq new-nodes 'confirm)
11716 (y-or-n-p (format "Create new node \"%s\"? "
11717 child)))))
11718 (org-refile-new-child parent-target child)))
11719 (user-error "Invalid target location")))))
11721 (declare-function org-string-nw-p "org-macs" (s))
11722 (defun org-refile-check-position (refile-pointer)
11723 "Check if the refile pointer matches the headline to which it points."
11724 (let* ((file (nth 1 refile-pointer))
11725 (re (nth 2 refile-pointer))
11726 (pos (nth 3 refile-pointer))
11727 buffer)
11728 (if (and (not (markerp pos)) (not file))
11729 (user-error "Please save the buffer to a file before refiling")
11730 (when (org-string-nw-p re)
11731 (setq buffer (if (markerp pos)
11732 (marker-buffer pos)
11733 (or (find-buffer-visiting file)
11734 (find-file-noselect file))))
11735 (with-current-buffer buffer
11736 (save-excursion
11737 (save-restriction
11738 (widen)
11739 (goto-char pos)
11740 (beginning-of-line 1)
11741 (unless (org-looking-at-p re)
11742 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11744 (defun org-refile-new-child (parent-target child)
11745 "Use refile target PARENT-TARGET to add new CHILD below it."
11746 (unless parent-target
11747 (error "Cannot find parent for new node"))
11748 (let ((file (nth 1 parent-target))
11749 (pos (nth 3 parent-target))
11750 level)
11751 (with-current-buffer (or (find-buffer-visiting file)
11752 (find-file-noselect file))
11753 (save-excursion
11754 (save-restriction
11755 (widen)
11756 (if pos
11757 (goto-char pos)
11758 (goto-char (point-max))
11759 (if (not (bolp)) (newline)))
11760 (when (looking-at org-outline-regexp)
11761 (setq level (funcall outline-level))
11762 (org-end-of-subtree t t))
11763 (org-back-over-empty-lines)
11764 (insert "\n" (make-string
11765 (if pos (org-get-valid-level level 1) 1) ?*)
11766 " " child "\n")
11767 (beginning-of-line 0)
11768 (list (concat (car parent-target) "/" child) file "" (point)))))))
11770 (defun org-olpath-completing-read (prompt collection &rest args)
11771 "Read an outline path like a file name."
11772 (let ((thetable collection)
11773 (org-completion-use-ido nil) ; does not work with ido.
11774 (org-completion-use-iswitchb nil)) ; or iswitchb
11775 (apply
11776 'org-icompleting-read prompt
11777 (lambda (string predicate &optional flag)
11778 (let (rtn r f (l (length string)))
11779 (cond
11780 ((eq flag nil)
11781 ;; try completion
11782 (try-completion string thetable))
11783 ((eq flag t)
11784 ;; all-completions
11785 (setq rtn (all-completions string thetable predicate))
11786 (mapcar
11787 (lambda (x)
11788 (setq r (substring x l))
11789 (if (string-match " ([^)]*)$" x)
11790 (setq f (match-string 0 x))
11791 (setq f ""))
11792 (if (string-match "/" r)
11793 (concat string (substring r 0 (match-end 0)) f)
11795 rtn))
11796 ((eq flag 'lambda)
11797 ;; exact match?
11798 (assoc string thetable)))))
11799 args)))
11801 ;;;; Dynamic blocks
11803 (defun org-find-dblock (name)
11804 "Find the first dynamic block with name NAME in the buffer.
11805 If not found, stay at current position and return nil."
11806 (let ((case-fold-search t) pos)
11807 (save-excursion
11808 (goto-char (point-min))
11809 (setq pos (and (re-search-forward
11810 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11811 (match-beginning 0))))
11812 (if pos (goto-char pos))
11813 pos))
11815 (defconst org-dblock-start-re
11816 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11817 "Matches the start line of a dynamic block, with parameters.")
11819 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11820 "Matches the end of a dynamic block.")
11822 (defun org-create-dblock (plist)
11823 "Create a dynamic block section, with parameters taken from PLIST.
11824 PLIST must contain a :name entry which is used as name of the block."
11825 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11826 (end-of-line 1)
11827 (newline))
11828 (let ((col (current-column))
11829 (name (plist-get plist :name)))
11830 (insert "#+BEGIN: " name)
11831 (while plist
11832 (if (eq (car plist) :name)
11833 (setq plist (cddr plist))
11834 (insert " " (prin1-to-string (pop plist)))))
11835 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11836 (beginning-of-line -2)))
11838 (defun org-prepare-dblock ()
11839 "Prepare dynamic block for refresh.
11840 This empties the block, puts the cursor at the insert position and returns
11841 the property list including an extra property :name with the block name."
11842 (unless (looking-at org-dblock-start-re)
11843 (user-error "Not at a dynamic block"))
11844 (let* ((begdel (1+ (match-end 0)))
11845 (name (org-no-properties (match-string 1)))
11846 (params (append (list :name name)
11847 (read (concat "(" (match-string 3) ")")))))
11848 (save-excursion
11849 (beginning-of-line 1)
11850 (skip-chars-forward " \t")
11851 (setq params (plist-put params :indentation-column (current-column))))
11852 (unless (re-search-forward org-dblock-end-re nil t)
11853 (error "Dynamic block not terminated"))
11854 (setq params
11855 (append params
11856 (list :content (buffer-substring
11857 begdel (match-beginning 0)))))
11858 (delete-region begdel (match-beginning 0))
11859 (goto-char begdel)
11860 (open-line 1)
11861 params))
11863 (defun org-map-dblocks (&optional command)
11864 "Apply COMMAND to all dynamic blocks in the current buffer.
11865 If COMMAND is not given, use `org-update-dblock'."
11866 (let ((cmd (or command 'org-update-dblock)))
11867 (save-excursion
11868 (goto-char (point-min))
11869 (while (re-search-forward org-dblock-start-re nil t)
11870 (goto-char (match-beginning 0))
11871 (save-excursion
11872 (condition-case nil
11873 (funcall cmd)
11874 (error (message "Error during update of dynamic block"))))
11875 (unless (re-search-forward org-dblock-end-re nil t)
11876 (error "Dynamic block not terminated"))))))
11878 (defun org-dblock-update (&optional arg)
11879 "User command for updating dynamic blocks.
11880 Update the dynamic block at point. With prefix ARG, update all dynamic
11881 blocks in the buffer."
11882 (interactive "P")
11883 (if arg
11884 (org-update-all-dblocks)
11885 (or (looking-at org-dblock-start-re)
11886 (org-beginning-of-dblock))
11887 (org-update-dblock)))
11889 (defun org-update-dblock ()
11890 "Update the dynamic block at point.
11891 This means to empty the block, parse for parameters and then call
11892 the correct writing function."
11893 (interactive)
11894 (save-window-excursion
11895 (let* ((pos (point))
11896 (line (org-current-line))
11897 (params (org-prepare-dblock))
11898 (name (plist-get params :name))
11899 (indent (plist-get params :indentation-column))
11900 (cmd (intern (concat "org-dblock-write:" name))))
11901 (message "Updating dynamic block `%s' at line %d..." name line)
11902 (funcall cmd params)
11903 (message "Updating dynamic block `%s' at line %d...done" name line)
11904 (goto-char pos)
11905 (when (and indent (> indent 0))
11906 (setq indent (make-string indent ?\ ))
11907 (save-excursion
11908 (org-beginning-of-dblock)
11909 (forward-line 1)
11910 (while (not (looking-at org-dblock-end-re))
11911 (insert indent)
11912 (beginning-of-line 2))
11913 (when (looking-at org-dblock-end-re)
11914 (and (looking-at "[ \t]+")
11915 (replace-match ""))
11916 (insert indent)))))))
11918 (defun org-beginning-of-dblock ()
11919 "Find the beginning of the dynamic block at point.
11920 Error if there is no such block at point."
11921 (let ((pos (point))
11922 beg)
11923 (end-of-line 1)
11924 (if (and (re-search-backward org-dblock-start-re nil t)
11925 (setq beg (match-beginning 0))
11926 (re-search-forward org-dblock-end-re nil t)
11927 (> (match-end 0) pos))
11928 (goto-char beg)
11929 (goto-char pos)
11930 (error "Not in a dynamic block"))))
11932 (defun org-update-all-dblocks ()
11933 "Update all dynamic blocks in the buffer.
11934 This function can be used in a hook."
11935 (interactive)
11936 (when (derived-mode-p 'org-mode)
11937 (org-map-dblocks 'org-update-dblock)))
11940 ;;;; Completion
11942 (declare-function org-export-backend-name "org-export" (cl-x))
11943 (declare-function org-export-backend-options "org-export" (cl-x))
11944 (defun org-get-export-keywords ()
11945 "Return a list of all currently understood export keywords.
11946 Export keywords include options, block names, attributes and
11947 keywords relative to each registered export back-end."
11948 (let (keywords)
11949 (dolist (backend
11950 (org-bound-and-true-p org-export--registered-backends)
11951 (delq nil keywords))
11952 ;; Back-end name (for keywords, like #+LATEX:)
11953 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11954 (dolist (option-entry (org-export-backend-options backend))
11955 ;; Back-end options.
11956 (push (nth 1 option-entry) keywords)))))
11958 (defconst org-options-keywords
11959 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11960 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11961 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11962 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11963 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11965 (defcustom org-structure-template-alist
11966 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
11967 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
11968 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
11969 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
11970 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
11971 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
11972 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11973 "<literal style=\"latex\">\n?\n</literal>")
11974 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
11975 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11976 "<literal style=\"html\">\n?\n</literal>")
11977 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
11978 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
11979 ("A" "#+ASCII: " "")
11980 ("i" "#+INDEX: ?" "#+INDEX: ?")
11981 ("I" "#+INCLUDE: %file ?"
11982 "<include file=%file markup=\"?\">"))
11983 "Structure completion elements.
11984 This is a list of abbreviation keys and values. The value gets inserted
11985 if you type `<' followed by the key and then press the completion key,
11986 usually `M-TAB'. %file will be replaced by a file name after prompting
11987 for the file using completion. The cursor will be placed at the position
11988 of the `?` in the template.
11989 There are two templates for each key, the first uses the original Org syntax,
11990 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11991 the default when the /org-mtags.el/ module has been loaded. See also the
11992 variable `org-mtags-prefer-muse-templates'."
11993 :group 'org-completion
11994 :type '(repeat
11995 (list
11996 (string :tag "Key")
11997 (string :tag "Template")
11998 (string :tag "Muse Template"))))
12000 (defun org-try-structure-completion ()
12001 "Try to complete a structure template before point.
12002 This looks for strings like \"<e\" on an otherwise empty line and
12003 expands them."
12004 (let ((l (buffer-substring (point-at-bol) (point)))
12006 (when (and (looking-at "[ \t]*$")
12007 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12008 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12009 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12010 (match-beginning 1)) a)
12011 t)))
12013 (defun org-complete-expand-structure-template (start cell)
12014 "Expand a structure template."
12015 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12016 (rpl (nth (if musep 2 1) cell))
12017 (ind ""))
12018 (delete-region start (point))
12019 (when (string-match "\\`#\\+" rpl)
12020 (cond
12021 ((bolp))
12022 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12023 (setq ind (buffer-substring (point-at-bol) (point))))
12024 (t (newline))))
12025 (setq start (point))
12026 (if (string-match "%file" rpl)
12027 (setq rpl (replace-match
12028 (concat
12029 "\""
12030 (save-match-data
12031 (abbreviate-file-name (read-file-name "Include file: ")))
12032 "\"")
12033 t t rpl)))
12034 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12035 (concat "\n" ind)))
12036 (insert rpl)
12037 (if (re-search-backward "\\?" start t) (delete-char 1))))
12039 ;;;; TODO, DEADLINE, Comments
12041 (defun org-toggle-comment ()
12042 "Change the COMMENT state of an entry."
12043 (interactive)
12044 (save-excursion
12045 (org-back-to-heading)
12046 (let (case-fold-search)
12047 (cond
12048 ((looking-at (format org-heading-keyword-regexp-format
12049 org-comment-string))
12050 (goto-char (match-end 1))
12051 (looking-at (concat " +" org-comment-string))
12052 (replace-match "" t t)
12053 (when (eolp) (insert " ")))
12054 ((looking-at org-outline-regexp)
12055 (goto-char (match-end 0))
12056 (insert org-comment-string " "))))))
12058 (defvar org-last-todo-state-is-todo nil
12059 "This is non-nil when the last TODO state change led to a TODO state.
12060 If the last change removed the TODO tag or switched to DONE, then
12061 this is nil.")
12063 (defvar org-setting-tags nil) ; dynamically skipped
12065 (defvar org-todo-setup-filter-hook nil
12066 "Hook for functions that pre-filter todo specs.
12067 Each function takes a todo spec and returns either nil or the spec
12068 transformed into canonical form." )
12070 (defvar org-todo-get-default-hook nil
12071 "Hook for functions that get a default item for todo.
12072 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12073 nil or a string to be used for the todo mark." )
12075 (defvar org-agenda-headline-snapshot-before-repeat)
12077 (defun org-current-effective-time ()
12078 "Return current time adjusted for `org-extend-today-until' variable."
12079 (let* ((ct (org-current-time))
12080 (dct (decode-time ct))
12081 (ct1
12082 (cond
12083 (org-use-last-clock-out-time-as-effective-time
12084 (or (org-clock-get-last-clock-out-time) ct))
12085 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12086 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12087 (t ct))))
12088 ct1))
12090 (defun org-todo-yesterday (&optional arg)
12091 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12092 (interactive "P")
12093 (if (eq major-mode 'org-agenda-mode)
12094 (apply 'org-agenda-todo-yesterday arg)
12095 (let* ((hour (third (decode-time
12096 (org-current-time))))
12097 (org-extend-today-until (1+ hour)))
12098 (org-todo arg))))
12100 (defvar org-block-entry-blocking ""
12101 "First entry preventing the TODO state change.")
12103 (defun org-todo (&optional arg)
12104 "Change the TODO state of an item.
12105 The state of an item is given by a keyword at the start of the heading,
12106 like
12107 *** TODO Write paper
12108 *** DONE Call mom
12110 The different keywords are specified in the variable `org-todo-keywords'.
12111 By default the available states are \"TODO\" and \"DONE\".
12112 So for this example: when the item starts with TODO, it is changed to DONE.
12113 When it starts with DONE, the DONE is removed. And when neither TODO nor
12114 DONE are present, add TODO at the beginning of the heading.
12116 With \\[universal-argument] prefix arg, use completion to determine the new \
12117 state.
12118 With numeric prefix arg, switch to that state.
12119 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12120 keywords (nextset).
12121 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12122 With a numeric prefix arg of 0, inhibit note taking for the change.
12124 For calling through lisp, arg is also interpreted in the following way:
12125 'none -> empty state
12126 \"\"(empty string) -> switch to empty state
12127 'done -> switch to DONE
12128 'nextset -> switch to the next set of keywords
12129 'previousset -> switch to the previous set of keywords
12130 \"WAITING\" -> switch to the specified keyword, but only if it
12131 really is a member of `org-todo-keywords'."
12132 (interactive "P")
12133 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12134 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12135 'region-start-level 'region))
12136 org-loop-over-headlines-in-active-region)
12137 (org-map-entries
12138 `(org-todo ,arg)
12139 org-loop-over-headlines-in-active-region
12140 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12141 (if (equal arg '(16)) (setq arg 'nextset))
12142 (let ((org-blocker-hook org-blocker-hook)
12143 commentp
12144 case-fold-search)
12145 (when (equal arg '(64))
12146 (setq arg nil org-blocker-hook nil))
12147 (when (and org-blocker-hook
12148 (or org-inhibit-blocking
12149 (org-entry-get nil "NOBLOCKING")))
12150 (setq org-blocker-hook nil))
12151 (save-excursion
12152 (catch 'exit
12153 (org-back-to-heading t)
12154 (when (looking-at (concat "^\\*+ " org-comment-string))
12155 (org-toggle-comment)
12156 (setq commentp t))
12157 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12158 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12159 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12160 (let* ((match-data (match-data))
12161 (startpos (point-at-bol))
12162 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12163 (org-log-done org-log-done)
12164 (org-log-repeat org-log-repeat)
12165 (org-todo-log-states org-todo-log-states)
12166 (org-inhibit-logging
12167 (if (equal arg 0)
12168 (progn (setq arg nil) 'note) org-inhibit-logging))
12169 (this (match-string 1))
12170 (hl-pos (match-beginning 0))
12171 (head (org-get-todo-sequence-head this))
12172 (ass (assoc head org-todo-kwd-alist))
12173 (interpret (nth 1 ass))
12174 (done-word (nth 3 ass))
12175 (final-done-word (nth 4 ass))
12176 (org-last-state (or this ""))
12177 (completion-ignore-case t)
12178 (member (member this org-todo-keywords-1))
12179 (tail (cdr member))
12180 (org-state (cond
12181 ((and org-todo-key-trigger
12182 (or (and (equal arg '(4))
12183 (eq org-use-fast-todo-selection 'prefix))
12184 (and (not arg) org-use-fast-todo-selection
12185 (not (eq org-use-fast-todo-selection
12186 'prefix)))))
12187 ;; Use fast selection
12188 (org-fast-todo-selection))
12189 ((and (equal arg '(4))
12190 (or (not org-use-fast-todo-selection)
12191 (not org-todo-key-trigger)))
12192 ;; Read a state with completion
12193 (org-icompleting-read
12194 "State: " (mapcar 'list org-todo-keywords-1)
12195 nil t))
12196 ((eq arg 'right)
12197 (if this
12198 (if tail (car tail) nil)
12199 (car org-todo-keywords-1)))
12200 ((eq arg 'left)
12201 (if (equal member org-todo-keywords-1)
12203 (if this
12204 (nth (- (length org-todo-keywords-1)
12205 (length tail) 2)
12206 org-todo-keywords-1)
12207 (org-last org-todo-keywords-1))))
12208 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12209 (setq arg nil))) ; hack to fall back to cycling
12210 (arg
12211 ;; user or caller requests a specific state
12212 (cond
12213 ((equal arg "") nil)
12214 ((eq arg 'none) nil)
12215 ((eq arg 'done) (or done-word (car org-done-keywords)))
12216 ((eq arg 'nextset)
12217 (or (car (cdr (member head org-todo-heads)))
12218 (car org-todo-heads)))
12219 ((eq arg 'previousset)
12220 (let ((org-todo-heads (reverse org-todo-heads)))
12221 (or (car (cdr (member head org-todo-heads)))
12222 (car org-todo-heads))))
12223 ((car (member arg org-todo-keywords-1)))
12224 ((stringp arg)
12225 (user-error "State `%s' not valid in this file" arg))
12226 ((nth (1- (prefix-numeric-value arg))
12227 org-todo-keywords-1))))
12228 ((null member) (or head (car org-todo-keywords-1)))
12229 ((equal this final-done-word) nil) ;; -> make empty
12230 ((null tail) nil) ;; -> first entry
12231 ((memq interpret '(type priority))
12232 (if (eq this-command last-command)
12233 (car tail)
12234 (if (> (length tail) 0)
12235 (or done-word (car org-done-keywords))
12236 nil)))
12238 (car tail))))
12239 (org-state (or
12240 (run-hook-with-args-until-success
12241 'org-todo-get-default-hook org-state org-last-state)
12242 org-state))
12243 (next (if org-state (concat " " org-state " ") " "))
12244 (change-plist (list :type 'todo-state-change :from this :to org-state
12245 :position startpos))
12246 dolog now-done-p)
12247 (when org-blocker-hook
12248 (setq org-last-todo-state-is-todo
12249 (not (member this org-done-keywords)))
12250 (unless (save-excursion
12251 (save-match-data
12252 (org-with-wide-buffer
12253 (run-hook-with-args-until-failure
12254 'org-blocker-hook change-plist))))
12255 (if (org-called-interactively-p 'interactive)
12256 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12257 this org-state org-block-entry-blocking)
12258 ;; fail silently
12259 (message "TODO state change from %s to %s blocked (by \"%s\")"
12260 this org-state org-block-entry-blocking)
12261 (throw 'exit nil))))
12262 (store-match-data match-data)
12263 (replace-match next t t)
12264 (unless (pos-visible-in-window-p hl-pos)
12265 (message "TODO state changed to %s" (org-trim next)))
12266 (unless head
12267 (setq head (org-get-todo-sequence-head org-state)
12268 ass (assoc head org-todo-kwd-alist)
12269 interpret (nth 1 ass)
12270 done-word (nth 3 ass)
12271 final-done-word (nth 4 ass)))
12272 (when (memq arg '(nextset previousset))
12273 (message "Keyword-Set %d/%d: %s"
12274 (- (length org-todo-sets) -1
12275 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12276 (length org-todo-sets)
12277 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12278 (setq org-last-todo-state-is-todo
12279 (not (member org-state org-done-keywords)))
12280 (setq now-done-p (and (member org-state org-done-keywords)
12281 (not (member this org-done-keywords))))
12282 (and logging (org-local-logging logging))
12283 (when (and (or org-todo-log-states org-log-done)
12284 (not (eq org-inhibit-logging t))
12285 (not (memq arg '(nextset previousset))))
12286 ;; we need to look at recording a time and note
12287 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12288 (nth 2 (assoc this org-todo-log-states))))
12289 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12290 (setq dolog 'time))
12291 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12292 (and org-state
12293 (member org-state org-not-done-keywords)
12294 (not (member this org-not-done-keywords))))
12295 ;; This is now a todo state and was not one before
12296 ;; If there was a CLOSED time stamp, get rid of it.
12297 (org-add-planning-info nil nil 'closed))
12298 (when (and now-done-p org-log-done)
12299 ;; It is now done, and it was not done before
12300 (org-add-planning-info 'closed (org-current-effective-time))
12301 (if (and (not dolog) (eq 'note org-log-done))
12302 (org-add-log-setup 'done org-state this 'findpos 'note)))
12303 (when (and org-state dolog)
12304 ;; This is a non-nil state, and we need to log it
12305 (org-add-log-setup 'state org-state this 'findpos dolog)))
12306 ;; Fixup tag positioning
12307 (org-todo-trigger-tag-changes org-state)
12308 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12309 (when org-provide-todo-statistics
12310 (org-update-parent-todo-statistics))
12311 (run-hooks 'org-after-todo-state-change-hook)
12312 (if (and arg (not (member org-state org-done-keywords)))
12313 (setq head (org-get-todo-sequence-head org-state)))
12314 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12315 ;; Do we need to trigger a repeat?
12316 (when now-done-p
12317 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12318 ;; This is for the agenda, take a snapshot of the headline.
12319 (save-match-data
12320 (setq org-agenda-headline-snapshot-before-repeat
12321 (org-get-heading))))
12322 (org-auto-repeat-maybe org-state))
12323 ;; Fixup cursor location if close to the keyword
12324 (if (and (outline-on-heading-p)
12325 (not (bolp))
12326 (save-excursion (beginning-of-line 1)
12327 (looking-at org-todo-line-regexp))
12328 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12329 (progn
12330 (goto-char (or (match-end 2) (match-end 1)))
12331 (and (looking-at " ") (just-one-space))))
12332 (when org-trigger-hook
12333 (save-excursion
12334 (run-hook-with-args 'org-trigger-hook change-plist)))
12335 (when commentp (org-toggle-comment))))))))
12337 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12338 "Block turning an entry into a TODO, using the hierarchy.
12339 This checks whether the current task should be blocked from state
12340 changes. Such blocking occurs when:
12342 1. The task has children which are not all in a completed state.
12344 2. A task has a parent with the property :ORDERED:, and there
12345 are siblings prior to the current task with incomplete
12346 status.
12348 3. The parent of the task is blocked because it has siblings that should
12349 be done first, or is child of a block grandparent TODO entry."
12351 (if (not org-enforce-todo-dependencies)
12352 t ; if locally turned off don't block
12353 (catch 'dont-block
12354 ;; If this is not a todo state change, or if this entry is already DONE,
12355 ;; do not block
12356 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12357 (member (plist-get change-plist :from)
12358 (cons 'done org-done-keywords))
12359 (member (plist-get change-plist :to)
12360 (cons 'todo org-not-done-keywords))
12361 (not (plist-get change-plist :to)))
12362 (throw 'dont-block t))
12363 ;; If this task has children, and any are undone, it's blocked
12364 (save-excursion
12365 (org-back-to-heading t)
12366 (let ((this-level (funcall outline-level)))
12367 (outline-next-heading)
12368 (let ((child-level (funcall outline-level)))
12369 (while (and (not (eobp))
12370 (> child-level this-level))
12371 ;; this todo has children, check whether they are all
12372 ;; completed
12373 (if (and (not (org-entry-is-done-p))
12374 (org-entry-is-todo-p))
12375 (progn (setq org-block-entry-blocking (org-get-heading))
12376 (throw 'dont-block nil)))
12377 (outline-next-heading)
12378 (setq child-level (funcall outline-level))))))
12379 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12380 ;; any previous siblings are undone, it's blocked
12381 (save-excursion
12382 (org-back-to-heading t)
12383 (let* ((pos (point))
12384 (parent-pos (and (org-up-heading-safe) (point))))
12385 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12386 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12387 (forward-line 1)
12388 (re-search-forward org-not-done-heading-regexp pos t))
12389 (setq org-block-entry-blocking (match-string 0))
12390 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12391 ;; Search further up the hierarchy, to see if an ancestor is blocked
12392 (while t
12393 (goto-char parent-pos)
12394 (if (not (looking-at org-not-done-heading-regexp))
12395 (throw 'dont-block t)) ; do not block, parent is not a TODO
12396 (setq pos (point))
12397 (setq parent-pos (and (org-up-heading-safe) (point)))
12398 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12399 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12400 (forward-line 1)
12401 (re-search-forward org-not-done-heading-regexp pos t)
12402 (setq org-block-entry-blocking (org-get-heading)))
12403 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12405 (defcustom org-track-ordered-property-with-tag nil
12406 "Should the ORDERED property also be shown as a tag?
12407 The ORDERED property decides if an entry should require subtasks to be
12408 completed in sequence. Since a property is not very visible, setting
12409 this option means that toggling the ORDERED property with the command
12410 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12411 not relevant for the behavior, but it makes things more visible.
12413 Note that toggling the tag with tags commands will not change the property
12414 and therefore not influence behavior!
12416 This can be t, meaning the tag ORDERED should be used, It can also be a
12417 string to select a different tag for this task."
12418 :group 'org-todo
12419 :type '(choice
12420 (const :tag "No tracking" nil)
12421 (const :tag "Track with ORDERED tag" t)
12422 (string :tag "Use other tag")))
12424 (defun org-toggle-ordered-property ()
12425 "Toggle the ORDERED property of the current entry.
12426 For better visibility, you can track the value of this property with a tag.
12427 See variable `org-track-ordered-property-with-tag'."
12428 (interactive)
12429 (let* ((t1 org-track-ordered-property-with-tag)
12430 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12431 (save-excursion
12432 (org-back-to-heading)
12433 (if (org-entry-get nil "ORDERED")
12434 (progn
12435 (org-delete-property "ORDERED" "PROPERTIES")
12436 (and tag (org-toggle-tag tag 'off))
12437 (message "Subtasks can be completed in arbitrary order"))
12438 (org-entry-put nil "ORDERED" "t")
12439 (and tag (org-toggle-tag tag 'on))
12440 (message "Subtasks must be completed in sequence")))))
12442 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12443 (defun org-block-todo-from-checkboxes (change-plist)
12444 "Block turning an entry into a TODO, using checkboxes.
12445 This checks whether the current task should be blocked from state
12446 changes because there are unchecked boxes in this entry."
12447 (if (not org-enforce-todo-checkbox-dependencies)
12448 t ; if locally turned off don't block
12449 (catch 'dont-block
12450 ;; If this is not a todo state change, or if this entry is already DONE,
12451 ;; do not block
12452 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12453 (member (plist-get change-plist :from)
12454 (cons 'done org-done-keywords))
12455 (member (plist-get change-plist :to)
12456 (cons 'todo org-not-done-keywords))
12457 (not (plist-get change-plist :to)))
12458 (throw 'dont-block t))
12459 ;; If this task has checkboxes that are not checked, it's blocked
12460 (save-excursion
12461 (org-back-to-heading t)
12462 (let ((beg (point)) end)
12463 (outline-next-heading)
12464 (setq end (point))
12465 (goto-char beg)
12466 (if (org-list-search-forward
12467 (concat (org-item-beginning-re)
12468 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12469 "\\[[- ]\\]")
12470 end t)
12471 (progn
12472 (if (boundp 'org-blocked-by-checkboxes)
12473 (setq org-blocked-by-checkboxes t))
12474 (throw 'dont-block nil)))))
12475 t))) ; do not block
12477 (defun org-entry-blocked-p ()
12478 "Is the current entry blocked?"
12479 (org-with-silent-modifications
12480 (if (org-entry-get nil "NOBLOCKING")
12481 nil ;; Never block this entry
12482 (not (run-hook-with-args-until-failure
12483 'org-blocker-hook
12484 (list :type 'todo-state-change
12485 :position (point)
12486 :from 'todo
12487 :to 'done))))))
12489 (defun org-update-statistics-cookies (all)
12490 "Update the statistics cookie, either from TODO or from checkboxes.
12491 This should be called with the cursor in a line with a statistics cookie."
12492 (interactive "P")
12493 (if all
12494 (progn
12495 (org-update-checkbox-count 'all)
12496 (org-map-entries 'org-update-parent-todo-statistics))
12497 (if (not (org-at-heading-p))
12498 (org-update-checkbox-count)
12499 (let ((pos (point-marker))
12500 end l1 l2)
12501 (ignore-errors (org-back-to-heading t))
12502 (if (not (org-at-heading-p))
12503 (org-update-checkbox-count)
12504 (setq l1 (org-outline-level))
12505 (setq end (save-excursion
12506 (outline-next-heading)
12507 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12508 (point)))
12509 (if (and (save-excursion
12510 (re-search-forward
12511 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12512 (not (save-excursion (re-search-forward
12513 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12514 (org-update-checkbox-count)
12515 (if (and l2 (> l2 l1))
12516 (progn
12517 (goto-char end)
12518 (org-update-parent-todo-statistics))
12519 (goto-char pos)
12520 (beginning-of-line 1)
12521 (while (re-search-forward
12522 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12523 (point-at-eol) t)
12524 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12525 (goto-char pos)
12526 (move-marker pos nil)))))
12528 (defvar org-entry-property-inherited-from) ;; defined below
12529 (defun org-update-parent-todo-statistics ()
12530 "Update any statistics cookie in the parent of the current headline.
12531 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12532 the entire subtree and this will travel up the hierarchy and update
12533 statistics everywhere."
12534 (let* ((prop (save-excursion (org-up-heading-safe)
12535 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12536 (recursive (or (not org-hierarchical-todo-statistics)
12537 (and prop (string-match "\\<recursive\\>" prop))))
12538 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12540 (first t)
12541 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12542 level ltoggle l1 new ndel
12543 (cnt-all 0) (cnt-done 0) is-percent kwd
12544 checkbox-beg ov ovs ove cookie-present)
12545 (catch 'exit
12546 (save-excursion
12547 (beginning-of-line 1)
12548 (setq ltoggle (funcall outline-level))
12549 ;; Three situations are to consider:
12551 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12552 ;; to the top-level ancestor on the headline;
12554 ;; 2. If parent has "recursive" property, repeat up to the
12555 ;; headline setting that property, taking inheritance into
12556 ;; account;
12558 ;; 3. Else, move up to direct parent and proceed only once.
12559 (while (and (setq level (org-up-heading-safe))
12560 (or recursive first)
12561 (>= (point) lim))
12562 (setq first nil cookie-present nil)
12563 (unless (and level
12564 (not (string-match
12565 "\\<checkbox\\>"
12566 (downcase (or (org-entry-get nil "COOKIE_DATA")
12567 "")))))
12568 (throw 'exit nil))
12569 (while (re-search-forward box-re (point-at-eol) t)
12570 (setq cnt-all 0 cnt-done 0 cookie-present t)
12571 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12572 (save-match-data
12573 (unless (outline-next-heading) (throw 'exit nil))
12574 (while (and (looking-at org-complex-heading-regexp)
12575 (> (setq l1 (length (match-string 1))) level))
12576 (setq kwd (and (or recursive (= l1 ltoggle))
12577 (match-string 2)))
12578 (if (or (eq org-provide-todo-statistics 'all-headlines)
12579 (and (listp org-provide-todo-statistics)
12580 (or (member kwd org-provide-todo-statistics)
12581 (member kwd org-done-keywords))))
12582 (setq cnt-all (1+ cnt-all))
12583 (if (eq org-provide-todo-statistics t)
12584 (and kwd (setq cnt-all (1+ cnt-all)))))
12585 (and (member kwd org-done-keywords)
12586 (setq cnt-done (1+ cnt-done)))
12587 (outline-next-heading)))
12588 (setq new
12589 (if is-percent
12590 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12591 (format "[%d/%d]" cnt-done cnt-all))
12592 ndel (- (match-end 0) checkbox-beg))
12593 ;; handle overlays when updating cookie from column view
12594 (when (setq ov (car (overlays-at checkbox-beg)))
12595 (setq ovs (overlay-start ov) ove (overlay-end ov))
12596 (delete-overlay ov))
12597 (goto-char checkbox-beg)
12598 (insert new)
12599 (delete-region (point) (+ (point) ndel))
12600 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12601 (when ov (move-overlay ov ovs ove)))
12602 (when cookie-present
12603 (run-hook-with-args 'org-after-todo-statistics-hook
12604 cnt-done (- cnt-all cnt-done))))))
12605 (run-hooks 'org-todo-statistics-hook)))
12607 (defvar org-after-todo-statistics-hook nil
12608 "Hook that is called after a TODO statistics cookie has been updated.
12609 Each function is called with two arguments: the number of not-done entries
12610 and the number of done entries.
12612 For example, the following function, when added to this hook, will switch
12613 an entry to DONE when all children are done, and back to TODO when new
12614 entries are set to a TODO status. Note that this hook is only called
12615 when there is a statistics cookie in the headline!
12617 (defun org-summary-todo (n-done n-not-done)
12618 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12619 (let (org-log-done org-log-states) ; turn off logging
12620 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12623 (defvar org-todo-statistics-hook nil
12624 "Hook that is run whenever Org thinks TODO statistics should be updated.
12625 This hook runs even if there is no statistics cookie present, in which case
12626 `org-after-todo-statistics-hook' would not run.")
12628 (defun org-todo-trigger-tag-changes (state)
12629 "Apply the changes defined in `org-todo-state-tags-triggers'."
12630 (let ((l org-todo-state-tags-triggers)
12631 changes)
12632 (when (or (not state) (equal state ""))
12633 (setq changes (append changes (cdr (assoc "" l)))))
12634 (when (and (stringp state) (> (length state) 0))
12635 (setq changes (append changes (cdr (assoc state l)))))
12636 (when (member state org-not-done-keywords)
12637 (setq changes (append changes (cdr (assoc 'todo l)))))
12638 (when (member state org-done-keywords)
12639 (setq changes (append changes (cdr (assoc 'done l)))))
12640 (dolist (c changes)
12641 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12643 (defun org-local-logging (value)
12644 "Get logging settings from a property VALUE."
12645 (let* (words w a)
12646 ;; directly set the variables, they are already local.
12647 (setq org-log-done nil
12648 org-log-repeat nil
12649 org-todo-log-states nil)
12650 (setq words (org-split-string value))
12651 (while (setq w (pop words))
12652 (cond
12653 ((setq a (assoc w org-startup-options))
12654 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12655 (set (nth 1 a) (nth 2 a))))
12656 ((setq a (org-extract-log-state-settings w))
12657 (and (member (car a) org-todo-keywords-1)
12658 (push a org-todo-log-states)))))))
12660 (defun org-get-todo-sequence-head (kwd)
12661 "Return the head of the TODO sequence to which KWD belongs.
12662 If KWD is not set, check if there is a text property remembering the
12663 right sequence."
12664 (let (p)
12665 (cond
12666 ((not kwd)
12667 (or (get-text-property (point-at-bol) 'org-todo-head)
12668 (progn
12669 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12670 nil (point-at-eol)))
12671 (get-text-property p 'org-todo-head))))
12672 ((not (member kwd org-todo-keywords-1))
12673 (car org-todo-keywords-1))
12674 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12676 (defun org-fast-todo-selection ()
12677 "Fast TODO keyword selection with single keys.
12678 Returns the new TODO keyword, or nil if no state change should occur."
12679 (let* ((fulltable org-todo-key-alist)
12680 (done-keywords org-done-keywords) ;; needed for the faces.
12681 (maxlen (apply 'max (mapcar
12682 (lambda (x)
12683 (if (stringp (car x)) (string-width (car x)) 0))
12684 fulltable)))
12685 (expert nil)
12686 (fwidth (+ maxlen 3 1 3))
12687 (ncol (/ (- (window-width) 4) fwidth))
12688 tg cnt e c tbl
12689 groups ingroup)
12690 (save-excursion
12691 (save-window-excursion
12692 (if expert
12693 (set-buffer (get-buffer-create " *Org todo*"))
12694 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12695 (erase-buffer)
12696 (org-set-local 'org-done-keywords done-keywords)
12697 (setq tbl fulltable cnt 0)
12698 (while (setq e (pop tbl))
12699 (cond
12700 ((equal e '(:startgroup))
12701 (push '() groups) (setq ingroup t)
12702 (when (not (= cnt 0))
12703 (setq cnt 0)
12704 (insert "\n"))
12705 (insert "{ "))
12706 ((equal e '(:endgroup))
12707 (setq ingroup nil cnt 0)
12708 (insert "}\n"))
12709 ((equal e '(:newline))
12710 (when (not (= cnt 0))
12711 (setq cnt 0)
12712 (insert "\n")
12713 (setq e (car tbl))
12714 (while (equal (car tbl) '(:newline))
12715 (insert "\n")
12716 (setq tbl (cdr tbl)))))
12718 (setq tg (car e) c (cdr e))
12719 (if ingroup (push tg (car groups)))
12720 (setq tg (org-add-props tg nil 'face
12721 (org-get-todo-face tg)))
12722 (if (and (= cnt 0) (not ingroup)) (insert " "))
12723 (insert "[" c "] " tg (make-string
12724 (- fwidth 4 (length tg)) ?\ ))
12725 (when (= (setq cnt (1+ cnt)) ncol)
12726 (insert "\n")
12727 (if ingroup (insert " "))
12728 (setq cnt 0)))))
12729 (insert "\n")
12730 (goto-char (point-min))
12731 (if (not expert) (org-fit-window-to-buffer))
12732 (message "[a-z..]:Set [SPC]:clear")
12733 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12734 (cond
12735 ((or (= c ?\C-g)
12736 (and (= c ?q) (not (rassoc c fulltable))))
12737 (setq quit-flag t))
12738 ((= c ?\ ) nil)
12739 ((setq e (rassoc c fulltable) tg (car e))
12741 (t (setq quit-flag t)))))))
12743 (defun org-entry-is-todo-p ()
12744 (member (org-get-todo-state) org-not-done-keywords))
12746 (defun org-entry-is-done-p ()
12747 (member (org-get-todo-state) org-done-keywords))
12749 (defun org-get-todo-state ()
12750 "Return the TODO keyword of the current subtree."
12751 (save-excursion
12752 (org-back-to-heading t)
12753 (and (looking-at org-todo-line-regexp)
12754 (match-end 2)
12755 (match-string 2))))
12757 (defun org-at-date-range-p (&optional inactive-ok)
12758 "Is the cursor inside a date range?"
12759 (interactive)
12760 (save-excursion
12761 (catch 'exit
12762 (let ((pos (point)))
12763 (skip-chars-backward "^[<\r\n")
12764 (skip-chars-backward "<[")
12765 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12766 (>= (match-end 0) pos)
12767 (throw 'exit t))
12768 (skip-chars-backward "^<[\r\n")
12769 (skip-chars-backward "<[")
12770 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12771 (>= (match-end 0) pos)
12772 (throw 'exit t)))
12773 nil)))
12775 (defun org-get-repeat (&optional tagline)
12776 "Check if there is a deadline/schedule with repeater in this entry."
12777 (save-match-data
12778 (save-excursion
12779 (org-back-to-heading t)
12780 (and (re-search-forward (if tagline
12781 (concat tagline "\\s-*" org-repeat-re)
12782 org-repeat-re)
12783 (org-entry-end-position) t)
12784 (match-string-no-properties 1)))))
12786 (defvar org-last-changed-timestamp)
12787 (defvar org-last-inserted-timestamp)
12788 (defvar org-log-post-message)
12789 (defvar org-log-note-purpose)
12790 (defvar org-log-note-how)
12791 (defvar org-log-note-extra)
12792 (defun org-auto-repeat-maybe (done-word)
12793 "Check if the current headline contains a repeated deadline/schedule.
12794 If yes, set TODO state back to what it was and change the base date
12795 of repeating deadline/scheduled time stamps to new date.
12796 This function is run automatically after each state change to a DONE state."
12797 ;; last-state is dynamically scoped into this function
12798 (let* ((repeat (org-get-repeat))
12799 (aa (assoc org-last-state org-todo-kwd-alist))
12800 (interpret (nth 1 aa))
12801 (head (nth 2 aa))
12802 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12803 (msg "Entry repeats: ")
12804 (org-log-done nil)
12805 (org-todo-log-states nil)
12806 re type n what ts time to-state)
12807 (when repeat
12808 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12809 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12810 org-todo-repeat-to-state))
12811 (unless (and to-state (member to-state org-todo-keywords-1))
12812 (setq to-state (if (eq interpret 'type) org-last-state head)))
12813 (org-todo to-state)
12814 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12815 (org-entry-put nil "LAST_REPEAT" (format-time-string
12816 (org-time-stamp-format t t))))
12817 (when org-log-repeat
12818 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12819 (memq 'org-add-log-note post-command-hook))
12820 ;; OK, we are already setup for some record
12821 (if (eq org-log-repeat 'note)
12822 ;; make sure we take a note, not only a time stamp
12823 (setq org-log-note-how 'note))
12824 ;; Set up for taking a record
12825 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12826 org-last-state
12827 'findpos org-log-repeat)))
12828 (org-back-to-heading t)
12829 (org-add-planning-info nil nil 'closed)
12830 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12831 org-deadline-time-regexp "\\)\\|\\("
12832 org-ts-regexp "\\)"))
12833 (while (re-search-forward
12834 re (save-excursion (outline-next-heading) (point)) t)
12835 (setq type (if (match-end 1) org-scheduled-string
12836 (if (match-end 3) org-deadline-string "Plain:"))
12837 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12838 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12839 (setq n (string-to-number (match-string 2 ts))
12840 what (match-string 3 ts))
12841 (if (equal what "w") (setq n (* n 7) what "d"))
12842 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12843 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12844 ;; Preparation, see if we need to modify the start date for the change
12845 (when (match-end 1)
12846 (setq time (save-match-data (org-time-string-to-time ts)))
12847 (cond
12848 ((equal (match-string 1 ts) ".")
12849 ;; Shift starting date to today
12850 (org-timestamp-change
12851 (- (org-today) (time-to-days time))
12852 'day))
12853 ((equal (match-string 1 ts) "+")
12854 (let ((nshiftmax 10) (nshift 0))
12855 (while (or (= nshift 0)
12856 (<= (time-to-days time)
12857 (time-to-days (current-time))))
12858 (when (= (incf nshift) nshiftmax)
12859 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12860 (error "Abort")))
12861 (org-timestamp-change n (cdr (assoc what whata)))
12862 (org-at-timestamp-p t)
12863 (setq ts (match-string 1))
12864 (setq time (save-match-data (org-time-string-to-time ts)))))
12865 (org-timestamp-change (- n) (cdr (assoc what whata)))
12866 ;; rematch, so that we have everything in place for the real shift
12867 (org-at-timestamp-p t)
12868 (setq ts (match-string 1))
12869 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12870 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12871 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12872 (setq org-log-post-message msg)
12873 (message "%s" msg))))
12875 (defun org-show-todo-tree (arg)
12876 "Make a compact tree which shows all headlines marked with TODO.
12877 The tree will show the lines where the regexp matches, and all higher
12878 headlines above the match.
12879 With a \\[universal-argument] prefix, prompt for a regexp to match.
12880 With a numeric prefix N, construct a sparse tree for the Nth element
12881 of `org-todo-keywords-1'."
12882 (interactive "P")
12883 (let ((case-fold-search nil)
12884 (kwd-re
12885 (cond ((null arg) org-not-done-regexp)
12886 ((equal arg '(4))
12887 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12888 (mapcar 'list org-todo-keywords-1))))
12889 (concat "\\("
12890 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12891 "\\)\\>")))
12892 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12893 (regexp-quote (nth (1- (prefix-numeric-value arg))
12894 org-todo-keywords-1)))
12895 (t (user-error "Invalid prefix argument: %s" arg)))))
12896 (message "%d TODO entries found"
12897 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12899 (defun org-deadline (arg &optional time)
12900 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12901 With one universal prefix argument, remove any deadline from the item.
12902 With two universal prefix arguments, prompt for a warning delay.
12903 With argument TIME, set the deadline at the corresponding date. TIME
12904 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12905 (interactive "P")
12906 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12907 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12908 'region-start-level 'region))
12909 org-loop-over-headlines-in-active-region)
12910 (org-map-entries
12911 `(org-deadline ',arg ,time)
12912 org-loop-over-headlines-in-active-region
12913 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12914 (let* ((old-date (org-entry-get nil "DEADLINE"))
12915 (old-date-time (if old-date (org-time-string-to-time old-date)))
12916 (repeater (and old-date
12917 (string-match
12918 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12919 old-date)
12920 (match-string 1 old-date))))
12921 (cond
12922 ((equal arg '(4))
12923 (when (and old-date org-log-redeadline)
12924 (org-add-log-setup 'deldeadline nil old-date 'findpos
12925 org-log-redeadline))
12926 (org-remove-timestamp-with-keyword org-deadline-string)
12927 (message "Item no longer has a deadline."))
12928 ((equal arg '(16))
12929 (save-excursion
12930 (if (re-search-forward
12931 org-deadline-time-regexp
12932 (save-excursion (outline-next-heading) (point)) t)
12933 (let* ((rpl0 (match-string 1))
12934 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12935 (replace-match
12936 (concat org-deadline-string
12937 " <" rpl
12938 (format " -%dd"
12939 (abs
12940 (- (time-to-days
12941 (save-match-data
12942 (org-read-date nil t nil "Warn starting from" old-date-time)))
12943 (time-to-days old-date-time))))
12944 ">") t t))
12945 (user-error "No deadline information to update"))))
12947 (org-add-planning-info 'deadline time 'closed)
12948 (when (and old-date org-log-redeadline
12949 (not (equal old-date
12950 (substring org-last-inserted-timestamp 1 -1))))
12951 (org-add-log-setup 'redeadline nil old-date 'findpos
12952 org-log-redeadline))
12953 (when repeater
12954 (save-excursion
12955 (org-back-to-heading t)
12956 (when (re-search-forward (concat org-deadline-string " "
12957 org-last-inserted-timestamp)
12958 (save-excursion
12959 (outline-next-heading) (point)) t)
12960 (goto-char (1- (match-end 0)))
12961 (insert " " repeater)
12962 (setq org-last-inserted-timestamp
12963 (concat (substring org-last-inserted-timestamp 0 -1)
12964 " " repeater
12965 (substring org-last-inserted-timestamp -1))))))
12966 (message "Deadline on %s" org-last-inserted-timestamp))))))
12968 (defun org-schedule (arg &optional time)
12969 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12970 With one universal prefix argument, remove any scheduling date from the item.
12971 With two universal prefix arguments, prompt for a delay cookie.
12972 With argument TIME, scheduled at the corresponding date. TIME can
12973 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12974 (interactive "P")
12975 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12976 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12977 'region-start-level 'region))
12978 org-loop-over-headlines-in-active-region)
12979 (org-map-entries
12980 `(org-schedule ',arg ,time)
12981 org-loop-over-headlines-in-active-region
12982 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12983 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12984 (old-date-time (if old-date (org-time-string-to-time old-date)))
12985 (repeater (and old-date
12986 (string-match
12987 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12988 old-date)
12989 (match-string 1 old-date))))
12990 (cond
12991 ((equal arg '(4))
12992 (progn
12993 (when (and old-date org-log-reschedule)
12994 (org-add-log-setup 'delschedule nil old-date 'findpos
12995 org-log-reschedule))
12996 (org-remove-timestamp-with-keyword org-scheduled-string)
12997 (message "Item is no longer scheduled.")))
12998 ((equal arg '(16))
12999 (save-excursion
13000 (if (re-search-forward
13001 org-scheduled-time-regexp
13002 (save-excursion (outline-next-heading) (point)) t)
13003 (let* ((rpl0 (match-string 1))
13004 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13005 (replace-match
13006 (concat org-scheduled-string
13007 " <" rpl
13008 (format " -%dd"
13009 (abs
13010 (- (time-to-days
13011 (save-match-data
13012 (org-read-date nil t nil "Delay until" old-date-time)))
13013 (time-to-days old-date-time))))
13014 ">") t t))
13015 (user-error "No scheduled information to update"))))
13017 (org-add-planning-info 'scheduled time 'closed)
13018 (when (and old-date org-log-reschedule
13019 (not (equal old-date
13020 (substring org-last-inserted-timestamp 1 -1))))
13021 (org-add-log-setup 'reschedule nil old-date 'findpos
13022 org-log-reschedule))
13023 (when repeater
13024 (save-excursion
13025 (org-back-to-heading t)
13026 (when (re-search-forward (concat org-scheduled-string " "
13027 org-last-inserted-timestamp)
13028 (save-excursion
13029 (outline-next-heading) (point)) t)
13030 (goto-char (1- (match-end 0)))
13031 (insert " " repeater)
13032 (setq org-last-inserted-timestamp
13033 (concat (substring org-last-inserted-timestamp 0 -1)
13034 " " repeater
13035 (substring org-last-inserted-timestamp -1))))))
13036 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13038 (defun org-get-scheduled-time (pom &optional inherit)
13039 "Get the scheduled time as a time tuple, of a format suitable
13040 for calling org-schedule with, or if there is no scheduling,
13041 returns nil."
13042 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13043 (when time
13044 (apply 'encode-time (org-parse-time-string time)))))
13046 (defun org-get-deadline-time (pom &optional inherit)
13047 "Get the deadline as a time tuple, of a format suitable for
13048 calling org-deadline with, or if there is no scheduling, returns
13049 nil."
13050 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13051 (when time
13052 (apply 'encode-time (org-parse-time-string time)))))
13054 (defun org-remove-timestamp-with-keyword (keyword)
13055 "Remove all time stamps with KEYWORD in the current entry."
13056 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13057 beg)
13058 (save-excursion
13059 (org-back-to-heading t)
13060 (setq beg (point))
13061 (outline-next-heading)
13062 (while (re-search-backward re beg t)
13063 (replace-match "")
13064 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13065 (equal (char-before) ?\ ))
13066 (backward-delete-char 1)
13067 (if (string-match "^[ \t]*$" (buffer-substring
13068 (point-at-bol) (point-at-eol)))
13069 (delete-region (point-at-bol)
13070 (min (point-max) (1+ (point-at-eol))))))))))
13072 (defun org-add-planning-info (what &optional time &rest remove)
13073 "Insert new timestamp with keyword in the line directly after the headline.
13074 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13075 If non is given, the user is prompted for a date.
13076 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13077 be removed."
13078 (interactive)
13079 (let (org-time-was-given org-end-time-was-given ts
13080 end default-time default-input)
13082 (catch 'exit
13083 (when (and (memq what '(scheduled deadline))
13084 (or (not time)
13085 (and (stringp time)
13086 (string-match "^[-+]+[0-9]" time))))
13087 ;; Try to get a default date/time from existing timestamp
13088 (save-excursion
13089 (org-back-to-heading t)
13090 (setq end (save-excursion (outline-next-heading) (point)))
13091 (when (re-search-forward (if (eq what 'scheduled)
13092 org-scheduled-time-regexp
13093 org-deadline-time-regexp)
13094 end t)
13095 (setq ts (match-string 1)
13096 default-time
13097 (apply 'encode-time (org-parse-time-string ts))
13098 default-input (and ts (org-get-compact-tod ts))))))
13099 (when what
13100 (setq time
13101 (if (stringp time)
13102 ;; This is a string (relative or absolute), set proper date
13103 (apply 'encode-time
13104 (org-read-date-analyze
13105 time default-time (decode-time default-time)))
13106 ;; If necessary, get the time from the user
13107 (or time (org-read-date nil 'to-time nil nil
13108 default-time default-input)))))
13110 (when (and org-insert-labeled-timestamps-at-point
13111 (member what '(scheduled deadline)))
13112 (insert
13113 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13114 (org-insert-time-stamp time org-time-was-given
13115 nil nil nil (list org-end-time-was-given))
13116 (setq what nil))
13117 (save-excursion
13118 (save-restriction
13119 (let (col list elt ts buffer-invisibility-spec)
13120 (org-back-to-heading t)
13121 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13122 (goto-char (match-end 1))
13123 (setq col (current-column))
13124 (goto-char (match-end 0))
13125 (if (eobp) (insert "\n") (forward-char 1))
13126 (when (and (not what)
13127 (not (looking-at
13128 (concat "[ \t]*"
13129 org-keyword-time-not-clock-regexp))))
13130 ;; Nothing to add, nothing to remove...... :-)
13131 (throw 'exit nil))
13132 (if (and (not (looking-at org-outline-regexp))
13133 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13134 "[^\r\n]*"))
13135 (not (equal (match-string 1) org-clock-string)))
13136 (narrow-to-region (match-beginning 0) (match-end 0))
13137 (insert-before-markers "\n")
13138 (backward-char 1)
13139 (narrow-to-region (point) (point))
13140 (and org-adapt-indentation (org-indent-to-column col)))
13141 ;; Check if we have to remove something.
13142 (setq list (cons what remove))
13143 (while list
13144 (setq elt (pop list))
13145 (when (or (and (eq elt 'scheduled)
13146 (re-search-forward org-scheduled-time-regexp nil t))
13147 (and (eq elt 'deadline)
13148 (re-search-forward org-deadline-time-regexp nil t))
13149 (and (eq elt 'closed)
13150 (re-search-forward org-closed-time-regexp nil t)))
13151 (replace-match "")
13152 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13153 (and (looking-at "[ \t]+") (replace-match ""))
13154 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13155 (when what
13156 (insert
13157 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13158 (cond ((eq what 'scheduled) org-scheduled-string)
13159 ((eq what 'deadline) org-deadline-string)
13160 ((eq what 'closed) org-closed-string))
13161 " ")
13162 (setq ts (org-insert-time-stamp
13163 time
13164 (or org-time-was-given
13165 (and (eq what 'closed) org-log-done-with-time))
13166 (eq what 'closed)
13167 nil nil (list org-end-time-was-given)))
13168 (insert
13169 (if (not (or (bolp) (eq (char-before) ?\ )
13170 (memq (char-after) '(32 10))
13171 (eobp))) " " ""))
13172 (end-of-line 1))
13173 (goto-char (point-min))
13174 (widen)
13175 (if (and (looking-at "[ \t]*\n")
13176 (equal (char-before) ?\n))
13177 (delete-region (1- (point)) (point-at-eol)))
13178 ts))))))
13180 (defvar org-log-note-marker (make-marker))
13181 (defvar org-log-note-purpose nil)
13182 (defvar org-log-note-state nil)
13183 (defvar org-log-note-previous-state nil)
13184 (defvar org-log-note-how nil)
13185 (defvar org-log-note-extra nil)
13186 (defvar org-log-note-window-configuration nil)
13187 (defvar org-log-note-return-to (make-marker))
13188 (defvar org-log-note-effective-time nil
13189 "Remembered current time so that dynamically scoped
13190 `org-extend-today-until' affects tha timestamps in state change
13191 log")
13193 (defvar org-log-post-message nil
13194 "Message to be displayed after a log note has been stored.
13195 The auto-repeater uses this.")
13197 (defun org-add-note ()
13198 "Add a note to the current entry.
13199 This is done in the same way as adding a state change note."
13200 (interactive)
13201 (org-add-log-setup 'note nil nil 'findpos nil))
13203 (defvar org-property-end-re)
13204 (defun org-add-log-setup (&optional purpose state prev-state
13205 findpos how extra)
13206 "Set up the post command hook to take a note.
13207 If this is about to TODO state change, the new state is expected in STATE.
13208 When FINDPOS is non-nil, find the correct position for the note in
13209 the current entry. If not, assume that it can be inserted at point.
13210 HOW is an indicator what kind of note should be created.
13211 EXTRA is additional text that will be inserted into the notes buffer."
13212 (let* ((org-log-into-drawer (org-log-into-drawer))
13213 (drawer (cond ((stringp org-log-into-drawer)
13214 org-log-into-drawer)
13215 (org-log-into-drawer "LOGBOOK"))))
13216 (save-restriction
13217 (save-excursion
13218 (when findpos
13219 (org-back-to-heading t)
13220 (narrow-to-region (point) (save-excursion
13221 (outline-next-heading) (point)))
13222 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13223 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13224 "[^\r\n]*\\)?"))
13225 (goto-char (match-end 0))
13226 (cond
13227 (drawer
13228 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13229 nil t)
13230 (progn
13231 (goto-char (match-end 0))
13232 (or org-log-states-order-reversed
13233 (and (re-search-forward org-property-end-re nil t)
13234 (goto-char (1- (match-beginning 0))))))
13235 (insert "\n:" drawer ":\n:END:")
13236 (beginning-of-line 0)
13237 (org-indent-line)
13238 (beginning-of-line 2)
13239 (org-indent-line)
13240 (end-of-line 0)))
13241 ((and org-log-state-notes-insert-after-drawers
13242 (save-excursion
13243 (forward-line) (looking-at org-drawer-regexp)))
13244 (forward-line)
13245 (while (looking-at org-drawer-regexp)
13246 (goto-char (match-end 0))
13247 (re-search-forward org-property-end-re (point-max) t)
13248 (forward-line))
13249 (forward-line -1)))
13250 (unless org-log-states-order-reversed
13251 (and (= (char-after) ?\n) (forward-char 1))
13252 (org-skip-over-state-notes)
13253 (skip-chars-backward " \t\n\r")))
13254 (move-marker org-log-note-marker (point))
13255 (setq org-log-note-purpose purpose
13256 org-log-note-state state
13257 org-log-note-previous-state prev-state
13258 org-log-note-how how
13259 org-log-note-extra extra
13260 org-log-note-effective-time (org-current-effective-time))
13261 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13263 (defun org-skip-over-state-notes ()
13264 "Skip past the list of State notes in an entry."
13265 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13266 (when (ignore-errors (goto-char (org-in-item-p)))
13267 (let* ((struct (org-list-struct))
13268 (prevs (org-list-prevs-alist struct)))
13269 (while (looking-at "[ \t]*- State")
13270 (goto-char (or (org-list-get-next-item (point) struct prevs)
13271 (org-list-get-item-end (point) struct)))))))
13273 (defun org-add-log-note (&optional purpose)
13274 "Pop up a window for taking a note, and add this note later at point."
13275 (remove-hook 'post-command-hook 'org-add-log-note)
13276 (setq org-log-note-window-configuration (current-window-configuration))
13277 (delete-other-windows)
13278 (move-marker org-log-note-return-to (point))
13279 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13280 (goto-char org-log-note-marker)
13281 (org-switch-to-buffer-other-window "*Org Note*")
13282 (erase-buffer)
13283 (if (memq org-log-note-how '(time state))
13284 (let (current-prefix-arg) (org-store-log-note))
13285 (let ((org-inhibit-startup t)) (org-mode))
13286 (insert (format "# Insert note for %s.
13287 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13288 (cond
13289 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13290 ((eq org-log-note-purpose 'done) "closed todo item")
13291 ((eq org-log-note-purpose 'state)
13292 (format "state change from \"%s\" to \"%s\""
13293 (or org-log-note-previous-state "")
13294 (or org-log-note-state "")))
13295 ((eq org-log-note-purpose 'reschedule)
13296 "rescheduling")
13297 ((eq org-log-note-purpose 'delschedule)
13298 "no longer scheduled")
13299 ((eq org-log-note-purpose 'redeadline)
13300 "changing deadline")
13301 ((eq org-log-note-purpose 'deldeadline)
13302 "removing deadline")
13303 ((eq org-log-note-purpose 'refile)
13304 "refiling")
13305 ((eq org-log-note-purpose 'note)
13306 "this entry")
13307 (t (error "This should not happen")))))
13308 (if org-log-note-extra (insert org-log-note-extra))
13309 (org-set-local 'org-finish-function 'org-store-log-note)
13310 (run-hooks 'org-log-buffer-setup-hook)))
13312 (defvar org-note-abort nil) ; dynamically scoped
13313 (defun org-store-log-note ()
13314 "Finish taking a log note, and insert it to where it belongs."
13315 (let ((txt (buffer-string)))
13316 (kill-buffer (current-buffer))
13317 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13318 lines ind bul)
13319 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13320 (setq txt (replace-match "" t t txt)))
13321 (if (string-match "\\s-+\\'" txt)
13322 (setq txt (replace-match "" t t txt)))
13323 (setq lines (org-split-string txt "\n"))
13324 (when (and note (string-match "\\S-" note))
13325 (setq note
13326 (org-replace-escapes
13327 note
13328 (list (cons "%u" (user-login-name))
13329 (cons "%U" user-full-name)
13330 (cons "%t" (format-time-string
13331 (org-time-stamp-format 'long 'inactive)
13332 org-log-note-effective-time))
13333 (cons "%T" (format-time-string
13334 (org-time-stamp-format 'long nil)
13335 org-log-note-effective-time))
13336 (cons "%d" (format-time-string
13337 (org-time-stamp-format nil 'inactive)
13338 org-log-note-effective-time))
13339 (cons "%D" (format-time-string
13340 (org-time-stamp-format nil nil)
13341 org-log-note-effective-time))
13342 (cons "%s" (if org-log-note-state
13343 (concat "\"" org-log-note-state "\"")
13344 ""))
13345 (cons "%S" (if org-log-note-previous-state
13346 (concat "\"" org-log-note-previous-state "\"")
13347 "\"\"")))))
13348 (if lines (setq note (concat note " \\\\")))
13349 (push note lines))
13350 (when (or current-prefix-arg org-note-abort)
13351 (when org-log-into-drawer
13352 (org-remove-empty-drawer-at
13353 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13354 org-log-note-marker))
13355 (setq lines nil))
13356 (when lines
13357 (with-current-buffer (marker-buffer org-log-note-marker)
13358 (save-excursion
13359 (goto-char org-log-note-marker)
13360 (move-marker org-log-note-marker nil)
13361 (end-of-line 1)
13362 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13363 (setq ind (save-excursion
13364 (if (ignore-errors (goto-char (org-in-item-p)))
13365 (let ((struct (org-list-struct)))
13366 (org-list-get-ind
13367 (org-list-get-top-point struct) struct))
13368 (skip-chars-backward " \r\t\n")
13369 (cond
13370 ((and (org-at-heading-p)
13371 org-adapt-indentation)
13372 (1+ (org-current-level)))
13373 ((org-at-heading-p) 0)
13374 (t (org-get-indentation))))))
13375 (setq bul (org-list-bullet-string "-"))
13376 (org-indent-line-to ind)
13377 (insert bul (pop lines))
13378 (let ((ind-body (+ (length bul) ind)))
13379 (while lines
13380 (insert "\n")
13381 (org-indent-line-to ind-body)
13382 (insert (pop lines))))
13383 (message "Note stored")
13384 (org-back-to-heading t)
13385 (org-cycle-hide-drawers 'children))
13386 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13387 ;; from within `org-add-log-note' because `buffer-undo-list'
13388 ;; is then modified outside of `org-with-remote-undo'.
13389 (when (eq this-command 'org-agenda-todo)
13390 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13391 ;; Don't add undo information when called from `org-agenda-todo'
13392 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13393 (set-window-configuration org-log-note-window-configuration)
13394 (with-current-buffer (marker-buffer org-log-note-return-to)
13395 (goto-char org-log-note-return-to))
13396 (move-marker org-log-note-return-to nil)
13397 (and org-log-post-message (message "%s" org-log-post-message))))
13399 (defun org-remove-empty-drawer-at (drawer pos)
13400 "Remove an empty drawer DRAWER at position POS.
13401 POS may also be a marker."
13402 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13403 (save-excursion
13404 (save-restriction
13405 (widen)
13406 (goto-char pos)
13407 (if (org-in-regexp
13408 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13409 (replace-match ""))))))
13411 (defvar org-ts-type nil)
13412 (defun org-sparse-tree (&optional arg type)
13413 "Create a sparse tree, prompt for the details.
13414 This command can create sparse trees. You first need to select the type
13415 of match used to create the tree:
13417 t Show all TODO entries.
13418 T Show entries with a specific TODO keyword.
13419 m Show entries selected by a tags/property match.
13420 p Enter a property name and its value (both with completion on existing
13421 names/values) and show entries with that property.
13422 r Show entries matching a regular expression (`/' can be used as well).
13423 b Show deadlines and scheduled items before a date.
13424 a Show deadlines and scheduled items after a date.
13425 d Show deadlines due within `org-deadline-warning-days'.
13426 D Show deadlines and scheduled items between a date range."
13427 (interactive "P")
13428 (let (ans kwd value ts-type)
13429 (setq type (or type org-sparse-tree-default-date-type))
13430 (setq org-ts-type type)
13431 (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"
13432 (cond ((eq type 'all) "all timestamps")
13433 ((eq type 'scheduled) "only scheduled")
13434 ((eq type 'deadline) "only deadline")
13435 ((eq type 'active) "only active timestamps")
13436 ((eq type 'inactive) "only inactive timestamps")
13437 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13438 ((eq type 'closed) "with a closed time-stamp")
13439 (t "scheduled/deadline")))
13440 (setq ans (read-char-exclusive))
13441 (cond
13442 ((equal ans ?c)
13443 (org-sparse-tree
13444 arg (cadr (member type '(scheduled-or-deadline
13445 all scheduled deadline active inactive closed)))))
13446 ((equal ans ?d)
13447 (call-interactively 'org-check-deadlines))
13448 ((equal ans ?b)
13449 (call-interactively 'org-check-before-date))
13450 ((equal ans ?a)
13451 (call-interactively 'org-check-after-date))
13452 ((equal ans ?D)
13453 (call-interactively 'org-check-dates-range))
13454 ((equal ans ?t)
13455 (call-interactively 'org-show-todo-tree))
13456 ((equal ans ?T)
13457 (org-show-todo-tree '(4)))
13458 ((member ans '(?T ?m))
13459 (call-interactively 'org-match-sparse-tree))
13460 ((member ans '(?p ?P))
13461 (setq kwd (org-icompleting-read "Property: "
13462 (mapcar 'list (org-buffer-property-keys))))
13463 (setq value (org-icompleting-read "Value: "
13464 (mapcar 'list (org-property-values kwd))))
13465 (unless (string-match "\\`{.*}\\'" value)
13466 (setq value (concat "\"" value "\"")))
13467 (org-match-sparse-tree arg (concat kwd "=" value)))
13468 ((member ans '(?r ?R ?/))
13469 (call-interactively 'org-occur))
13470 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13472 (defvar org-occur-highlights nil
13473 "List of overlays used for occur matches.")
13474 (make-variable-buffer-local 'org-occur-highlights)
13475 (defvar org-occur-parameters nil
13476 "Parameters of the active org-occur calls.
13477 This is a list, each call to org-occur pushes as cons cell,
13478 containing the regular expression and the callback, onto the list.
13479 The list can contain several entries if `org-occur' has been called
13480 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13481 will only contain one set of parameters. When the highlights are
13482 removed (for example with `C-c C-c', or with the next edit (depending
13483 on `org-remove-highlights-with-change'), this variable is emptied
13484 as well.")
13485 (make-variable-buffer-local 'org-occur-parameters)
13487 (defun org-occur (regexp &optional keep-previous callback)
13488 "Make a compact tree which shows all matches of REGEXP.
13489 The tree will show the lines where the regexp matches, and all higher
13490 headlines above the match. It will also show the heading after the match,
13491 to make sure editing the matching entry is easy.
13492 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13493 call to `org-occur' will be kept, to allow stacking of calls to this
13494 command.
13495 If CALLBACK is non-nil, it is a function which is called to confirm
13496 that the match should indeed be shown."
13497 (interactive "sRegexp: \nP")
13498 (when (equal regexp "")
13499 (user-error "Regexp cannot be empty"))
13500 (unless keep-previous
13501 (org-remove-occur-highlights nil nil t))
13502 (push (cons regexp callback) org-occur-parameters)
13503 (let ((cnt 0))
13504 (save-excursion
13505 (goto-char (point-min))
13506 (if (or (not keep-previous) ; do not want to keep
13507 (not org-occur-highlights)) ; no previous matches
13508 ;; hide everything
13509 (org-overview))
13510 (while (re-search-forward regexp nil t)
13511 (when (or (not callback)
13512 (save-match-data (funcall callback)))
13513 (setq cnt (1+ cnt))
13514 (when org-highlight-sparse-tree-matches
13515 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13516 (org-show-context 'occur-tree))))
13517 (when org-remove-highlights-with-change
13518 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13519 nil 'local))
13520 (unless org-sparse-tree-open-archived-trees
13521 (org-hide-archived-subtrees (point-min) (point-max)))
13522 (run-hooks 'org-occur-hook)
13523 (if (org-called-interactively-p 'interactive)
13524 (message "%d match(es) for regexp %s" cnt regexp))
13525 cnt))
13527 (defun org-occur-next-match (&optional n reset)
13528 "Function for `next-error-function' to find sparse tree matches.
13529 N is the number of matches to move, when negative move backwards.
13530 RESET is entirely ignored - this function always goes back to the
13531 starting point when no match is found."
13532 (let* ((limit (if (< n 0) (point-min) (point-max)))
13533 (search-func (if (< n 0)
13534 'previous-single-char-property-change
13535 'next-single-char-property-change))
13536 (n (abs n))
13537 (pos (point))
13539 (catch 'exit
13540 (while (setq p1 (funcall search-func (point) 'org-type))
13541 (when (equal p1 limit)
13542 (goto-char pos)
13543 (error "No more matches"))
13544 (when (equal (get-char-property p1 'org-type) 'org-occur)
13545 (setq n (1- n))
13546 (when (= n 0)
13547 (goto-char p1)
13548 (throw 'exit (point))))
13549 (goto-char p1))
13550 (goto-char p1)
13551 (error "No more matches"))))
13553 (defun org-show-context (&optional key)
13554 "Make sure point and context are visible.
13555 How much context is shown depends upon the variables
13556 `org-show-hierarchy-above', `org-show-following-heading',
13557 `org-show-entry-below' and `org-show-siblings'."
13558 (let ((heading-p (org-at-heading-p t))
13559 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13560 (following-p (org-get-alist-option org-show-following-heading key))
13561 (entry-p (org-get-alist-option org-show-entry-below key))
13562 (siblings-p (org-get-alist-option org-show-siblings key)))
13563 ;; Show heading or entry text
13564 (if (and heading-p (not entry-p))
13565 (org-flag-heading nil) ; only show the heading
13566 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13567 (org-show-hidden-entry))) ; show entire entry
13568 (when following-p
13569 ;; Show next sibling, or heading below text
13570 (save-excursion
13571 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13572 (org-flag-heading nil))))
13573 (when siblings-p (org-show-siblings))
13574 (when hierarchy-p
13575 ;; show all higher headings, possibly with siblings
13576 (save-excursion
13577 (while (and (condition-case nil
13578 (progn (org-up-heading-all 1) t)
13579 (error nil))
13580 (not (bobp)))
13581 (org-flag-heading nil)
13582 (when siblings-p (org-show-siblings)))))
13583 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13585 (defvar org-reveal-start-hook nil
13586 "Hook run before revealing a location.")
13588 (defun org-reveal (&optional siblings)
13589 "Show current entry, hierarchy above it, and the following headline.
13590 This can be used to show a consistent set of context around locations
13591 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13592 not t for the search context.
13594 With optional argument SIBLINGS, on each level of the hierarchy all
13595 siblings are shown. This repairs the tree structure to what it would
13596 look like when opened with hierarchical calls to `org-cycle'.
13597 With double optional argument \\[universal-argument] \\[universal-argument], \
13598 go to the parent and show the
13599 entire tree."
13600 (interactive "P")
13601 (run-hooks 'org-reveal-start-hook)
13602 (let ((org-show-hierarchy-above t)
13603 (org-show-following-heading t)
13604 (org-show-siblings (if siblings t org-show-siblings)))
13605 (org-show-context nil))
13606 (when (equal siblings '(16))
13607 (save-excursion
13608 (when (org-up-heading-safe)
13609 (org-show-subtree)
13610 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13612 (defun org-highlight-new-match (beg end)
13613 "Highlight from BEG to END and mark the highlight is an occur headline."
13614 (let ((ov (make-overlay beg end)))
13615 (overlay-put ov 'face 'secondary-selection)
13616 (overlay-put ov 'org-type 'org-occur)
13617 (push ov org-occur-highlights)))
13619 (defun org-remove-occur-highlights (&optional beg end noremove)
13620 "Remove the occur highlights from the buffer.
13621 BEG and END are ignored. If NOREMOVE is nil, remove this function
13622 from the `before-change-functions' in the current buffer."
13623 (interactive)
13624 (unless org-inhibit-highlight-removal
13625 (mapc 'delete-overlay org-occur-highlights)
13626 (setq org-occur-highlights nil)
13627 (setq org-occur-parameters nil)
13628 (unless noremove
13629 (remove-hook 'before-change-functions
13630 'org-remove-occur-highlights 'local))))
13632 ;;;; Priorities
13634 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13635 "Regular expression matching the priority indicator.")
13637 (defvar org-remove-priority-next-time nil)
13639 (defun org-priority-up ()
13640 "Increase the priority of the current item."
13641 (interactive)
13642 (org-priority 'up))
13644 (defun org-priority-down ()
13645 "Decrease the priority of the current item."
13646 (interactive)
13647 (org-priority 'down))
13649 (defun org-priority (&optional action show)
13650 "Change the priority of an item.
13651 ACTION can be `set', `up', `down', or a character."
13652 (interactive "P")
13653 (if (equal action '(4))
13654 (org-show-priority)
13655 (unless org-enable-priority-commands
13656 (user-error "Priority commands are disabled"))
13657 (setq action (or action 'set))
13658 (let (current new news have remove)
13659 (save-excursion
13660 (org-back-to-heading t)
13661 (if (looking-at org-priority-regexp)
13662 (setq current (string-to-char (match-string 2))
13663 have t))
13664 (cond
13665 ((eq action 'remove)
13666 (setq remove t new ?\ ))
13667 ((or (eq action 'set)
13668 (if (featurep 'xemacs) (characterp action) (integerp action)))
13669 (if (not (eq action 'set))
13670 (setq new action)
13671 (message "Priority %c-%c, SPC to remove: "
13672 org-highest-priority org-lowest-priority)
13673 (save-match-data
13674 (setq new (read-char-exclusive))))
13675 (if (and (= (upcase org-highest-priority) org-highest-priority)
13676 (= (upcase org-lowest-priority) org-lowest-priority))
13677 (setq new (upcase new)))
13678 (cond ((equal new ?\ ) (setq remove t))
13679 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13680 (user-error "Priority must be between `%c' and `%c'"
13681 org-highest-priority org-lowest-priority))))
13682 ((eq action 'up)
13683 (setq new (if have
13684 (1- current) ; normal cycling
13685 ;; last priority was empty
13686 (if (eq last-command this-command)
13687 org-lowest-priority ; wrap around empty to lowest
13688 ;; default
13689 (if org-priority-start-cycle-with-default
13690 org-default-priority
13691 (1- org-default-priority))))))
13692 ((eq action 'down)
13693 (setq new (if have
13694 (1+ current) ; normal cycling
13695 ;; last priority was empty
13696 (if (eq last-command this-command)
13697 org-highest-priority ; wrap around empty to highest
13698 ;; default
13699 (if org-priority-start-cycle-with-default
13700 org-default-priority
13701 (1+ org-default-priority))))))
13702 (t (user-error "Invalid action")))
13703 (if (or (< (upcase new) org-highest-priority)
13704 (> (upcase new) org-lowest-priority))
13705 (if (and (memq action '(up down))
13706 (not have) (not (eq last-command this-command)))
13707 ;; `new' is from default priority
13708 (error
13709 "The default can not be set, see `org-default-priority' why")
13710 ;; normal cycling: `new' is beyond highest/lowest priority
13711 ;; and is wrapped around to the empty priority
13712 (setq remove t)))
13713 (setq news (format "%c" new))
13714 (if have
13715 (if remove
13716 (replace-match "" t t nil 1)
13717 (replace-match news t t nil 2))
13718 (if remove
13719 (user-error "No priority cookie found in line")
13720 (let ((case-fold-search nil))
13721 (looking-at org-todo-line-regexp))
13722 (if (match-end 2)
13723 (progn
13724 (goto-char (match-end 2))
13725 (insert " [#" news "]"))
13726 (goto-char (match-beginning 3))
13727 (insert "[#" news "] "))))
13728 (org-preserve-lc (org-set-tags nil 'align)))
13729 (if remove
13730 (message "Priority removed")
13731 (message "Priority of current item set to %s" news)))))
13733 (defun org-show-priority ()
13734 "Show the priority of the current item.
13735 This priority is composed of the main priority given with the [#A] cookies,
13736 and by additional input from the age of a schedules or deadline entry."
13737 (interactive)
13738 (let ((pri (if (eq major-mode 'org-agenda-mode)
13739 (org-get-at-bol 'priority)
13740 (save-excursion
13741 (save-match-data
13742 (beginning-of-line)
13743 (and (looking-at org-heading-regexp)
13744 (org-get-priority (match-string 0))))))))
13745 (message "Priority is %d" (if pri pri -1000))))
13747 (defun org-get-priority (s)
13748 "Find priority cookie and return priority."
13749 (save-match-data
13750 (if (functionp org-get-priority-function)
13751 (funcall org-get-priority-function)
13752 (if (not (string-match org-priority-regexp s))
13753 (* 1000 (- org-lowest-priority org-default-priority))
13754 (* 1000 (- org-lowest-priority
13755 (string-to-char (match-string 2 s))))))))
13757 ;;;; Tags
13759 (defvar org-agenda-archives-mode)
13760 (defvar org-map-continue-from nil
13761 "Position from where mapping should continue.
13762 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13764 (defvar org-scanner-tags nil
13765 "The current tag list while the tags scanner is running.")
13766 (defvar org-trust-scanner-tags nil
13767 "Should `org-get-tags-at' use the tags for the scanner.
13768 This is for internal dynamical scoping only.
13769 When this is non-nil, the function `org-get-tags-at' will return the value
13770 of `org-scanner-tags' instead of building the list by itself. This
13771 can lead to large speed-ups when the tags scanner is used in a file with
13772 many entries, and when the list of tags is retrieved, for example to
13773 obtain a list of properties. Building the tags list for each entry in such
13774 a file becomes an N^2 operation - but with this variable set, it scales
13775 as N.")
13777 (defun org-scan-tags (action matcher todo-only &optional start-level)
13778 "Sca headline tags with inheritance and produce output ACTION.
13780 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13781 or `agenda' to produce an entry list for an agenda view. It can also be
13782 a Lisp form or a function that should be called at each matched headline, in
13783 this case the return value is a list of all return values from these calls.
13785 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13786 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13787 only lines with a not-done TODO keyword are included in the output.
13788 This should be the same variable that was scoped into
13789 and set by `org-make-tags-matcher' when it constructed MATCHER.
13791 START-LEVEL can be a string with asterisks, reducing the scope to
13792 headlines matching this string."
13793 (require 'org-agenda)
13794 (let* ((re (concat "^"
13795 (if start-level
13796 ;; Get the correct level to match
13797 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13798 org-outline-regexp)
13799 " *\\(\\<\\("
13800 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13801 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13802 (props (list 'face 'default
13803 'done-face 'org-agenda-done
13804 'undone-face 'default
13805 'mouse-face 'highlight
13806 'org-not-done-regexp org-not-done-regexp
13807 'org-todo-regexp org-todo-regexp
13808 'org-complex-heading-regexp org-complex-heading-regexp
13809 'help-echo
13810 (format "mouse-2 or RET jump to org file %s"
13811 (abbreviate-file-name
13812 (or (buffer-file-name (buffer-base-buffer))
13813 (buffer-name (buffer-base-buffer)))))))
13814 (org-map-continue-from nil)
13815 lspos tags tags-list
13816 (tags-alist (list (cons 0 org-file-tags)))
13817 (llast 0) rtn rtn1 level category i txt
13818 todo marker entry priority)
13819 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13820 (setq action (list 'lambda nil action)))
13821 (save-excursion
13822 (goto-char (point-min))
13823 (when (eq action 'sparse-tree)
13824 (org-overview)
13825 (org-remove-occur-highlights))
13826 (while (let (case-fold-search)
13827 (re-search-forward re nil t))
13828 (setq org-map-continue-from nil)
13829 (catch :skip
13830 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13831 tags (if (match-end 4) (org-match-string-no-properties 4)))
13832 (goto-char (setq lspos (match-beginning 0)))
13833 (setq level (org-reduced-level (org-outline-level))
13834 category (org-get-category))
13835 (setq i llast llast level)
13836 ;; remove tag lists from same and sublevels
13837 (while (>= i level)
13838 (when (setq entry (assoc i tags-alist))
13839 (setq tags-alist (delete entry tags-alist)))
13840 (setq i (1- i)))
13841 ;; add the next tags
13842 (when tags
13843 (setq tags (org-split-string tags ":")
13844 tags-alist
13845 (cons (cons level tags) tags-alist)))
13846 ;; compile tags for current headline
13847 (setq tags-list
13848 (if org-use-tag-inheritance
13849 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13850 tags)
13851 org-scanner-tags tags-list)
13852 (when org-use-tag-inheritance
13853 (setcdr (car tags-alist)
13854 (mapcar (lambda (x)
13855 (setq x (copy-sequence x))
13856 (org-add-prop-inherited x))
13857 (cdar tags-alist))))
13858 (when (and tags org-use-tag-inheritance
13859 (or (not (eq t org-use-tag-inheritance))
13860 org-tags-exclude-from-inheritance))
13861 ;; selective inheritance, remove uninherited ones
13862 (setcdr (car tags-alist)
13863 (org-remove-uninherited-tags (cdar tags-alist))))
13864 (when (and
13866 ;; eval matcher only when the todo condition is OK
13867 (and (or (not todo-only) (member todo org-not-done-keywords))
13868 (let ((case-fold-search t) (org-trust-scanner-tags t))
13869 (eval matcher)))
13871 ;; Call the skipper, but return t if it does not skip,
13872 ;; so that the `and' form continues evaluating
13873 (progn
13874 (unless (eq action 'sparse-tree) (org-agenda-skip))
13877 ;; Check if timestamps are deselecting this entry
13878 (or (not todo-only)
13879 (and (member todo org-not-done-keywords)
13880 (or (not org-agenda-tags-todo-honor-ignore-options)
13881 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13883 ;; select this headline
13884 (cond
13885 ((eq action 'sparse-tree)
13886 (and org-highlight-sparse-tree-matches
13887 (org-get-heading) (match-end 0)
13888 (org-highlight-new-match
13889 (match-beginning 1) (match-end 1)))
13890 (org-show-context 'tags-tree))
13891 ((eq action 'agenda)
13892 (setq txt (org-agenda-format-item
13894 (concat
13895 (if (eq org-tags-match-list-sublevels 'indented)
13896 (make-string (1- level) ?.) "")
13897 (org-get-heading))
13898 level category
13899 tags-list)
13900 priority (org-get-priority txt))
13901 (goto-char lspos)
13902 (setq marker (org-agenda-new-marker))
13903 (org-add-props txt props
13904 'org-marker marker 'org-hd-marker marker 'org-category category
13905 'todo-state todo
13906 'priority priority 'type "tagsmatch")
13907 (push txt rtn))
13908 ((functionp action)
13909 (setq org-map-continue-from nil)
13910 (save-excursion
13911 (setq rtn1 (funcall action))
13912 (push rtn1 rtn)))
13913 (t (user-error "Invalid action")))
13915 ;; if we are to skip sublevels, jump to end of subtree
13916 (unless org-tags-match-list-sublevels
13917 (org-end-of-subtree t)
13918 (backward-char 1))))
13919 ;; Get the correct position from where to continue
13920 (if org-map-continue-from
13921 (goto-char org-map-continue-from)
13922 (and (= (point) lspos) (end-of-line 1)))))
13923 (when (and (eq action 'sparse-tree)
13924 (not org-sparse-tree-open-archived-trees))
13925 (org-hide-archived-subtrees (point-min) (point-max)))
13926 (nreverse rtn)))
13928 (defun org-remove-uninherited-tags (tags)
13929 "Remove all tags that are not inherited from the list TAGS."
13930 (cond
13931 ((eq org-use-tag-inheritance t)
13932 (if org-tags-exclude-from-inheritance
13933 (org-delete-all org-tags-exclude-from-inheritance tags)
13934 tags))
13935 ((not org-use-tag-inheritance) nil)
13936 ((stringp org-use-tag-inheritance)
13937 (delq nil (mapcar
13938 (lambda (x)
13939 (if (and (string-match org-use-tag-inheritance x)
13940 (not (member x org-tags-exclude-from-inheritance)))
13941 x nil))
13942 tags)))
13943 ((listp org-use-tag-inheritance)
13944 (delq nil (mapcar
13945 (lambda (x)
13946 (if (member x org-use-tag-inheritance) x nil))
13947 tags)))))
13949 (defun org-match-sparse-tree (&optional todo-only match)
13950 "Create a sparse tree according to tags string MATCH.
13951 MATCH can contain positive and negative selection of tags, like
13952 \"+WORK+URGENT-WITHBOSS\".
13953 If optional argument TODO-ONLY is non-nil, only select lines that are
13954 also TODO lines."
13955 (interactive "P")
13956 (org-agenda-prepare-buffers (list (current-buffer)))
13957 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13959 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13961 (defvar org-cached-props nil)
13962 (defun org-cached-entry-get (pom property)
13963 (if (or (eq t org-use-property-inheritance)
13964 (and (stringp org-use-property-inheritance)
13965 (string-match org-use-property-inheritance property))
13966 (and (listp org-use-property-inheritance)
13967 (member property org-use-property-inheritance)))
13968 ;; Caching is not possible, check it directly
13969 (org-entry-get pom property 'inherit)
13970 ;; Get all properties, so that we can do complicated checks easily
13971 (cdr (assoc property (or org-cached-props
13972 (setq org-cached-props
13973 (org-entry-properties pom)))))))
13975 (defun org-global-tags-completion-table (&optional files)
13976 "Return the list of all tags in all agenda buffer/files.
13977 Optional FILES argument is a list of files which can be used
13978 instead of the agenda files."
13979 (save-excursion
13980 (org-uniquify
13981 (delq nil
13982 (apply 'append
13983 (mapcar
13984 (lambda (file)
13985 (set-buffer (find-file-noselect file))
13986 (append (org-get-buffer-tags)
13987 (mapcar (lambda (x) (if (stringp (car-safe x))
13988 (list (car-safe x)) nil))
13989 org-tag-alist)))
13990 (if (and files (car files))
13991 files
13992 (org-agenda-files))))))))
13994 (defun org-make-tags-matcher (match)
13995 "Create the TAGS/TODO matcher form for the selection string MATCH.
13997 The variable `todo-only' is scoped dynamically into this function.
13998 It will be set to t if the matcher restricts matching to TODO entries,
13999 otherwise will not be touched.
14001 Returns a cons of the selection string MATCH and the constructed
14002 lisp form implementing the matcher. The matcher is to be evaluated
14003 at an Org entry, with point on the headline, and returns t if the
14004 entry matches the selection string MATCH. The returned lisp form
14005 references two variables with information about the entry, which
14006 must be bound around the form's evaluation: todo, the TODO keyword
14007 at the entry (or nil of none); and tags-list, the list of all tags
14008 at the entry including inherited ones. Additionally, the category
14009 of the entry (if any) must be specified as the text property
14010 'org-category on the headline.
14012 See also `org-scan-tags'.
14014 (declare (special todo-only))
14015 (unless (boundp 'todo-only)
14016 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14017 (unless match
14018 ;; Get a new match request, with completion against the global
14019 ;; tags table and the local tags in current buffer
14020 (let ((org-last-tags-completion-table
14021 (org-uniquify
14022 (delq nil (append (org-get-buffer-tags)
14023 (org-global-tags-completion-table))))))
14024 (setq match (org-completing-read-no-i
14025 "Match: " 'org-tags-completion-function nil nil nil
14026 'org-tags-history))))
14028 ;; Parse the string and create a lisp form
14029 (let ((match0 match)
14030 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14031 minus tag mm
14032 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14033 orterms term orlist re-p str-p level-p level-op time-p
14034 prop-p pn pv po gv rest)
14035 ;; Expand group tags
14036 (setq match (org-tags-expand match))
14037 (if (string-match "/+" match)
14038 ;; match contains also a todo-matching request
14039 (progn
14040 (setq tagsmatch (substring match 0 (match-beginning 0))
14041 todomatch (substring match (match-end 0)))
14042 (if (string-match "^!" todomatch)
14043 (setq todo-only t todomatch (substring todomatch 1)))
14044 (if (string-match "^\\s-*$" todomatch)
14045 (setq todomatch nil)))
14046 ;; only matching tags
14047 (setq tagsmatch match todomatch nil))
14049 ;; Make the tags matcher
14050 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14051 (setq tagsmatcher t)
14052 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14053 (while (setq term (pop orterms))
14054 (while (and (equal (substring term -1) "\\") orterms)
14055 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14056 (while (string-match re term)
14057 (setq rest (substring term (match-end 0))
14058 minus (and (match-end 1)
14059 (equal (match-string 1 term) "-"))
14060 tag (save-match-data (replace-regexp-in-string
14061 "\\\\-" "-"
14062 (match-string 2 term)))
14063 re-p (equal (string-to-char tag) ?{)
14064 level-p (match-end 4)
14065 prop-p (match-end 5)
14066 mm (cond
14067 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14068 (level-p
14069 (setq level-op (org-op-to-function (match-string 3 term)))
14070 `(,level-op level ,(string-to-number
14071 (match-string 4 term))))
14072 (prop-p
14073 (setq pn (match-string 5 term)
14074 po (match-string 6 term)
14075 pv (match-string 7 term)
14076 re-p (equal (string-to-char pv) ?{)
14077 str-p (equal (string-to-char pv) ?\")
14078 time-p (save-match-data
14079 (string-match "^\"[[<].*[]>]\"$" pv))
14080 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14081 (if time-p (setq pv (org-matcher-time pv)))
14082 (setq po (org-op-to-function po (if time-p 'time str-p)))
14083 (cond
14084 ((equal pn "CATEGORY")
14085 (setq gv '(get-text-property (point) 'org-category)))
14086 ((equal pn "TODO")
14087 (setq gv 'todo))
14089 (setq gv `(org-cached-entry-get nil ,pn))))
14090 (if re-p
14091 (if (eq po 'org<>)
14092 `(not (string-match ,pv (or ,gv "")))
14093 `(string-match ,pv (or ,gv "")))
14094 (if str-p
14095 `(,po (or ,gv "") ,pv)
14096 `(,po (string-to-number (or ,gv ""))
14097 ,(string-to-number pv) ))))
14098 (t `(member ,tag tags-list)))
14099 mm (if minus (list 'not mm) mm)
14100 term rest)
14101 (push mm tagsmatcher))
14102 (push (if (> (length tagsmatcher) 1)
14103 (cons 'and tagsmatcher)
14104 (car tagsmatcher))
14105 orlist)
14106 (setq tagsmatcher nil))
14107 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14108 (setq tagsmatcher
14109 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14110 ;; Make the todo matcher
14111 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14112 (setq todomatcher t)
14113 (setq orterms (org-split-string todomatch "|") orlist nil)
14114 (while (setq term (pop orterms))
14115 (while (string-match re term)
14116 (setq minus (and (match-end 1)
14117 (equal (match-string 1 term) "-"))
14118 kwd (match-string 2 term)
14119 re-p (equal (string-to-char kwd) ?{)
14120 term (substring term (match-end 0))
14121 mm (if re-p
14122 `(string-match ,(substring kwd 1 -1) todo)
14123 (list 'equal 'todo kwd))
14124 mm (if minus (list 'not mm) mm))
14125 (push mm todomatcher))
14126 (push (if (> (length todomatcher) 1)
14127 (cons 'and todomatcher)
14128 (car todomatcher))
14129 orlist)
14130 (setq todomatcher nil))
14131 (setq todomatcher (if (> (length orlist) 1)
14132 (cons 'or orlist) (car orlist))))
14134 ;; Return the string and lisp forms of the matcher
14135 (setq matcher (if todomatcher
14136 (list 'and tagsmatcher todomatcher)
14137 tagsmatcher))
14138 (when todo-only
14139 (setq matcher (list 'and '(member todo org-not-done-keywords)
14140 matcher)))
14141 (cons match0 matcher)))
14143 (defun org-tags-expand (match &optional single-as-list downcased)
14144 "Expand group tags in MATCH.
14146 This replaces every group tag in MATCH with a regexp tag search.
14147 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14148 will be replaced like this:
14150 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14151 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14152 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14154 Replacing by a regexp preserves the structure of the match.
14155 E.g., this expansion
14157 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14159 will match anything tagged with \"Lab\" and \"Home\", or tagged
14160 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14162 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14163 assumed to be a single group tag, and the function will return
14164 the list of tags in this group.
14166 When DOWNCASE is non-nil, expand downcased TAGS."
14167 (if org-group-tags
14168 (let* ((case-fold-search t)
14169 (stable org-mode-syntax-table)
14170 (tal (or org-tag-groups-alist-for-agenda
14171 org-tag-groups-alist))
14172 (tal (if downcased
14173 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14174 (tml (mapcar 'car tal))
14175 (rtnmatch match) rpl)
14176 ;; @ and _ are allowed as word-components in tags
14177 (modify-syntax-entry ?@ "w" stable)
14178 (modify-syntax-entry ?_ "w" stable)
14179 (while (and tml
14180 (with-syntax-table stable
14181 (string-match
14182 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14183 (regexp-opt tml) "\\>\\)") rtnmatch)))
14184 (let* ((dir (match-string 1 rtnmatch))
14185 (tag (match-string 2 rtnmatch))
14186 (tag (if downcased (downcase tag) tag)))
14187 (setq tml (delete tag tml))
14188 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14189 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14190 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14191 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14192 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14193 (if single-as-list
14194 (or (reverse rpl) (list rtnmatch))
14195 rtnmatch))
14196 (if single-as-list (list (if downcased (downcase match) match))
14197 match)))
14199 (defun org-op-to-function (op &optional stringp)
14200 "Turn an operator into the appropriate function."
14201 (setq op
14202 (cond
14203 ((equal op "<" ) '(< string< org-time<))
14204 ((equal op ">" ) '(> org-string> org-time>))
14205 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14206 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14207 ((member op '("=" "==")) '(= string= org-time=))
14208 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14209 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14211 (defun org<> (a b) (not (= a b)))
14212 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14213 (defun org-string>= (a b) (not (string< a b)))
14214 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14215 (defun org-string<> (a b) (not (string= a b)))
14216 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14217 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14218 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14219 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14220 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14221 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14222 (defun org-2ft (s)
14223 "Convert S to a floating point time.
14224 If S is already a number, just return it. If it is a string, parse
14225 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14226 (cond
14227 ((numberp s) s)
14228 ((stringp s)
14229 (condition-case nil
14230 (float-time (apply 'encode-time (org-parse-time-string s)))
14231 (error 0.)))
14232 (t 0.)))
14234 (defun org-time-today ()
14235 "Time in seconds today at 0:00.
14236 Returns the float number of seconds since the beginning of the
14237 epoch to the beginning of today (00:00)."
14238 (float-time (apply 'encode-time
14239 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14241 (defun org-matcher-time (s)
14242 "Interpret a time comparison value."
14243 (save-match-data
14244 (cond
14245 ((string= s "<now>") (float-time))
14246 ((string= s "<today>") (org-time-today))
14247 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14248 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14249 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14250 (+ (org-time-today)
14251 (* (string-to-number (match-string 1 s))
14252 (cdr (assoc (match-string 2 s)
14253 '(("d" . 86400.0) ("w" . 604800.0)
14254 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14255 (t (org-2ft s)))))
14257 (defun org-match-any-p (re list)
14258 "Does re match any element of list?"
14259 (setq list (mapcar (lambda (x) (string-match re x)) list))
14260 (delq nil list))
14262 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14263 (defvar org-tags-overlay (make-overlay 1 1))
14264 (org-detach-overlay org-tags-overlay)
14266 (defun org-get-local-tags-at (&optional pos)
14267 "Get a list of tags defined in the current headline."
14268 (org-get-tags-at pos 'local))
14270 (defun org-get-local-tags ()
14271 "Get a list of tags defined in the current headline."
14272 (org-get-tags-at nil 'local))
14274 (defun org-get-tags-at (&optional pos local)
14275 "Get a list of all headline tags applicable at POS.
14276 POS defaults to point. If tags are inherited, the list contains
14277 the targets in the same sequence as the headlines appear, i.e.
14278 the tags of the current headline come last.
14279 When LOCAL is non-nil, only return tags from the current headline,
14280 ignore inherited ones."
14281 (interactive)
14282 (if (and org-trust-scanner-tags
14283 (or (not pos) (equal pos (point)))
14284 (not local))
14285 org-scanner-tags
14286 (let (tags ltags lastpos parent)
14287 (save-excursion
14288 (save-restriction
14289 (widen)
14290 (goto-char (or pos (point)))
14291 (save-match-data
14292 (catch 'done
14293 (condition-case nil
14294 (progn
14295 (org-back-to-heading t)
14296 (while (not (equal lastpos (point)))
14297 (setq lastpos (point))
14298 (when (looking-at
14299 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14300 (setq ltags (org-split-string
14301 (org-match-string-no-properties 1) ":"))
14302 (when parent
14303 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14304 (setq tags (append
14305 (if parent
14306 (org-remove-uninherited-tags ltags)
14307 ltags)
14308 tags)))
14309 (or org-use-tag-inheritance (throw 'done t))
14310 (if local (throw 'done t))
14311 (or (org-up-heading-safe) (error nil))
14312 (setq parent t)))
14313 (error nil)))))
14314 (if local
14315 tags
14316 (reverse (delete-dups
14317 (reverse (append
14318 (org-remove-uninherited-tags
14319 org-file-tags) tags)))))))))
14321 (defun org-add-prop-inherited (s)
14322 (add-text-properties 0 (length s) '(inherited t) s)
14325 (defun org-toggle-tag (tag &optional onoff)
14326 "Toggle the tag TAG for the current line.
14327 If ONOFF is `on' or `off', don't toggle but set to this state."
14328 (let (res current)
14329 (save-excursion
14330 (org-back-to-heading t)
14331 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14332 (point-at-eol) t)
14333 (progn
14334 (setq current (match-string 1))
14335 (replace-match ""))
14336 (setq current ""))
14337 (setq current (nreverse (org-split-string current ":")))
14338 (cond
14339 ((eq onoff 'on)
14340 (setq res t)
14341 (or (member tag current) (push tag current)))
14342 ((eq onoff 'off)
14343 (or (not (member tag current)) (setq current (delete tag current))))
14344 (t (if (member tag current)
14345 (setq current (delete tag current))
14346 (setq res t)
14347 (push tag current))))
14348 (end-of-line 1)
14349 (if current
14350 (progn
14351 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14352 (org-set-tags nil t))
14353 (delete-horizontal-space))
14354 (run-hooks 'org-after-tags-change-hook))
14355 res))
14357 (defun org-align-tags-here (to-col)
14358 ;; Assumes that this is a headline
14359 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14360 (beginning-of-line 1)
14361 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14362 (< pos (match-beginning 2)))
14363 (progn
14364 (setq tags-l (- (match-end 2) (match-beginning 2)))
14365 (goto-char (match-beginning 1))
14366 (insert " ")
14367 (delete-region (point) (1+ (match-beginning 2)))
14368 (setq ncol (max (current-column)
14369 (1+ col)
14370 (if (> to-col 0)
14371 to-col
14372 (- (abs to-col) tags-l))))
14373 (setq p (point))
14374 (insert (make-string (- ncol (current-column)) ?\ ))
14375 (setq ncol (current-column))
14376 (when indent-tabs-mode (tabify p (point-at-eol)))
14377 (org-move-to-column (min ncol col) t))
14378 (goto-char pos))))
14380 (defun org-set-tags-command (&optional arg just-align)
14381 "Call the set-tags command for the current entry."
14382 (interactive "P")
14383 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14384 (org-set-tags arg just-align)
14385 (save-excursion
14386 (unless (and (org-region-active-p)
14387 org-loop-over-headlines-in-active-region)
14388 (org-back-to-heading t))
14389 (org-set-tags arg just-align))))
14391 (defun org-set-tags-to (data)
14392 "Set the tags of the current entry to DATA, replacing the current tags.
14393 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14394 If DATA is nil or the empty string, any tags will be removed."
14395 (interactive "sTags: ")
14396 (setq data
14397 (cond
14398 ((eq data nil) "")
14399 ((equal data "") "")
14400 ((stringp data)
14401 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14402 ":"))
14403 ((listp data)
14404 (concat ":" (mapconcat 'identity data ":") ":"))))
14405 (when data
14406 (save-excursion
14407 (org-back-to-heading t)
14408 (when (looking-at org-complex-heading-regexp)
14409 (if (match-end 5)
14410 (progn
14411 (goto-char (match-beginning 5))
14412 (insert data)
14413 (delete-region (point) (point-at-eol))
14414 (org-set-tags nil 'align))
14415 (goto-char (point-at-eol))
14416 (insert " " data)
14417 (org-set-tags nil 'align)))
14418 (beginning-of-line 1)
14419 (if (looking-at ".*?\\([ \t]+\\)$")
14420 (delete-region (match-beginning 1) (match-end 1))))))
14422 (defun org-align-all-tags ()
14423 "Align the tags i all headings."
14424 (interactive)
14425 (save-excursion
14426 (or (ignore-errors (org-back-to-heading t))
14427 (outline-next-heading))
14428 (if (org-at-heading-p)
14429 (org-set-tags t)
14430 (message "No headings"))))
14432 (defvar org-indent-indentation-per-level)
14433 (defun org-set-tags (&optional arg just-align)
14434 "Set the tags for the current headline.
14435 With prefix ARG, realign all tags in headings in the current buffer."
14436 (interactive "P")
14437 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14438 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14439 'region-start-level 'region))
14440 org-loop-over-headlines-in-active-region)
14441 (org-map-entries
14442 ;; We don't use ARG and JUST-ALIGN here these args are not
14443 ;; useful when looping over headlines
14444 `(org-set-tags)
14445 org-loop-over-headlines-in-active-region
14446 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14447 (let* ((re org-outline-regexp-bol)
14448 (current (unless arg (org-get-tags-string)))
14449 (col (current-column))
14450 (org-setting-tags t)
14451 table current-tags inherited-tags ; computed below when needed
14452 tags p0 c0 c1 rpl di tc level)
14453 (if arg
14454 (save-excursion
14455 (goto-char (point-min))
14456 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14457 (while (re-search-forward re nil t)
14458 (org-set-tags nil t)
14459 (end-of-line 1)))
14460 (message "All tags realigned to column %d" org-tags-column))
14461 (if just-align
14462 (setq tags current)
14463 ;; Get a new set of tags from the user
14464 (save-excursion
14465 (setq table (append org-tag-persistent-alist
14466 (or org-tag-alist (org-get-buffer-tags))
14467 (and
14468 org-complete-tags-always-offer-all-agenda-tags
14469 (org-global-tags-completion-table
14470 (org-agenda-files))))
14471 org-last-tags-completion-table table
14472 current-tags (org-split-string current ":")
14473 inherited-tags (nreverse
14474 (nthcdr (length current-tags)
14475 (nreverse (org-get-tags-at))))
14476 tags
14477 (if (or (eq t org-use-fast-tag-selection)
14478 (and org-use-fast-tag-selection
14479 (delq nil (mapcar 'cdr table))))
14480 (org-fast-tag-selection
14481 current-tags inherited-tags table
14482 (if org-fast-tag-selection-include-todo
14483 org-todo-key-alist))
14484 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14485 (org-trim
14486 (org-icompleting-read "Tags: "
14487 'org-tags-completion-function
14488 nil nil current 'org-tags-history))))))
14489 (while (string-match "[-+&]+" tags)
14490 ;; No boolean logic, just a list
14491 (setq tags (replace-match ":" t t tags))))
14493 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14495 (if org-tags-sort-function
14496 (setq tags (mapconcat 'identity
14497 (sort (org-split-string
14498 tags (org-re "[^[:alnum:]_@#%]+"))
14499 org-tags-sort-function) ":")))
14501 (if (string-match "\\`[\t ]*\\'" tags)
14502 (setq tags "")
14503 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14504 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14506 ;; Insert new tags at the correct column
14507 (beginning-of-line 1)
14508 (setq level (or (and (looking-at org-outline-regexp)
14509 (- (match-end 0) (point) 1))
14511 (cond
14512 ((and (equal current "") (equal tags "")))
14513 ((re-search-forward
14514 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14515 (point-at-eol) t)
14516 (if (equal tags "")
14517 (setq rpl "")
14518 (goto-char (match-beginning 0))
14519 (setq c0 (current-column)
14520 ;; compute offset for the case of org-indent-mode active
14521 di (if org-indent-mode
14522 (* (1- org-indent-indentation-per-level) (1- level))
14524 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14525 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14526 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14527 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14528 (replace-match rpl t t)
14529 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14530 tags)
14531 (t (error "Tags alignment failed")))
14532 (org-move-to-column col)
14533 (unless just-align
14534 (run-hooks 'org-after-tags-change-hook))))))
14536 (defun org-change-tag-in-region (beg end tag off)
14537 "Add or remove TAG for each entry in the region.
14538 This works in the agenda, and also in an org-mode buffer."
14539 (interactive
14540 (list (region-beginning) (region-end)
14541 (let ((org-last-tags-completion-table
14542 (if (derived-mode-p 'org-mode)
14543 (org-uniquify
14544 (delq nil (append (org-get-buffer-tags)
14545 (org-global-tags-completion-table))))
14546 (org-global-tags-completion-table))))
14547 (org-icompleting-read
14548 "Tag: " 'org-tags-completion-function nil nil nil
14549 'org-tags-history))
14550 (progn
14551 (message "[s]et or [r]emove? ")
14552 (equal (read-char-exclusive) ?r))))
14553 (if (fboundp 'deactivate-mark) (deactivate-mark))
14554 (let ((agendap (equal major-mode 'org-agenda-mode))
14555 l1 l2 m buf pos newhead (cnt 0))
14556 (goto-char end)
14557 (setq l2 (1- (org-current-line)))
14558 (goto-char beg)
14559 (setq l1 (org-current-line))
14560 (loop for l from l1 to l2 do
14561 (org-goto-line l)
14562 (setq m (get-text-property (point) 'org-hd-marker))
14563 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14564 (and agendap m))
14565 (setq buf (if agendap (marker-buffer m) (current-buffer))
14566 pos (if agendap m (point)))
14567 (with-current-buffer buf
14568 (save-excursion
14569 (save-restriction
14570 (goto-char pos)
14571 (setq cnt (1+ cnt))
14572 (org-toggle-tag tag (if off 'off 'on))
14573 (setq newhead (org-get-heading)))))
14574 (and agendap (org-agenda-change-all-lines newhead m))))
14575 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14577 (defun org-tags-completion-function (string predicate &optional flag)
14578 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14579 (confirm (lambda (x) (stringp (car x)))))
14580 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14581 (setq s1 (match-string 1 string)
14582 s2 (match-string 2 string))
14583 (setq s1 "" s2 string))
14584 (cond
14585 ((eq flag nil)
14586 ;; try completion
14587 (setq rtn (try-completion s2 ctable confirm))
14588 (if (stringp rtn)
14589 (setq rtn
14590 (concat s1 s2 (substring rtn (length s2))
14591 (if (and org-add-colon-after-tag-completion
14592 (assoc rtn ctable))
14593 ":" ""))))
14594 rtn)
14595 ((eq flag t)
14596 ;; all-completions
14597 (all-completions s2 ctable confirm))
14598 ((eq flag 'lambda)
14599 ;; exact match?
14600 (assoc s2 ctable)))))
14602 (defun org-fast-tag-insert (kwd tags face &optional end)
14603 "Insert KDW, and the TAGS, the latter with face FACE.
14604 Also insert END."
14605 (insert (format "%-12s" (concat kwd ":"))
14606 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14607 (or end "")))
14609 (defun org-fast-tag-show-exit (flag)
14610 (save-excursion
14611 (org-goto-line 3)
14612 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14613 (replace-match ""))
14614 (when flag
14615 (end-of-line 1)
14616 (org-move-to-column (- (window-width) 19) t)
14617 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14619 (defun org-set-current-tags-overlay (current prefix)
14620 "Add an overlay to CURRENT tag with PREFIX."
14621 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14622 (if (featurep 'xemacs)
14623 (org-overlay-display org-tags-overlay (concat prefix s)
14624 'secondary-selection)
14625 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14626 (org-overlay-display org-tags-overlay (concat prefix s)))))
14628 (defvar org-last-tag-selection-key nil)
14629 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14630 "Fast tag selection with single keys.
14631 CURRENT is the current list of tags in the headline, INHERITED is the
14632 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14633 possibly with grouping information. TODO-TABLE is a similar table with
14634 TODO keywords, should these have keys assigned to them.
14635 If the keys are nil, a-z are automatically assigned.
14636 Returns the new tags string, or nil to not change the current settings."
14637 (let* ((fulltable (append table todo-table))
14638 (maxlen (apply 'max (mapcar
14639 (lambda (x)
14640 (if (stringp (car x)) (string-width (car x)) 0))
14641 fulltable)))
14642 (buf (current-buffer))
14643 (expert (eq org-fast-tag-selection-single-key 'expert))
14644 (buffer-tags nil)
14645 (fwidth (+ maxlen 3 1 3))
14646 (ncol (/ (- (window-width) 4) fwidth))
14647 (i-face 'org-done)
14648 (c-face 'org-todo)
14649 tg cnt e c char c1 c2 ntable tbl rtn
14650 ov-start ov-end ov-prefix
14651 (exit-after-next org-fast-tag-selection-single-key)
14652 (done-keywords org-done-keywords)
14653 groups ingroup)
14654 (save-excursion
14655 (beginning-of-line 1)
14656 (if (looking-at
14657 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14658 (setq ov-start (match-beginning 1)
14659 ov-end (match-end 1)
14660 ov-prefix "")
14661 (setq ov-start (1- (point-at-eol))
14662 ov-end (1+ ov-start))
14663 (skip-chars-forward "^\n\r")
14664 (setq ov-prefix
14665 (concat
14666 (buffer-substring (1- (point)) (point))
14667 (if (> (current-column) org-tags-column)
14669 (make-string (- org-tags-column (current-column)) ?\ ))))))
14670 (move-overlay org-tags-overlay ov-start ov-end)
14671 (save-window-excursion
14672 (if expert
14673 (set-buffer (get-buffer-create " *Org tags*"))
14674 (delete-other-windows)
14675 (split-window-vertically)
14676 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14677 (erase-buffer)
14678 (org-set-local 'org-done-keywords done-keywords)
14679 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14680 (org-fast-tag-insert "Current" current c-face "\n\n")
14681 (org-fast-tag-show-exit exit-after-next)
14682 (org-set-current-tags-overlay current ov-prefix)
14683 (setq tbl fulltable char ?a cnt 0)
14684 (while (setq e (pop tbl))
14685 (cond
14686 ((equal (car e) :startgroup)
14687 (push '() groups) (setq ingroup t)
14688 (when (not (= cnt 0))
14689 (setq cnt 0)
14690 (insert "\n"))
14691 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14692 ((equal (car e) :endgroup)
14693 (setq ingroup nil cnt 0)
14694 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14695 ((equal e '(:newline))
14696 (when (not (= cnt 0))
14697 (setq cnt 0)
14698 (insert "\n")
14699 (setq e (car tbl))
14700 (while (equal (car tbl) '(:newline))
14701 (insert "\n")
14702 (setq tbl (cdr tbl)))))
14703 ((equal e '(:grouptags)) nil)
14705 (setq tg (copy-sequence (car e)) c2 nil)
14706 (if (cdr e)
14707 (setq c (cdr e))
14708 ;; automatically assign a character.
14709 (setq c1 (string-to-char
14710 (downcase (substring
14711 tg (if (= (string-to-char tg) ?@) 1 0)))))
14712 (if (or (rassoc c1 ntable) (rassoc c1 table))
14713 (while (or (rassoc char ntable) (rassoc char table))
14714 (setq char (1+ char)))
14715 (setq c2 c1))
14716 (setq c (or c2 char)))
14717 (if ingroup (push tg (car groups)))
14718 (setq tg (org-add-props tg nil 'face
14719 (cond
14720 ((not (assoc tg table))
14721 (org-get-todo-face tg))
14722 ((member tg current) c-face)
14723 ((member tg inherited) i-face))))
14724 (if (equal (caar tbl) :grouptags)
14725 (org-add-props tg nil 'face 'org-tag-group))
14726 (if (and (= cnt 0) (not ingroup)) (insert " "))
14727 (insert "[" c "] " tg (make-string
14728 (- fwidth 4 (length tg)) ?\ ))
14729 (push (cons tg c) ntable)
14730 (when (= (setq cnt (1+ cnt)) ncol)
14731 (insert "\n")
14732 (if ingroup (insert " "))
14733 (setq cnt 0)))))
14734 (setq ntable (nreverse ntable))
14735 (insert "\n")
14736 (goto-char (point-min))
14737 (if (not expert) (org-fit-window-to-buffer))
14738 (setq rtn
14739 (catch 'exit
14740 (while t
14741 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14742 (if (not groups) "no " "")
14743 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14744 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14745 (setq org-last-tag-selection-key c)
14746 (cond
14747 ((= c ?\r) (throw 'exit t))
14748 ((= c ?!)
14749 (setq groups (not groups))
14750 (goto-char (point-min))
14751 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14752 ((= c ?\C-c)
14753 (if (not expert)
14754 (org-fast-tag-show-exit
14755 (setq exit-after-next (not exit-after-next)))
14756 (setq expert nil)
14757 (delete-other-windows)
14758 (set-window-buffer (split-window-vertically) " *Org tags*")
14759 (org-switch-to-buffer-other-window " *Org tags*")
14760 (org-fit-window-to-buffer)))
14761 ((or (= c ?\C-g)
14762 (and (= c ?q) (not (rassoc c ntable))))
14763 (org-detach-overlay org-tags-overlay)
14764 (setq quit-flag t))
14765 ((= c ?\ )
14766 (setq current nil)
14767 (if exit-after-next (setq exit-after-next 'now)))
14768 ((= c ?\t)
14769 (condition-case nil
14770 (setq tg (org-icompleting-read
14771 "Tag: "
14772 (or buffer-tags
14773 (with-current-buffer buf
14774 (org-get-buffer-tags)))))
14775 (quit (setq tg "")))
14776 (when (string-match "\\S-" tg)
14777 (add-to-list 'buffer-tags (list tg))
14778 (if (member tg current)
14779 (setq current (delete tg current))
14780 (push tg current)))
14781 (if exit-after-next (setq exit-after-next 'now)))
14782 ((setq e (rassoc c todo-table) tg (car e))
14783 (with-current-buffer buf
14784 (save-excursion (org-todo tg)))
14785 (if exit-after-next (setq exit-after-next 'now)))
14786 ((setq e (rassoc c ntable) tg (car e))
14787 (if (member tg current)
14788 (setq current (delete tg current))
14789 (loop for g in groups do
14790 (if (member tg g)
14791 (mapc (lambda (x)
14792 (setq current (delete x current)))
14793 g)))
14794 (push tg current))
14795 (if exit-after-next (setq exit-after-next 'now))))
14797 ;; Create a sorted list
14798 (setq current
14799 (sort current
14800 (lambda (a b)
14801 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14802 (if (eq exit-after-next 'now) (throw 'exit t))
14803 (goto-char (point-min))
14804 (beginning-of-line 2)
14805 (delete-region (point) (point-at-eol))
14806 (org-fast-tag-insert "Current" current c-face)
14807 (org-set-current-tags-overlay current ov-prefix)
14808 (while (re-search-forward
14809 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14810 (setq tg (match-string 1))
14811 (add-text-properties
14812 (match-beginning 1) (match-end 1)
14813 (list 'face
14814 (cond
14815 ((member tg current) c-face)
14816 ((member tg inherited) i-face)
14817 (t (get-text-property (match-beginning 1) 'face))))))
14818 (goto-char (point-min)))))
14819 (org-detach-overlay org-tags-overlay)
14820 (if rtn
14821 (mapconcat 'identity current ":")
14822 nil))))
14824 (defun org-get-tags-string ()
14825 "Get the TAGS string in the current headline."
14826 (unless (org-at-heading-p t)
14827 (user-error "Not on a heading"))
14828 (save-excursion
14829 (beginning-of-line 1)
14830 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14831 (org-match-string-no-properties 1)
14832 "")))
14834 (defun org-get-tags ()
14835 "Get the list of tags specified in the current headline."
14836 (org-split-string (org-get-tags-string) ":"))
14838 (defun org-get-buffer-tags ()
14839 "Get a table of all tags used in the buffer, for completion."
14840 (let (tags)
14841 (save-excursion
14842 (goto-char (point-min))
14843 (while (re-search-forward
14844 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14845 (when (equal (char-after (point-at-bol 0)) ?*)
14846 (mapc (lambda (x) (add-to-list 'tags x))
14847 (org-split-string (org-match-string-no-properties 1) ":")))))
14848 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14849 (mapcar 'list tags)))
14851 ;;;; The mapping API
14853 (defun org-map-entries (func &optional match scope &rest skip)
14854 "Call FUNC at each headline selected by MATCH in SCOPE.
14856 FUNC is a function or a lisp form. The function will be called without
14857 arguments, with the cursor positioned at the beginning of the headline.
14858 The return values of all calls to the function will be collected and
14859 returned as a list.
14861 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14862 does not need to preserve point. After evaluation, the cursor will be
14863 moved to the end of the line (presumably of the headline of the
14864 processed entry) and search continues from there. Under some
14865 circumstances, this may not produce the wanted results. For example,
14866 if you have removed (e.g. archived) the current (sub)tree it could
14867 mean that the next entry will be skipped entirely. In such cases, you
14868 can specify the position from where search should continue by making
14869 FUNC set the variable `org-map-continue-from' to the desired buffer
14870 position.
14872 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14873 Only headlines that are matched by this query will be considered during
14874 the iteration. When MATCH is nil or t, all headlines will be
14875 visited by the iteration.
14877 SCOPE determines the scope of this command. It can be any of:
14879 nil The current buffer, respecting the restriction if any
14880 tree The subtree started with the entry at point
14881 region The entries within the active region, if any
14882 region-start-level
14883 The entries within the active region, but only those at
14884 the same level than the first one.
14885 file The current buffer, without restriction
14886 file-with-archives
14887 The current buffer, and any archives associated with it
14888 agenda All agenda files
14889 agenda-with-archives
14890 All agenda files with any archive files associated with them
14891 \(file1 file2 ...)
14892 If this is a list, all files in the list will be scanned
14894 The remaining args are treated as settings for the skipping facilities of
14895 the scanner. The following items can be given here:
14897 archive skip trees with the archive tag
14898 comment skip trees with the COMMENT keyword
14899 function or Emacs Lisp form:
14900 will be used as value for `org-agenda-skip-function', so
14901 whenever the function returns a position, FUNC will not be
14902 called for that entry and search will continue from the
14903 position returned
14905 If your function needs to retrieve the tags including inherited tags
14906 at the *current* entry, you can use the value of the variable
14907 `org-scanner-tags' which will be much faster than getting the value
14908 with `org-get-tags-at'. If your function gets properties with
14909 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14910 to t around the call to `org-entry-properties' to get the same speedup.
14911 Note that if your function moves around to retrieve tags and properties at
14912 a *different* entry, you cannot use these techniques."
14913 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14914 (not (org-region-active-p)))
14915 (let* ((org-agenda-archives-mode nil) ; just to make sure
14916 (org-agenda-skip-archived-trees (memq 'archive skip))
14917 (org-agenda-skip-comment-trees (memq 'comment skip))
14918 (org-agenda-skip-function
14919 (car (org-delete-all '(comment archive) skip)))
14920 (org-tags-match-list-sublevels t)
14921 (start-level (eq scope 'region-start-level))
14922 matcher file res
14923 org-todo-keywords-for-agenda
14924 org-done-keywords-for-agenda
14925 org-todo-keyword-alist-for-agenda
14926 org-drawers-for-agenda
14927 org-tag-alist-for-agenda
14928 todo-only)
14930 (cond
14931 ((eq match t) (setq matcher t))
14932 ((eq match nil) (setq matcher t))
14933 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14935 (save-window-excursion
14936 (save-restriction
14937 (cond ((eq scope 'tree)
14938 (org-back-to-heading t)
14939 (org-narrow-to-subtree)
14940 (setq scope nil))
14941 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14942 (org-region-active-p))
14943 ;; If needed, set start-level to a string like "2"
14944 (when start-level
14945 (save-excursion
14946 (goto-char (region-beginning))
14947 (unless (org-at-heading-p) (outline-next-heading))
14948 (setq start-level (org-current-level))))
14949 (narrow-to-region (region-beginning)
14950 (save-excursion
14951 (goto-char (region-end))
14952 (unless (and (bolp) (org-at-heading-p))
14953 (outline-next-heading))
14954 (point)))
14955 (setq scope nil)))
14957 (if (not scope)
14958 (progn
14959 (org-agenda-prepare-buffers
14960 (list (buffer-file-name (current-buffer))))
14961 (setq res (org-scan-tags func matcher todo-only start-level)))
14962 ;; Get the right scope
14963 (cond
14964 ((and scope (listp scope) (symbolp (car scope)))
14965 (setq scope (eval scope)))
14966 ((eq scope 'agenda)
14967 (setq scope (org-agenda-files t)))
14968 ((eq scope 'agenda-with-archives)
14969 (setq scope (org-agenda-files t))
14970 (setq scope (org-add-archive-files scope)))
14971 ((eq scope 'file)
14972 (setq scope (list (buffer-file-name))))
14973 ((eq scope 'file-with-archives)
14974 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14975 (org-agenda-prepare-buffers scope)
14976 (while (setq file (pop scope))
14977 (with-current-buffer (org-find-base-buffer-visiting file)
14978 (save-excursion
14979 (save-restriction
14980 (widen)
14981 (goto-char (point-min))
14982 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14983 res)))
14985 ;;;; Properties
14987 ;;; Setting and retrieving properties
14989 (defconst org-special-properties
14990 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14991 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14992 "The special properties valid in Org-mode.
14994 These are properties that are not defined in the property drawer,
14995 but in some other way.")
14997 (defconst org-default-properties
14998 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14999 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15000 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15001 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15002 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15003 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15004 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15005 "Some properties that are used by Org-mode for various purposes.
15006 Being in this list makes sure that they are offered for completion.")
15008 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15009 "Regular expression matching the first line of a property drawer.")
15011 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15012 "Regular expression matching the last line of a property drawer.")
15014 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15015 "Regular expression matching the first line of a property drawer.")
15017 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15018 "Regular expression matching the first line of a property drawer.")
15020 (defconst org-property-drawer-re
15021 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15022 org-property-end-re "\\)\n?")
15023 "Matches an entire property drawer.")
15025 (defconst org-clock-drawer-re
15026 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15027 org-property-end-re "\\)\n?")
15028 "Matches an entire clock drawer.")
15030 (defun org-property-action ()
15031 "Do an action on properties."
15032 (interactive)
15033 (let (c)
15034 (org-at-property-p)
15035 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15036 (setq c (read-char-exclusive))
15037 (cond
15038 ((equal c ?s)
15039 (call-interactively 'org-set-property))
15040 ((equal c ?d)
15041 (call-interactively 'org-delete-property))
15042 ((equal c ?D)
15043 (call-interactively 'org-delete-property-globally))
15044 ((equal c ?c)
15045 (call-interactively 'org-compute-property-at-point))
15046 (t (user-error "No such property action %c" c)))))
15048 (defun org-inc-effort ()
15049 "Increment the value of the effort property in the current entry."
15050 (interactive)
15051 (org-set-effort nil t))
15053 (defvar org-clock-effort) ;; Defined in org-clock.el
15054 (defvar org-clock-current-task) ;; Defined in org-clock.el
15055 (defun org-set-effort (&optional value increment)
15056 "Set the effort property of the current entry.
15057 With numerical prefix arg, use the nth allowed value, 0 stands for the
15058 10th allowed value.
15060 When INCREMENT is non-nil, set the property to the next allowed value."
15061 (interactive "P")
15062 (if (equal value 0) (setq value 10))
15063 (let* ((completion-ignore-case t)
15064 (prop org-effort-property)
15065 (cur (org-entry-get nil prop))
15066 (allowed (org-property-get-allowed-values nil prop 'table))
15067 (existing (mapcar 'list (org-property-values prop)))
15068 (heading (nth 4 (org-heading-components)))
15070 (val (cond
15071 ((stringp value) value)
15072 ((and allowed (integerp value))
15073 (or (car (nth (1- value) allowed))
15074 (car (org-last allowed))))
15075 ((and allowed increment)
15076 (or (caadr (member (list cur) allowed))
15077 (user-error "Allowed effort values are not set")))
15078 (allowed
15079 (message "Select 1-9,0, [RET%s]: %s"
15080 (if cur (concat "=" cur) "")
15081 (mapconcat 'car allowed " "))
15082 (setq rpl (read-char-exclusive))
15083 (if (equal rpl ?\r)
15085 (setq rpl (- rpl ?0))
15086 (if (equal rpl 0) (setq rpl 10))
15087 (if (and (> rpl 0) (<= rpl (length allowed)))
15088 (car (nth (1- rpl) allowed))
15089 (org-completing-read "Effort: " allowed nil))))
15091 (let (org-completion-use-ido org-completion-use-iswitchb)
15092 (org-completing-read
15093 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15094 (concat "[" cur "]") "")
15095 ": ")
15096 existing nil nil "" nil cur))))))
15097 (unless (equal (org-entry-get nil prop) val)
15098 (org-entry-put nil prop val))
15099 (save-excursion
15100 (org-back-to-heading t)
15101 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15102 (when (string= heading org-clock-current-task)
15103 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15104 (org-clock-update-mode-line))
15105 (message "%s is now %s" prop val)))
15107 (defun org-at-property-p ()
15108 "Is cursor inside a property drawer?"
15109 (save-excursion
15110 (when (equal 'node-property (car (org-element-at-point)))
15111 (beginning-of-line 1)
15112 (looking-at org-property-re))))
15114 (defun org-get-property-block (&optional beg end force)
15115 "Return the (beg . end) range of the body of the property drawer.
15116 BEG and END are the beginning and end of the current subtree, or of
15117 the part before the first headline. If they are not given, they will
15118 be found. If the drawer does not exist and FORCE is non-nil, create
15119 the drawer."
15120 (catch 'exit
15121 (save-excursion
15122 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15123 (progn (org-back-to-heading t) (point))))
15124 (end (or end (and (not (outline-next-heading)) (point-max))
15125 (point))))
15126 (goto-char beg)
15127 (if (re-search-forward org-property-start-re end t)
15128 (setq beg (1+ (match-end 0)))
15129 (if force
15130 (save-excursion
15131 (org-insert-property-drawer)
15132 (setq end (progn (outline-next-heading) (point))))
15133 (throw 'exit nil))
15134 (goto-char beg)
15135 (if (re-search-forward org-property-start-re end t)
15136 (setq beg (1+ (match-end 0)))))
15137 (if (re-search-forward org-property-end-re end t)
15138 (setq end (match-beginning 0))
15139 (or force (throw 'exit nil))
15140 (goto-char beg)
15141 (setq end beg)
15142 (org-indent-line)
15143 (insert ":END:\n"))
15144 (cons beg end)))))
15146 (defun org-entry-properties (&optional pom which specific)
15147 "Get all properties of the entry at point-or-marker POM.
15148 This includes the TODO keyword, the tags, time strings for deadline,
15149 scheduled, and clocking, and any additional properties defined in the
15150 entry. The return value is an alist, keys may occur multiple times
15151 if the property key was used several times.
15152 POM may also be nil, in which case the current entry is used.
15153 If WHICH is nil or `all', get all properties. If WHICH is
15154 `special' or `standard', only get that subclass. If WHICH
15155 is a string only get exactly this property. SPECIFIC can be a string, the
15156 specific property we are interested in. Specifying it can speed
15157 things up because then unnecessary parsing is avoided."
15158 (setq which (or which 'all))
15159 (org-with-point-at pom
15160 (let ((clockstr (substring org-clock-string 0 -1))
15161 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15162 (case-fold-search nil)
15163 beg end range props sum-props key key1 value string clocksum clocksumt)
15164 (save-excursion
15165 (when (condition-case nil
15166 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15167 (error nil))
15168 (setq beg (point))
15169 (setq sum-props (get-text-property (point) 'org-summaries))
15170 (setq clocksum (get-text-property (point) :org-clock-minutes)
15171 clocksumt (get-text-property (point) :org-clock-minutes-today))
15172 (outline-next-heading)
15173 (setq end (point))
15174 (when (memq which '(all special))
15175 ;; Get the special properties, like TODO and tags
15176 (goto-char beg)
15177 (when (and (or (not specific) (string= specific "TODO"))
15178 (looking-at org-todo-line-regexp) (match-end 2))
15179 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15180 (when (and (or (not specific) (string= specific "PRIORITY"))
15181 (looking-at org-priority-regexp))
15182 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15183 (when (or (not specific) (string= specific "FILE"))
15184 (push (cons "FILE" buffer-file-name) props))
15185 (when (and (or (not specific) (string= specific "TAGS"))
15186 (setq value (org-get-tags-string))
15187 (string-match "\\S-" value))
15188 (push (cons "TAGS" value) props))
15189 (when (and (or (not specific) (string= specific "ALLTAGS"))
15190 (setq value (org-get-tags-at)))
15191 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15192 ":"))
15193 props))
15194 (when (or (not specific) (string= specific "BLOCKED"))
15195 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15196 (when (or (not specific)
15197 (member specific
15198 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15199 "TIMESTAMP" "TIMESTAMP_IA")))
15200 (catch 'match
15201 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15202 (setq key (if (match-end 1)
15203 (substring (org-match-string-no-properties 1)
15204 0 -1))
15205 string (if (equal key clockstr)
15206 (org-trim
15207 (buffer-substring-no-properties
15208 (match-beginning 3) (goto-char
15209 (point-at-eol))))
15210 (substring (org-match-string-no-properties 3)
15211 1 -1)))
15212 ;; Get the correct property name from the key. This is
15213 ;; necessary if the user has configured time keywords.
15214 (setq key1 (concat key ":"))
15215 (cond
15216 ((not key)
15217 (setq key
15218 (if (= (char-after (match-beginning 3)) ?\[)
15219 "TIMESTAMP_IA" "TIMESTAMP")))
15220 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15221 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15222 ((equal key1 org-closed-string) (setq key "CLOSED"))
15223 ((equal key1 org-clock-string) (setq key "CLOCK")))
15224 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15225 (progn
15226 (push (cons key string) props)
15227 ;; no need to search further if match is found
15228 (throw 'match t))
15229 (when (or (equal key "CLOCK") (not (assoc key props)))
15230 (push (cons key string) props)))))))
15232 (when (memq which '(all standard))
15233 ;; Get the standard properties, like :PROP: ...
15234 (setq range (org-get-property-block beg end))
15235 (when range
15236 (goto-char (car range))
15237 (while (re-search-forward org-property-re
15238 (cdr range) t)
15239 (setq key (org-match-string-no-properties 2)
15240 value (org-trim (or (org-match-string-no-properties 3) "")))
15241 (unless (member key excluded)
15242 (push (cons key (or value "")) props)))))
15243 (if clocksum
15244 (push (cons "CLOCKSUM"
15245 (org-columns-number-to-string (/ (float clocksum) 60.)
15246 'add_times))
15247 props))
15248 (if clocksumt
15249 (push (cons "CLOCKSUM_T"
15250 (org-columns-number-to-string (/ (float clocksumt) 60.)
15251 'add_times))
15252 props))
15253 (unless (assoc "CATEGORY" props)
15254 (push (cons "CATEGORY" (org-get-category)) props))
15255 (append sum-props (nreverse props)))))))
15257 (defun org-entry-get (pom property &optional inherit literal-nil)
15258 "Get value of PROPERTY for entry or content at point-or-marker POM.
15259 If INHERIT is non-nil and the entry does not have the property,
15260 then also check higher levels of the hierarchy.
15261 If INHERIT is the symbol `selective', use inheritance only if the setting
15262 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15263 If the property is present but empty, the return value is the empty string.
15264 If the property is not present at all, nil is returned.
15266 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15267 do not interpret it as the list atom nil. This is used for inheritance
15268 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15269 (org-with-point-at pom
15270 (if (and inherit (if (eq inherit 'selective)
15271 (org-property-inherit-p property)
15273 (org-entry-get-with-inheritance property literal-nil)
15274 (if (member property org-special-properties)
15275 ;; We need a special property. Use `org-entry-properties' to
15276 ;; retrieve it, but specify the wanted property
15277 (cdr (assoc property (org-entry-properties nil 'special property)))
15278 (let ((range (org-get-property-block)))
15279 (when (and range (not (eq (car range) (cdr range))))
15280 (let* ((props (list (or (assoc property org-file-properties)
15281 (assoc property org-global-properties)
15282 (assoc property org-global-properties-fixed))))
15283 (ap (lambda (key)
15284 (when (re-search-forward
15285 (org-re-property key) (cdr range) t)
15286 (setq props
15287 (org-update-property-plist
15289 (if (match-end 3)
15290 (org-match-string-no-properties 3) "")
15291 props)))))
15292 val)
15293 (goto-char (car range))
15294 (funcall ap property)
15295 (goto-char (car range))
15296 (while (funcall ap (concat property "+")))
15297 (setq val (cdr (assoc property props)))
15298 (when val (if literal-nil val (org-not-nil val))))))))))
15300 (defun org-property-or-variable-value (var &optional inherit)
15301 "Check if there is a property fixing the value of VAR.
15302 If yes, return this value. If not, return the current value of the variable."
15303 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15304 (if (and prop (stringp prop) (string-match "\\S-" prop))
15305 (read prop)
15306 (symbol-value var))))
15308 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15309 "Delete the property PROPERTY from entry at point-or-marker POM.
15310 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15311 an empty drawer to delete."
15312 (org-with-point-at pom
15313 (if (member property org-special-properties)
15314 nil ; cannot delete these properties.
15315 (let ((range (org-get-property-block)))
15316 (if (and range
15317 (goto-char (car range))
15318 (re-search-forward
15319 (org-re-property property)
15320 (cdr range) t))
15321 (progn
15322 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15323 (and delete-empty-drawer
15324 (org-remove-empty-drawer-at
15325 delete-empty-drawer (car range)))
15327 nil)))))
15329 ;; Multi-values properties are properties that contain multiple values
15330 ;; These values are assumed to be single words, separated by whitespace.
15331 (defun org-entry-add-to-multivalued-property (pom property value)
15332 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15333 (let* ((old (org-entry-get pom property))
15334 (values (and old (org-split-string old "[ \t]"))))
15335 (setq value (org-entry-protect-space value))
15336 (unless (member value values)
15337 (setq values (append values (list value)))
15338 (org-entry-put pom property
15339 (mapconcat 'identity values " ")))))
15341 (defun org-entry-remove-from-multivalued-property (pom property value)
15342 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15343 (let* ((old (org-entry-get pom property))
15344 (values (and old (org-split-string old "[ \t]"))))
15345 (setq value (org-entry-protect-space value))
15346 (when (member value values)
15347 (setq values (delete value values))
15348 (org-entry-put pom property
15349 (mapconcat 'identity values " ")))))
15351 (defun org-entry-member-in-multivalued-property (pom property value)
15352 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15353 (let* ((old (org-entry-get pom property))
15354 (values (and old (org-split-string old "[ \t]"))))
15355 (setq value (org-entry-protect-space value))
15356 (member value values)))
15358 (defun org-entry-get-multivalued-property (pom property)
15359 "Return a list of values in a multivalued property."
15360 (let* ((value (org-entry-get pom property))
15361 (values (and value (org-split-string value "[ \t]"))))
15362 (mapcar 'org-entry-restore-space values)))
15364 (defun org-entry-put-multivalued-property (pom property &rest values)
15365 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15366 VALUES should be a list of strings. Spaces will be protected."
15367 (org-entry-put pom property
15368 (mapconcat 'org-entry-protect-space values " "))
15369 (let* ((value (org-entry-get pom property))
15370 (values (and value (org-split-string value "[ \t]"))))
15371 (mapcar 'org-entry-restore-space values)))
15373 (defun org-entry-protect-space (s)
15374 "Protect spaces and newline in string S."
15375 (while (string-match " " s)
15376 (setq s (replace-match "%20" t t s)))
15377 (while (string-match "\n" s)
15378 (setq s (replace-match "%0A" t t s)))
15381 (defun org-entry-restore-space (s)
15382 "Restore spaces and newline in string S."
15383 (while (string-match "%20" s)
15384 (setq s (replace-match " " t t s)))
15385 (while (string-match "%0A" s)
15386 (setq s (replace-match "\n" t t s)))
15389 (defvar org-entry-property-inherited-from (make-marker)
15390 "Marker pointing to the entry from where a property was inherited.
15391 Each call to `org-entry-get-with-inheritance' will set this marker to the
15392 location of the entry where the inheritance search matched. If there was
15393 no match, the marker will point nowhere.
15394 Note that also `org-entry-get' calls this function, if the INHERIT flag
15395 is set.")
15397 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15398 "Get PROPERTY of entry or content at point, search higher levels if needed.
15399 The search will stop at the first ancestor which has the property defined.
15400 If the value found is \"nil\", return nil to show that the property
15401 should be considered as undefined (this is the meaning of nil here).
15402 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15403 (move-marker org-entry-property-inherited-from nil)
15404 (let (tmp)
15405 (save-excursion
15406 (save-restriction
15407 (widen)
15408 (catch 'ex
15409 (while t
15410 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15411 (or (ignore-errors (org-back-to-heading t))
15412 (goto-char (point-min)))
15413 (move-marker org-entry-property-inherited-from (point))
15414 (throw 'ex tmp))
15415 (or (ignore-errors (org-up-heading-safe))
15416 (throw 'ex nil))))))
15417 (setq tmp (or tmp
15418 (cdr (assoc property org-file-properties))
15419 (cdr (assoc property org-global-properties))
15420 (cdr (assoc property org-global-properties-fixed))))
15421 (if literal-nil tmp (org-not-nil tmp))))
15423 (defvar org-property-changed-functions nil
15424 "Hook called when the value of a property has changed.
15425 Each hook function should accept two arguments, the name of the property
15426 and the new value.")
15428 (defun org-entry-put (pom property value)
15429 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15430 (org-with-point-at pom
15431 (org-back-to-heading t)
15432 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15433 range)
15434 (cond
15435 ((equal property "TODO")
15436 (when (and (stringp value) (string-match "\\S-" value)
15437 (not (member value org-todo-keywords-1)))
15438 (user-error "\"%s\" is not a valid TODO state" value))
15439 (if (or (not value)
15440 (not (string-match "\\S-" value)))
15441 (setq value 'none))
15442 (org-todo value)
15443 (org-set-tags nil 'align))
15444 ((equal property "PRIORITY")
15445 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15446 (string-to-char value) ?\ ))
15447 (org-set-tags nil 'align))
15448 ((equal property "CLOCKSUM")
15449 (if (not (re-search-forward
15450 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15451 (error "Cannot find a clock log")
15452 (goto-char (- (match-end 1) 2))
15453 (cond
15454 ((eq value 'earlier) (org-timestamp-down))
15455 ((eq value 'later) (org-timestamp-up)))
15456 (org-clock-sum-current-item)))
15457 ((equal property "SCHEDULED")
15458 (if (re-search-forward org-scheduled-time-regexp end t)
15459 (cond
15460 ((eq value 'earlier) (org-timestamp-change -1 'day))
15461 ((eq value 'later) (org-timestamp-change 1 'day))
15462 (t (call-interactively 'org-schedule)))
15463 (call-interactively 'org-schedule)))
15464 ((equal property "DEADLINE")
15465 (if (re-search-forward org-deadline-time-regexp end t)
15466 (cond
15467 ((eq value 'earlier) (org-timestamp-change -1 'day))
15468 ((eq value 'later) (org-timestamp-change 1 'day))
15469 (t (call-interactively 'org-deadline)))
15470 (call-interactively 'org-deadline)))
15471 ((member property org-special-properties)
15472 (error "The %s property can not yet be set with `org-entry-put'"
15473 property))
15474 (t ; a non-special property
15475 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15476 (setq range (org-get-property-block beg end 'force))
15477 (goto-char (car range))
15478 (if (re-search-forward
15479 (org-re-property property) (cdr range) t)
15480 (progn
15481 (delete-region (match-beginning 0) (match-end 0))
15482 (goto-char (match-beginning 0)))
15483 (goto-char (cdr range))
15484 (insert "\n")
15485 (backward-char 1)
15486 (org-indent-line))
15487 (insert ":" property ":")
15488 (and value (insert " " value))
15489 (org-indent-line)))))
15490 (run-hook-with-args 'org-property-changed-functions property value)))
15492 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15493 "Get all property keys in the current buffer.
15494 With INCLUDE-SPECIALS, also list the special properties that reflect things
15495 like tags and TODO state.
15496 With INCLUDE-DEFAULTS, also include properties that has special meaning
15497 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15498 and others.
15499 With INCLUDE-COLUMNS, also include property names given in COLUMN
15500 formats in the current buffer."
15501 (let (rtn range cfmt s p)
15502 (save-excursion
15503 (save-restriction
15504 (widen)
15505 (goto-char (point-min))
15506 (while (re-search-forward org-property-start-re nil t)
15507 (setq range (org-get-property-block))
15508 (goto-char (car range))
15509 (while (re-search-forward org-property-re
15510 (cdr range) t)
15511 (add-to-list 'rtn (org-match-string-no-properties 2)))
15512 (outline-next-heading))))
15514 (when include-specials
15515 (setq rtn (append org-special-properties rtn)))
15517 (when include-defaults
15518 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15519 (add-to-list 'rtn org-effort-property))
15521 (when include-columns
15522 (save-excursion
15523 (save-restriction
15524 (widen)
15525 (goto-char (point-min))
15526 (while (re-search-forward
15527 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15528 nil t)
15529 (setq cfmt (match-string 2) s 0)
15530 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15531 cfmt s)
15532 (setq s (match-end 0)
15533 p (match-string 1 cfmt))
15534 (unless (or (equal p "ITEM")
15535 (member p org-special-properties))
15536 (add-to-list 'rtn (match-string 1 cfmt))))))))
15538 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15540 (defun org-property-values (key)
15541 "Return a list of all values of property KEY in the current buffer."
15542 (save-excursion
15543 (save-restriction
15544 (widen)
15545 (goto-char (point-min))
15546 (let ((re (org-re-property key))
15547 values)
15548 (while (re-search-forward re nil t)
15549 (add-to-list 'values (org-trim (match-string 3))))
15550 (delete "" values)))))
15552 (defun org-insert-property-drawer ()
15553 "Insert a property drawer into the current entry."
15554 (org-back-to-heading t)
15555 (looking-at org-outline-regexp)
15556 (let ((indent (if org-adapt-indentation
15557 (- (match-end 0) (match-beginning 0))
15559 (beg (point))
15560 (re (concat "^[ \t]*" org-keyword-time-regexp))
15561 end hiddenp)
15562 (outline-next-heading)
15563 (setq end (point))
15564 (goto-char beg)
15565 (while (re-search-forward re end t))
15566 (setq hiddenp (outline-invisible-p))
15567 (end-of-line 1)
15568 (and (equal (char-after) ?\n) (forward-char 1))
15569 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15570 (if (member (match-string 1) '("CLOCK:" ":END:"))
15571 ;; just skip this line
15572 (beginning-of-line 2)
15573 ;; Drawer start, find the end
15574 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15575 (beginning-of-line 1)))
15576 (org-skip-over-state-notes)
15577 (skip-chars-backward " \t\n\r")
15578 (if (eq (char-before) ?*) (forward-char 1))
15579 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15580 (beginning-of-line 0)
15581 (org-indent-to-column indent)
15582 (beginning-of-line 2)
15583 (org-indent-to-column indent)
15584 (beginning-of-line 0)
15585 (if hiddenp
15586 (save-excursion
15587 (org-back-to-heading t)
15588 (hide-entry))
15589 (org-flag-drawer t))))
15591 (defun org-insert-drawer (&optional arg drawer)
15592 "Insert a drawer at point.
15594 Optional argument DRAWER, when non-nil, is a string representing
15595 drawer's name. Otherwise, the user is prompted for a name.
15597 If a region is active, insert the drawer around that region
15598 instead.
15600 Point is left between drawer's boundaries."
15601 (interactive "P")
15602 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15603 "LOGBOOK"))
15604 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15605 ;; internally by Org. They are meant to be inserted
15606 ;; automatically.
15607 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15608 ;; Remove system drawers from list. Note: For some reason,
15609 ;; `org-completing-read' ignores the predicate while
15610 ;; `completing-read' handles it fine.
15611 (drawer (if arg "PROPERTIES"
15612 (or drawer
15613 (completing-read
15614 "Drawer: " org-drawers
15615 (lambda (d) (not (member d system-drawers))))))))
15616 (cond
15617 ;; With C-u, fall back on `org-insert-property-drawer'
15618 (arg (org-insert-property-drawer))
15619 ;; With an active region, insert a drawer at point.
15620 ((not (org-region-active-p))
15621 (progn
15622 (unless (bolp) (insert "\n"))
15623 (insert (format ":%s:\n\n:END:\n" drawer))
15624 (forward-line -2)))
15625 ;; Otherwise, insert the drawer at point
15627 (let ((rbeg (region-beginning))
15628 (rend (copy-marker (region-end))))
15629 (unwind-protect
15630 (progn
15631 (goto-char rbeg)
15632 (beginning-of-line)
15633 (when (save-excursion
15634 (re-search-forward org-outline-regexp-bol rend t))
15635 (user-error "Drawers cannot contain headlines"))
15636 ;; Position point at the beginning of the first
15637 ;; non-blank line in region. Insert drawer's opening
15638 ;; there, then indent it.
15639 (org-skip-whitespace)
15640 (beginning-of-line)
15641 (insert ":" drawer ":\n")
15642 (forward-line -1)
15643 (indent-for-tab-command)
15644 ;; Move point to the beginning of the first blank line
15645 ;; after the last non-blank line in region. Insert
15646 ;; drawer's closing, then indent it.
15647 (goto-char rend)
15648 (skip-chars-backward " \r\t\n")
15649 (insert "\n:END:")
15650 (deactivate-mark t)
15651 (indent-for-tab-command)
15652 (unless (eolp) (insert "\n")))
15653 ;; Clear marker, whatever the outcome of insertion is.
15654 (set-marker rend nil)))))))
15656 (defvar org-property-set-functions-alist nil
15657 "Property set function alist.
15658 Each entry should have the following format:
15660 (PROPERTY . READ-FUNCTION)
15662 The read function will be called with the same argument as
15663 `org-completing-read'.")
15665 (defun org-set-property-function (property)
15666 "Get the function that should be used to set PROPERTY.
15667 This is computed according to `org-property-set-functions-alist'."
15668 (or (cdr (assoc property org-property-set-functions-alist))
15669 'org-completing-read))
15671 (defun org-read-property-value (property)
15672 "Read PROPERTY value from user."
15673 (let* ((completion-ignore-case t)
15674 (allowed (org-property-get-allowed-values nil property 'table))
15675 (cur (org-entry-get nil property))
15676 (prompt (concat property " value"
15677 (if (and cur (string-match "\\S-" cur))
15678 (concat " [" cur "]") "") ": "))
15679 (set-function (org-set-property-function property))
15680 (val (if allowed
15681 (funcall set-function prompt allowed nil
15682 (not (get-text-property 0 'org-unrestricted
15683 (caar allowed))))
15684 (let (org-completion-use-ido org-completion-use-iswitchb)
15685 (funcall set-function prompt
15686 (mapcar 'list (org-property-values property))
15687 nil nil "" nil cur)))))
15688 (if (equal val "")
15690 val)))
15692 (defvar org-last-set-property nil)
15693 (defvar org-last-set-property-value nil)
15694 (defun org-read-property-name ()
15695 "Read a property name."
15696 (let* ((completion-ignore-case t)
15697 (keys (org-buffer-property-keys nil t t))
15698 (default-prop (or (save-excursion
15699 (save-match-data
15700 (beginning-of-line)
15701 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15702 (null (string= (match-string 1) "END"))
15703 (match-string 1))))
15704 org-last-set-property))
15705 (property (org-icompleting-read
15706 (concat "Property"
15707 (if default-prop (concat " [" default-prop "]") "")
15708 ": ")
15709 (mapcar 'list keys)
15710 nil nil nil nil
15711 default-prop)))
15712 (if (member property keys)
15713 property
15714 (or (cdr (assoc (downcase property)
15715 (mapcar (lambda (x) (cons (downcase x) x))
15716 keys)))
15717 property))))
15719 (defun org-set-property-and-value (use-last)
15720 "Allow to set [PROPERTY]: [value] direction from prompt.
15721 When use-default, don't even ask, just use the last
15722 \"[PROPERTY]: [value]\" string from the history."
15723 (interactive "P")
15724 (let* ((completion-ignore-case t)
15725 (pv (or (and use-last org-last-set-property-value)
15726 (org-completing-read
15727 "Enter a \"[Property]: [value]\" pair: "
15728 nil nil nil nil nil
15729 org-last-set-property-value)))
15730 prop val)
15731 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15732 (setq prop (match-string 1 pv)
15733 val (match-string 2 pv))
15734 (org-set-property prop val))))
15736 (defun org-set-property (property value)
15737 "In the current entry, set PROPERTY to VALUE.
15738 When called interactively, this will prompt for a property name, offering
15739 completion on existing and default properties. And then it will prompt
15740 for a value, offering completion either on allowed values (via an inherited
15741 xxx_ALL property) or on existing values in other instances of this property
15742 in the current file."
15743 (interactive (list nil nil))
15744 (let* ((property (or property (org-read-property-name)))
15745 (value (or value (org-read-property-value property)))
15746 (fn (cdr (assoc property org-properties-postprocess-alist))))
15747 (setq org-last-set-property property)
15748 (setq org-last-set-property-value (concat property ": " value))
15749 ;; Possibly postprocess the inserted value:
15750 (when fn (setq value (funcall fn value)))
15751 (unless (equal (org-entry-get nil property) value)
15752 (org-entry-put nil property value))))
15754 (defun org-delete-property (property &optional delete-empty-drawer)
15755 "In the current entry, delete PROPERTY.
15756 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15757 an empty drawer to delete."
15758 (interactive
15759 (let* ((completion-ignore-case t)
15760 (prop (org-icompleting-read "Property: "
15761 (org-entry-properties nil 'standard))))
15762 (list prop)))
15763 (message "Property %s %s" property
15764 (if (org-entry-delete nil property delete-empty-drawer)
15765 "deleted"
15766 "was not present in the entry")))
15768 (defun org-delete-property-globally (property)
15769 "Remove PROPERTY globally, from all entries."
15770 (interactive
15771 (let* ((completion-ignore-case t)
15772 (prop (org-icompleting-read
15773 "Globally remove property: "
15774 (mapcar 'list (org-buffer-property-keys)))))
15775 (list prop)))
15776 (save-excursion
15777 (save-restriction
15778 (widen)
15779 (goto-char (point-min))
15780 (let ((cnt 0))
15781 (while (re-search-forward
15782 (org-re-property property)
15783 nil t)
15784 (setq cnt (1+ cnt))
15785 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15786 (message "Property \"%s\" removed from %d entries" property cnt)))))
15788 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15790 (defun org-compute-property-at-point ()
15791 "Compute the property at point.
15792 This looks for an enclosing column format, extracts the operator and
15793 then applies it to the property in the column format's scope."
15794 (interactive)
15795 (unless (org-at-property-p)
15796 (user-error "Not at a property"))
15797 (let ((prop (org-match-string-no-properties 2)))
15798 (org-columns-get-format-and-top-level)
15799 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15800 (user-error "No operator defined for property %s" prop))
15801 (org-columns-compute prop)))
15803 (defvar org-property-allowed-value-functions nil
15804 "Hook for functions supplying allowed values for a specific property.
15805 The functions must take a single argument, the name of the property, and
15806 return a flat list of allowed values. If \":ETC\" is one of
15807 the values, this means that these values are intended as defaults for
15808 completion, but that other values should be allowed too.
15809 The functions must return nil if they are not responsible for this
15810 property.")
15812 (defun org-property-get-allowed-values (pom property &optional table)
15813 "Get allowed values for the property PROPERTY.
15814 When TABLE is non-nil, return an alist that can directly be used for
15815 completion."
15816 (let (vals)
15817 (cond
15818 ((equal property "TODO")
15819 (setq vals (org-with-point-at pom
15820 (append org-todo-keywords-1 '("")))))
15821 ((equal property "PRIORITY")
15822 (let ((n org-lowest-priority))
15823 (while (>= n org-highest-priority)
15824 (push (char-to-string n) vals)
15825 (setq n (1- n)))))
15826 ((member property org-special-properties))
15827 ((setq vals (run-hook-with-args-until-success
15828 'org-property-allowed-value-functions property)))
15830 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15831 (when (and vals (string-match "\\S-" vals))
15832 (setq vals (car (read-from-string (concat "(" vals ")"))))
15833 (setq vals (mapcar (lambda (x)
15834 (cond ((stringp x) x)
15835 ((numberp x) (number-to-string x))
15836 ((symbolp x) (symbol-name x))
15837 (t "???")))
15838 vals)))))
15839 (when (member ":ETC" vals)
15840 (setq vals (remove ":ETC" vals))
15841 (org-add-props (car vals) '(org-unrestricted t)))
15842 (if table (mapcar 'list vals) vals)))
15844 (defun org-property-previous-allowed-value (&optional previous)
15845 "Switch to the next allowed value for this property."
15846 (interactive)
15847 (org-property-next-allowed-value t))
15849 (defun org-property-next-allowed-value (&optional previous)
15850 "Switch to the next allowed value for this property."
15851 (interactive)
15852 (unless (org-at-property-p)
15853 (user-error "Not at a property"))
15854 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15855 (key (match-string 2))
15856 (value (match-string 3))
15857 (allowed (or (org-property-get-allowed-values (point) key)
15858 (and (member value '("[ ]" "[-]" "[X]"))
15859 '("[ ]" "[X]"))))
15860 (heading (save-match-data (nth 4 (org-heading-components))))
15861 nval)
15862 (unless allowed
15863 (user-error "Allowed values for this property have not been defined"))
15864 (if previous (setq allowed (reverse allowed)))
15865 (if (member value allowed)
15866 (setq nval (car (cdr (member value allowed)))))
15867 (setq nval (or nval (car allowed)))
15868 (if (equal nval value)
15869 (user-error "Only one allowed value for this property"))
15870 (org-at-property-p)
15871 (replace-match (concat " :" key ": " nval) t t)
15872 (org-indent-line)
15873 (beginning-of-line 1)
15874 (skip-chars-forward " \t")
15875 (when (equal prop org-effort-property)
15876 (save-excursion
15877 (org-back-to-heading t)
15878 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15879 (when (string= org-clock-current-task heading)
15880 (setq org-clock-effort nval)
15881 (org-clock-update-mode-line)))
15882 (run-hook-with-args 'org-property-changed-functions key nval)))
15884 (defun org-find-olp (path &optional this-buffer)
15885 "Return a marker pointing to the entry at outline path OLP.
15886 If anything goes wrong, throw an error.
15887 You can wrap this call to catch the error like this:
15889 (condition-case msg
15890 (org-mobile-locate-entry (match-string 4))
15891 (error (nth 1 msg)))
15893 The return value will then be either a string with the error message,
15894 or a marker if everything is OK.
15896 If THIS-BUFFER is set, the outline path does not contain a file,
15897 only headings."
15898 (let* ((file (if this-buffer buffer-file-name (pop path)))
15899 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15900 (level 1)
15901 (lmin 1)
15902 (lmax 1)
15903 limit re end found pos heading cnt flevel)
15904 (unless buffer (error "File not found :%s" file))
15905 (with-current-buffer buffer
15906 (save-excursion
15907 (save-restriction
15908 (widen)
15909 (setq limit (point-max))
15910 (goto-char (point-min))
15911 (while (setq heading (pop path))
15912 (setq re (format org-complex-heading-regexp-format
15913 (regexp-quote heading)))
15914 (setq cnt 0 pos (point))
15915 (while (re-search-forward re end t)
15916 (setq level (- (match-end 1) (match-beginning 1)))
15917 (if (and (>= level lmin) (<= level lmax))
15918 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15919 (when (= cnt 0) (error "Heading not found on level %d: %s"
15920 lmax heading))
15921 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15922 lmax heading))
15923 (goto-char found)
15924 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15925 (setq end (save-excursion (org-end-of-subtree t t))))
15926 (when (org-at-heading-p)
15927 (point-marker)))))))
15929 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15930 "Find node HEADING in BUFFER.
15931 Return a marker to the heading if it was found, or nil if not.
15932 If POS-ONLY is set, return just the position instead of a marker.
15934 The heading text must match exact, but it may have a TODO keyword,
15935 a priority cookie and tags in the standard locations."
15936 (with-current-buffer (or buffer (current-buffer))
15937 (save-excursion
15938 (save-restriction
15939 (widen)
15940 (goto-char (point-min))
15941 (let (case-fold-search)
15942 (if (re-search-forward
15943 (format org-complex-heading-regexp-format
15944 (regexp-quote heading)) nil t)
15945 (if pos-only
15946 (match-beginning 0)
15947 (move-marker (make-marker) (match-beginning 0)))))))))
15949 (defun org-find-exact-heading-in-directory (heading &optional dir)
15950 "Find Org node headline HEADING in all .org files in directory DIR.
15951 When the target headline is found, return a marker to this location."
15952 (let ((files (directory-files (or dir default-directory)
15953 nil "\\`[^.#].*\\.org\\'"))
15954 file visiting m buffer)
15955 (catch 'found
15956 (while (setq file (pop files))
15957 (message "trying %s" file)
15958 (setq visiting (org-find-base-buffer-visiting file))
15959 (setq buffer (or visiting (find-file-noselect file)))
15960 (setq m (org-find-exact-headline-in-buffer
15961 heading buffer))
15962 (when (and (not m) (not visiting)) (kill-buffer buffer))
15963 (and m (throw 'found m))))))
15965 (defun org-find-entry-with-id (ident)
15966 "Locate the entry that contains the ID property with exact value IDENT.
15967 IDENT can be a string, a symbol or a number, this function will search for
15968 the string representation of it.
15969 Return the position where this entry starts, or nil if there is no such entry."
15970 (interactive "sID: ")
15971 (let ((id (cond
15972 ((stringp ident) ident)
15973 ((symbol-name ident) (symbol-name ident))
15974 ((numberp ident) (number-to-string ident))
15975 (t (error "IDENT %s must be a string, symbol or number" ident))))
15976 (case-fold-search nil))
15977 (save-excursion
15978 (save-restriction
15979 (widen)
15980 (goto-char (point-min))
15981 (when (re-search-forward
15982 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15983 nil t)
15984 (org-back-to-heading t)
15985 (point))))))
15987 ;;;; Timestamps
15989 (defvar org-last-changed-timestamp nil)
15990 (defvar org-last-inserted-timestamp nil
15991 "The last time stamp inserted with `org-insert-time-stamp'.")
15992 (defvar org-time-was-given) ; dynamically scoped parameter
15993 (defvar org-end-time-was-given) ; dynamically scoped parameter
15994 (defvar org-ts-what) ; dynamically scoped parameter
15996 (defun org-time-stamp (arg &optional inactive)
15997 "Prompt for a date/time and insert a time stamp.
15998 If the user specifies a time like HH:MM or if this command is
15999 called with at least one prefix argument, the time stamp contains
16000 the date and the time. Otherwise, only the date is be included.
16002 All parts of a date not specified by the user is filled in from
16003 the current date/time. So if you just press return without
16004 typing anything, the time stamp will represent the current
16005 date/time.
16007 If there is already a timestamp at the cursor, it will be
16008 modified.
16010 With two universal prefix arguments, insert an active timestamp
16011 with the current time without prompting the user."
16012 (interactive "P")
16013 (let* ((ts nil)
16014 (default-time
16015 ;; Default time is either today, or, when entering a range,
16016 ;; the range start.
16017 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16018 (save-excursion
16019 (re-search-backward
16020 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16021 (- (point) 20) t)))
16022 (apply 'encode-time (org-parse-time-string (match-string 1)))
16023 (current-time)))
16024 (default-input (and ts (org-get-compact-tod ts)))
16025 (repeater (save-excursion
16026 (save-match-data
16027 (beginning-of-line)
16028 (when (re-search-forward
16029 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16030 (save-excursion (progn (end-of-line) (point))) t)
16031 (match-string 0)))))
16032 org-time-was-given org-end-time-was-given time)
16033 (cond
16034 ((and (org-at-timestamp-p t)
16035 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16036 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16037 (insert "--")
16038 (setq time (let ((this-command this-command))
16039 (org-read-date arg 'totime nil nil
16040 default-time default-input inactive)))
16041 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16042 ((org-at-timestamp-p t)
16043 (setq time (let ((this-command this-command))
16044 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16045 (when (org-at-timestamp-p t) ; just to get the match data
16046 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16047 (replace-match "")
16048 (setq org-last-changed-timestamp
16049 (org-insert-time-stamp
16050 time (or org-time-was-given arg)
16051 inactive nil nil (list org-end-time-was-given)))
16052 (when repeater (goto-char (1- (point))) (insert " " repeater)
16053 (setq org-last-changed-timestamp
16054 (concat (substring org-last-inserted-timestamp 0 -1)
16055 " " repeater ">"))))
16056 (message "Timestamp updated"))
16057 ((equal arg '(16))
16058 (org-insert-time-stamp (current-time) t))
16060 (setq time (let ((this-command this-command))
16061 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16062 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16063 nil nil (list org-end-time-was-given))))))
16065 ;; FIXME: can we use this for something else, like computing time differences?
16066 (defun org-get-compact-tod (s)
16067 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16068 (let* ((t1 (match-string 1 s))
16069 (h1 (string-to-number (match-string 2 s)))
16070 (m1 (string-to-number (match-string 3 s)))
16071 (t2 (and (match-end 4) (match-string 5 s)))
16072 (h2 (and t2 (string-to-number (match-string 6 s))))
16073 (m2 (and t2 (string-to-number (match-string 7 s))))
16074 dh dm)
16075 (if (not t2)
16077 (setq dh (- h2 h1) dm (- m2 m1))
16078 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16079 (concat t1 "+" (number-to-string dh)
16080 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16082 (defun org-time-stamp-inactive (&optional arg)
16083 "Insert an inactive time stamp.
16084 An inactive time stamp is enclosed in square brackets instead of angle
16085 brackets. It is inactive in the sense that it does not trigger agenda entries,
16086 does not link to the calendar and cannot be changed with the S-cursor keys.
16087 So these are more for recording a certain time/date."
16088 (interactive "P")
16089 (org-time-stamp arg 'inactive))
16091 (defvar org-date-ovl (make-overlay 1 1))
16092 (overlay-put org-date-ovl 'face 'org-date-selected)
16093 (org-detach-overlay org-date-ovl)
16095 (defvar org-ans1) ; dynamically scoped parameter
16096 (defvar org-ans2) ; dynamically scoped parameter
16098 (defvar org-plain-time-of-day-regexp) ; defined below
16100 (defvar org-overriding-default-time nil) ; dynamically scoped
16101 (defvar org-read-date-overlay nil)
16102 (defvar org-dcst nil) ; dynamically scoped
16103 (defvar org-read-date-history nil)
16104 (defvar org-read-date-final-answer nil)
16105 (defvar org-read-date-analyze-futurep nil)
16106 (defvar org-read-date-analyze-forced-year nil)
16107 (defvar org-read-date-inactive)
16109 (defvar org-read-date-minibuffer-local-map
16110 (let ((map (make-sparse-keymap)))
16111 (set-keymap-parent map minibuffer-local-map)
16112 (org-defkey map (kbd ".")
16113 (lambda () (interactive)
16114 ;; Are we at the beginning of the prompt?
16115 (if (looking-back "^[^:]+: ")
16116 (org-eval-in-calendar '(calendar-goto-today))
16117 (insert "."))))
16118 (org-defkey map (kbd "C-.")
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(calendar-goto-today))))
16121 (org-defkey map [(meta shift left)]
16122 (lambda () (interactive)
16123 (org-eval-in-calendar '(calendar-backward-month 1))))
16124 (org-defkey map [(meta shift right)]
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-forward-month 1))))
16127 (org-defkey map [(meta shift up)]
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-backward-year 1))))
16130 (org-defkey map [(meta shift down)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-forward-year 1))))
16133 (org-defkey map [?\e (shift left)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-backward-month 1))))
16136 (org-defkey map [?\e (shift right)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-forward-month 1))))
16139 (org-defkey map [?\e (shift up)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-backward-year 1))))
16142 (org-defkey map [?\e (shift down)]
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-forward-year 1))))
16145 (org-defkey map [(shift up)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-backward-week 1))))
16148 (org-defkey map [(shift down)]
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-forward-week 1))))
16151 (org-defkey map [(shift left)]
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-backward-day 1))))
16154 (org-defkey map [(shift right)]
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-forward-day 1))))
16157 (org-defkey map "!"
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(diary-view-entries))
16160 (message "")))
16161 (org-defkey map ">"
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(scroll-calendar-left 1))))
16164 (org-defkey map "<"
16165 (lambda () (interactive)
16166 (org-eval-in-calendar '(scroll-calendar-right 1))))
16167 (org-defkey map "\C-v"
16168 (lambda () (interactive)
16169 (org-eval-in-calendar
16170 '(calendar-scroll-left-three-months 1))))
16171 (org-defkey map "\M-v"
16172 (lambda () (interactive)
16173 (org-eval-in-calendar
16174 '(calendar-scroll-right-three-months 1))))
16175 map)
16176 "Keymap for minibuffer commands when using `org-read-date'.")
16178 (defun org-read-date (&optional org-with-time to-time from-string prompt
16179 default-time default-input inactive)
16180 "Read a date, possibly a time, and make things smooth for the user.
16181 The prompt will suggest to enter an ISO date, but you can also enter anything
16182 which will at least partially be understood by `parse-time-string'.
16183 Unrecognized parts of the date will default to the current day, month, year,
16184 hour and minute. If this command is called to replace a timestamp at point,
16185 or to enter the second timestamp of a range, the default time is taken
16186 from the existing stamp. Furthermore, the command prefers the future,
16187 so if you are giving a date where the year is not given, and the day-month
16188 combination is already past in the current year, it will assume you
16189 mean next year. For details, see the manual. A few examples:
16191 3-2-5 --> 2003-02-05
16192 feb 15 --> currentyear-02-15
16193 2/15 --> currentyear-02-15
16194 sep 12 9 --> 2009-09-12
16195 12:45 --> today 12:45
16196 22 sept 0:34 --> currentyear-09-22 0:34
16197 12 --> currentyear-currentmonth-12
16198 Fri --> nearest Friday after today
16199 -Tue --> last Tuesday
16200 etc.
16202 Furthermore you can specify a relative date by giving, as the *first* thing
16203 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16204 change in days weeks, months, years.
16205 With a single plus or minus, the date is relative to today. With a double
16206 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16207 +4d --> four days from today
16208 +4 --> same as above
16209 +2w --> two weeks from today
16210 ++5 --> five days from default date
16212 The function understands only English month and weekday abbreviations.
16214 While prompting, a calendar is popped up - you can also select the
16215 date with the mouse (button 1). The calendar shows a period of three
16216 months. To scroll it to other months, use the keys `>' and `<'.
16217 If you don't like the calendar, turn it off with
16218 \(setq org-read-date-popup-calendar nil)
16220 With optional argument TO-TIME, the date will immediately be converted
16221 to an internal time.
16222 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16223 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16224 still enter a time, and this function will inform the calling routine
16225 about this change. The calling routine may then choose to change the
16226 format used to insert the time stamp into the buffer to include the time.
16227 With optional argument FROM-STRING, read from this string instead from
16228 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16229 the time/date that is used for everything that is not specified by the
16230 user."
16231 (require 'parse-time)
16232 (let* ((org-time-stamp-rounding-minutes
16233 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16234 (org-dcst org-display-custom-times)
16235 (ct (org-current-time))
16236 (org-def (or org-overriding-default-time default-time ct))
16237 (org-defdecode (decode-time org-def))
16238 (dummy (progn
16239 (when (< (nth 2 org-defdecode) org-extend-today-until)
16240 (setcar (nthcdr 2 org-defdecode) -1)
16241 (setcar (nthcdr 1 org-defdecode) 59)
16242 (setq org-def (apply 'encode-time org-defdecode)
16243 org-defdecode (decode-time org-def)))))
16244 (mouse-autoselect-window nil) ; Don't let the mouse jump
16245 (calendar-frame-setup nil)
16246 (calendar-setup nil)
16247 (calendar-move-hook nil)
16248 (calendar-view-diary-initially-flag nil)
16249 (calendar-view-holidays-initially-flag nil)
16250 (timestr (format-time-string
16251 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16252 (prompt (concat (if prompt (concat prompt " ") "")
16253 (format "Date+time [%s]: " timestr)))
16254 ans (org-ans0 "") org-ans1 org-ans2 final)
16256 (cond
16257 (from-string (setq ans from-string))
16258 (org-read-date-popup-calendar
16259 (save-excursion
16260 (save-window-excursion
16261 (calendar)
16262 (org-eval-in-calendar '(setq cursor-type nil) t)
16263 (unwind-protect
16264 (progn
16265 (calendar-forward-day (- (time-to-days org-def)
16266 (calendar-absolute-from-gregorian
16267 (calendar-current-date))))
16268 (org-eval-in-calendar nil t)
16269 (let* ((old-map (current-local-map))
16270 (map (copy-keymap calendar-mode-map))
16271 (minibuffer-local-map
16272 (copy-keymap org-read-date-minibuffer-local-map)))
16273 (org-defkey map (kbd "RET") 'org-calendar-select)
16274 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16275 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16276 (unwind-protect
16277 (progn
16278 (use-local-map map)
16279 (setq org-read-date-inactive inactive)
16280 (add-hook 'post-command-hook 'org-read-date-display)
16281 (setq org-ans0 (read-string prompt default-input
16282 'org-read-date-history nil))
16283 ;; org-ans0: from prompt
16284 ;; org-ans1: from mouse click
16285 ;; org-ans2: from calendar motion
16286 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16287 (remove-hook 'post-command-hook 'org-read-date-display)
16288 (use-local-map old-map)
16289 (when org-read-date-overlay
16290 (delete-overlay org-read-date-overlay)
16291 (setq org-read-date-overlay nil)))))
16292 (bury-buffer "*Calendar*")))))
16294 (t ; Naked prompt only
16295 (unwind-protect
16296 (setq ans (read-string prompt default-input
16297 'org-read-date-history timestr))
16298 (when org-read-date-overlay
16299 (delete-overlay org-read-date-overlay)
16300 (setq org-read-date-overlay nil)))))
16302 (setq final (org-read-date-analyze ans org-def org-defdecode))
16304 (when org-read-date-analyze-forced-year
16305 (message "Year was forced into %s"
16306 (if org-read-date-force-compatible-dates
16307 "compatible range (1970-2037)"
16308 "range representable on this machine"))
16309 (ding))
16311 ;; One round trip to get rid of 34th of August and stuff like that....
16312 (setq final (decode-time (apply 'encode-time final)))
16314 (setq org-read-date-final-answer ans)
16316 (if to-time
16317 (apply 'encode-time final)
16318 (if (and (boundp 'org-time-was-given) org-time-was-given)
16319 (format "%04d-%02d-%02d %02d:%02d"
16320 (nth 5 final) (nth 4 final) (nth 3 final)
16321 (nth 2 final) (nth 1 final))
16322 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16324 (defvar org-def)
16325 (defvar org-defdecode)
16326 (defvar org-with-time)
16327 (defun org-read-date-display ()
16328 "Display the current date prompt interpretation in the minibuffer."
16329 (when org-read-date-display-live
16330 (when org-read-date-overlay
16331 (delete-overlay org-read-date-overlay))
16332 (when (minibufferp (current-buffer))
16333 (save-excursion
16334 (end-of-line 1)
16335 (while (not (equal (buffer-substring
16336 (max (point-min) (- (point) 4)) (point))
16337 " "))
16338 (insert " ")))
16339 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16340 " " (or org-ans1 org-ans2)))
16341 (org-end-time-was-given nil)
16342 (f (org-read-date-analyze ans org-def org-defdecode))
16343 (fmts (if org-dcst
16344 org-time-stamp-custom-formats
16345 org-time-stamp-formats))
16346 (fmt (if (or org-with-time
16347 (and (boundp 'org-time-was-given) org-time-was-given))
16348 (cdr fmts)
16349 (car fmts)))
16350 (txt (format-time-string fmt (apply 'encode-time f)))
16351 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16352 (txt (concat "=> " txt)))
16353 (when (and org-end-time-was-given
16354 (string-match org-plain-time-of-day-regexp txt))
16355 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16356 org-end-time-was-given
16357 (substring txt (match-end 0)))))
16358 (when org-read-date-analyze-futurep
16359 (setq txt (concat txt " (=>F)")))
16360 (setq org-read-date-overlay
16361 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16362 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16364 (defun org-read-date-analyze (ans org-def org-defdecode)
16365 "Analyze the combined answer of the date prompt."
16366 ;; FIXME: cleanup and comment
16367 (let ((nowdecode (decode-time (current-time)))
16368 delta deltan deltaw deltadef year month day
16369 hour minute second wday pm h2 m2 tl wday1
16370 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16371 (setq org-read-date-analyze-futurep nil
16372 org-read-date-analyze-forced-year nil)
16373 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16374 (setq ans "+0"))
16376 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16377 (setq ans (replace-match "" t t ans)
16378 deltan (car delta)
16379 deltaw (nth 1 delta)
16380 deltadef (nth 2 delta)))
16382 ;; Check if there is an iso week date in there. If yes, store the
16383 ;; info and postpone interpreting it until the rest of the parsing
16384 ;; is done.
16385 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16386 (setq iso-year (if (match-end 1)
16387 (org-small-year-to-year
16388 (string-to-number (match-string 1 ans))))
16389 iso-weekday (if (match-end 3)
16390 (string-to-number (match-string 3 ans)))
16391 iso-week (string-to-number (match-string 2 ans)))
16392 (setq ans (replace-match "" t t ans)))
16394 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16395 (when (string-match
16396 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16397 (setq year (if (match-end 2)
16398 (string-to-number (match-string 2 ans))
16399 (progn (setq kill-year t)
16400 (string-to-number (format-time-string "%Y"))))
16401 month (string-to-number (match-string 3 ans))
16402 day (string-to-number (match-string 4 ans)))
16403 (if (< year 100) (setq year (+ 2000 year)))
16404 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16405 t nil ans)))
16407 ;; Help matching dotted european dates
16408 (when (string-match
16409 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16410 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16411 (setq kill-year t)
16412 (string-to-number (format-time-string "%Y")))
16413 day (string-to-number (match-string 1 ans))
16414 month (string-to-number (match-string 2 ans))
16415 ans (replace-match (format "%04d-%02d-%02d" year month day)
16416 t nil ans)))
16418 ;; Help matching american dates, like 5/30 or 5/30/7
16419 (when (string-match
16420 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16421 (setq year (if (match-end 4)
16422 (string-to-number (match-string 4 ans))
16423 (progn (setq kill-year t)
16424 (string-to-number (format-time-string "%Y"))))
16425 month (string-to-number (match-string 1 ans))
16426 day (string-to-number (match-string 2 ans)))
16427 (if (< year 100) (setq year (+ 2000 year)))
16428 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16429 t nil ans)))
16430 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16431 ;; If there is a time with am/pm, and *no* time without it, we convert
16432 ;; so that matching will be successful.
16433 (loop for i from 1 to 2 do ; twice, for end time as well
16434 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16435 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16436 (setq hour (string-to-number (match-string 1 ans))
16437 minute (if (match-end 3)
16438 (string-to-number (match-string 3 ans))
16440 pm (equal ?p
16441 (string-to-char (downcase (match-string 4 ans)))))
16442 (if (and (= hour 12) (not pm))
16443 (setq hour 0)
16444 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16445 (setq ans (replace-match (format "%02d:%02d" hour minute)
16446 t t ans))))
16448 ;; Check if a time range is given as a duration
16449 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16450 (setq hour (string-to-number (match-string 1 ans))
16451 h2 (+ hour (string-to-number (match-string 3 ans)))
16452 minute (string-to-number (match-string 2 ans))
16453 m2 (+ minute (if (match-end 5) (string-to-number
16454 (match-string 5 ans))0)))
16455 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16456 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16457 t t ans)))
16459 ;; Check if there is a time range
16460 (when (boundp 'org-end-time-was-given)
16461 (setq org-time-was-given nil)
16462 (when (and (string-match org-plain-time-of-day-regexp ans)
16463 (match-end 8))
16464 (setq org-end-time-was-given (match-string 8 ans))
16465 (setq ans (concat (substring ans 0 (match-beginning 7))
16466 (substring ans (match-end 7))))))
16468 (setq tl (parse-time-string ans)
16469 day (or (nth 3 tl) (nth 3 org-defdecode))
16470 month (or (nth 4 tl)
16471 (if (and org-read-date-prefer-future
16472 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16473 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16474 (nth 4 org-defdecode)))
16475 year (or (and (not kill-year) (nth 5 tl))
16476 (if (and org-read-date-prefer-future
16477 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16478 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16479 (nth 5 org-defdecode)))
16480 hour (or (nth 2 tl) (nth 2 org-defdecode))
16481 minute (or (nth 1 tl) (nth 1 org-defdecode))
16482 second (or (nth 0 tl) 0)
16483 wday (nth 6 tl))
16485 (when (and (eq org-read-date-prefer-future 'time)
16486 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16487 (equal day (nth 3 nowdecode))
16488 (equal month (nth 4 nowdecode))
16489 (equal year (nth 5 nowdecode))
16490 (nth 2 tl)
16491 (or (< (nth 2 tl) (nth 2 nowdecode))
16492 (and (= (nth 2 tl) (nth 2 nowdecode))
16493 (nth 1 tl)
16494 (< (nth 1 tl) (nth 1 nowdecode)))))
16495 (setq day (1+ day)
16496 futurep t))
16498 ;; Special date definitions below
16499 (cond
16500 (iso-week
16501 ;; There was an iso week
16502 (require 'cal-iso)
16503 (setq futurep nil)
16504 (setq year (or iso-year year)
16505 day (or iso-weekday wday 1)
16506 wday nil ; to make sure that the trigger below does not match
16507 iso-date (calendar-gregorian-from-absolute
16508 (calendar-absolute-from-iso
16509 (list iso-week day year))))
16510 ; FIXME: Should we also push ISO weeks into the future?
16511 ; (when (and org-read-date-prefer-future
16512 ; (not iso-year)
16513 ; (< (calendar-absolute-from-gregorian iso-date)
16514 ; (time-to-days (current-time))))
16515 ; (setq year (1+ year)
16516 ; iso-date (calendar-gregorian-from-absolute
16517 ; (calendar-absolute-from-iso
16518 ; (list iso-week day year)))))
16519 (setq month (car iso-date)
16520 year (nth 2 iso-date)
16521 day (nth 1 iso-date)))
16522 (deltan
16523 (setq futurep nil)
16524 (unless deltadef
16525 (let ((now (decode-time (current-time))))
16526 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16527 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16528 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16529 ((equal deltaw "m") (setq month (+ month deltan)))
16530 ((equal deltaw "y") (setq year (+ year deltan)))))
16531 ((and wday (not (nth 3 tl)))
16532 ;; Weekday was given, but no day, so pick that day in the week
16533 ;; on or after the derived date.
16534 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16535 (unless (equal wday wday1)
16536 (setq day (+ day (% (- wday wday1 -7) 7))))))
16537 (if (and (boundp 'org-time-was-given)
16538 (nth 2 tl))
16539 (setq org-time-was-given t))
16540 (if (< year 100) (setq year (+ 2000 year)))
16541 ;; Check of the date is representable
16542 (if org-read-date-force-compatible-dates
16543 (progn
16544 (if (< year 1970)
16545 (setq year 1970 org-read-date-analyze-forced-year t))
16546 (if (> year 2037)
16547 (setq year 2037 org-read-date-analyze-forced-year t)))
16548 (condition-case nil
16549 (ignore (encode-time second minute hour day month year))
16550 (error
16551 (setq year (nth 5 org-defdecode))
16552 (setq org-read-date-analyze-forced-year t))))
16553 (setq org-read-date-analyze-futurep futurep)
16554 (list second minute hour day month year)))
16556 (defvar parse-time-weekdays)
16557 (defun org-read-date-get-relative (s today default)
16558 "Check string S for special relative date string.
16559 TODAY and DEFAULT are internal times, for today and for a default.
16560 Return shift list (N what def-flag)
16561 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16562 N is the number of WHATs to shift.
16563 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16564 the DEFAULT date rather than TODAY."
16565 (require 'parse-time)
16566 (when (and
16567 (string-match
16568 (concat
16569 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16570 "\\([0-9]+\\)?"
16571 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16572 "\\([ \t]\\|$\\)") s)
16573 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16574 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16575 (string-to-char (substring (match-string 1 s) -1))
16576 ?+))
16577 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16578 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16579 (what (if (match-end 3) (match-string 3 s) "d"))
16580 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16581 (date (if rel default today))
16582 (wday (nth 6 (decode-time date)))
16583 delta)
16584 (if wday1
16585 (progn
16586 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16587 (if (= delta 0) (setq delta 7))
16588 (if (= dir ?-)
16589 (progn
16590 (setq delta (- delta 7))
16591 (if (= delta 0) (setq delta -7))))
16592 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16593 (list delta "d" rel))
16594 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16596 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16597 "Turn a user-specified date into the internal representation.
16598 The internal representation needed by the calendar is (month day year).
16599 This is a wrapper to handle the brain-dead convention in calendar that
16600 user function argument order change dependent on argument order."
16601 (if (boundp 'calendar-date-style)
16602 (cond
16603 ((eq calendar-date-style 'american)
16604 (list arg1 arg2 arg3))
16605 ((eq calendar-date-style 'european)
16606 (list arg2 arg1 arg3))
16607 ((eq calendar-date-style 'iso)
16608 (list arg2 arg3 arg1)))
16609 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16610 (if (org-bound-and-true-p european-calendar-style)
16611 (list arg2 arg1 arg3)
16612 (list arg1 arg2 arg3)))))
16614 (defun org-eval-in-calendar (form &optional keepdate)
16615 "Eval FORM in the calendar window and return to current window.
16616 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16617 otherwise stick to the current value of `org-ans2'."
16618 (let ((sf (selected-frame))
16619 (sw (selected-window)))
16620 (select-window (get-buffer-window "*Calendar*" t))
16621 (eval form)
16622 (when (and (not keepdate) (calendar-cursor-to-date))
16623 (let* ((date (calendar-cursor-to-date))
16624 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16625 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16626 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16627 (select-window sw)
16628 (org-select-frame-set-input-focus sf)))
16630 (defun org-calendar-select ()
16631 "Return to `org-read-date' with the date currently selected.
16632 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16633 (interactive)
16634 (when (calendar-cursor-to-date)
16635 (let* ((date (calendar-cursor-to-date))
16636 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16637 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16638 (if (active-minibuffer-window) (exit-minibuffer))))
16640 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16641 "Insert a date stamp for the date given by the internal TIME.
16642 WITH-HM means use the stamp format that includes the time of the day.
16643 INACTIVE means use square brackets instead of angular ones, so that the
16644 stamp will not contribute to the agenda.
16645 PRE and POST are optional strings to be inserted before and after the
16646 stamp.
16647 The command returns the inserted time stamp."
16648 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16649 stamp)
16650 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16651 (insert-before-markers (or pre ""))
16652 (when (listp extra)
16653 (setq extra (car extra))
16654 (if (and (stringp extra)
16655 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16656 (setq extra (format "-%02d:%02d"
16657 (string-to-number (match-string 1 extra))
16658 (string-to-number (match-string 2 extra))))
16659 (setq extra nil)))
16660 (when extra
16661 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16662 (insert-before-markers (setq stamp (format-time-string fmt time)))
16663 (insert-before-markers (or post ""))
16664 (setq org-last-inserted-timestamp stamp)))
16666 (defun org-toggle-time-stamp-overlays ()
16667 "Toggle the use of custom time stamp formats."
16668 (interactive)
16669 (setq org-display-custom-times (not org-display-custom-times))
16670 (unless org-display-custom-times
16671 (let ((p (point-min)) (bmp (buffer-modified-p)))
16672 (while (setq p (next-single-property-change p 'display))
16673 (if (and (get-text-property p 'display)
16674 (eq (get-text-property p 'face) 'org-date))
16675 (remove-text-properties
16676 p (setq p (next-single-property-change p 'display))
16677 '(display t))))
16678 (set-buffer-modified-p bmp)))
16679 (if (featurep 'xemacs)
16680 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16681 (org-restart-font-lock)
16682 (setq org-table-may-need-update t)
16683 (if org-display-custom-times
16684 (message "Time stamps are overlaid with custom format")
16685 (message "Time stamp overlays removed")))
16687 (defun org-display-custom-time (beg end)
16688 "Overlay modified time stamp format over timestamp between BEG and END."
16689 (let* ((ts (buffer-substring beg end))
16690 t1 w1 with-hm tf time str w2 (off 0))
16691 (save-match-data
16692 (setq t1 (org-parse-time-string ts t))
16693 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16694 (setq off (- (match-end 0) (match-beginning 0)))))
16695 (setq end (- end off))
16696 (setq w1 (- end beg)
16697 with-hm (and (nth 1 t1) (nth 2 t1))
16698 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16699 time (org-fix-decoded-time t1)
16700 str (org-add-props
16701 (format-time-string
16702 (substring tf 1 -1) (apply 'encode-time time))
16703 nil 'mouse-face 'highlight)
16704 w2 (length str))
16705 (if (not (= w2 w1))
16706 (add-text-properties (1+ beg) (+ 2 beg)
16707 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16708 (if (featurep 'xemacs)
16709 (progn
16710 (put-text-property beg end 'invisible t)
16711 (put-text-property beg end 'end-glyph (make-glyph str)))
16712 (put-text-property beg end 'display str))))
16714 (defun org-translate-time (string)
16715 "Translate all timestamps in STRING to custom format.
16716 But do this only if the variable `org-display-custom-times' is set."
16717 (when org-display-custom-times
16718 (save-match-data
16719 (let* ((start 0)
16720 (re org-ts-regexp-both)
16721 t1 with-hm inactive tf time str beg end)
16722 (while (setq start (string-match re string start))
16723 (setq beg (match-beginning 0)
16724 end (match-end 0)
16725 t1 (save-match-data
16726 (org-parse-time-string (substring string beg end) t))
16727 with-hm (and (nth 1 t1) (nth 2 t1))
16728 inactive (equal (substring string beg (1+ beg)) "[")
16729 tf (funcall (if with-hm 'cdr 'car)
16730 org-time-stamp-custom-formats)
16731 time (org-fix-decoded-time t1)
16732 str (format-time-string
16733 (concat
16734 (if inactive "[" "<") (substring tf 1 -1)
16735 (if inactive "]" ">"))
16736 (apply 'encode-time time))
16737 string (replace-match str t t string)
16738 start (+ start (length str)))))))
16739 string)
16741 (defun org-fix-decoded-time (time)
16742 "Set 0 instead of nil for the first 6 elements of time.
16743 Don't touch the rest."
16744 (let ((n 0))
16745 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16747 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16749 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16750 "Difference between TIMESTAMP-STRING and now in days.
16751 If SECONDS is non-nil, return the difference in seconds."
16752 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16753 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16754 (funcall fdiff (current-time)))))
16756 (defun org-deadline-close (timestamp-string &optional ndays)
16757 "Is the time in TIMESTAMP-STRING close to the current date?"
16758 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16759 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16760 (not (org-entry-is-done-p))))
16762 (defun org-get-wdays (ts &optional delay zero-delay)
16763 "Get the deadline lead time appropriate for timestring TS.
16764 When DELAY is non-nil, get the delay time for scheduled items
16765 instead of the deadline lead time. When ZERO-DELAY is non-nil
16766 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16767 don't try to find the delay cookie in the scheduled timestamp."
16768 (let ((tv (if delay org-scheduled-delay-days
16769 org-deadline-warning-days)))
16770 (cond
16771 ((or (and delay (< tv 0))
16772 (and delay zero-delay (<= tv 0))
16773 (and (not delay) (<= tv 0)))
16774 ;; Enforce this value no matter what
16775 (- tv))
16776 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16777 ;; lead time is specified.
16778 (floor (* (string-to-number (match-string 1 ts))
16779 (cdr (assoc (match-string 2 ts)
16780 '(("d" . 1) ("w" . 7)
16781 ("m" . 30.4) ("y" . 365.25)
16782 ("h" . 0.041667)))))))
16783 ;; go for the default.
16784 (t tv))))
16786 (defun org-calendar-select-mouse (ev)
16787 "Return to `org-read-date' with the date currently selected.
16788 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16789 (interactive "e")
16790 (mouse-set-point ev)
16791 (when (calendar-cursor-to-date)
16792 (let* ((date (calendar-cursor-to-date))
16793 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16794 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16795 (if (active-minibuffer-window) (exit-minibuffer))))
16797 (defun org-check-deadlines (ndays)
16798 "Check if there are any deadlines due or past due.
16799 A deadline is considered due if it happens within `org-deadline-warning-days'
16800 days from today's date. If the deadline appears in an entry marked DONE,
16801 it is not shown. The prefix arg NDAYS can be used to test that many
16802 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16803 (interactive "P")
16804 (let* ((org-warn-days
16805 (cond
16806 ((equal ndays '(4)) 100000)
16807 (ndays (prefix-numeric-value ndays))
16808 (t (abs org-deadline-warning-days))))
16809 (case-fold-search nil)
16810 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16811 (callback
16812 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16814 (message "%d deadlines past-due or due within %d days"
16815 (org-occur regexp nil callback)
16816 org-warn-days)))
16818 (defsubst org-re-timestamp (type)
16819 "Return a regexp for timestamp TYPE.
16820 Allowed values for TYPE are:
16822 all: all timestamps
16823 active: only active timestamps (<...>)
16824 inactive: only inactive timestamps ([...])
16825 scheduled: only scheduled timestamps
16826 deadline: only deadline timestamps
16827 closed: only closed time-stamps
16829 When TYPE is nil, fall back on returning a regexp that matches
16830 both scheduled and deadline timestamps."
16831 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16832 ((eq type 'active) org-ts-regexp)
16833 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16834 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16835 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16836 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16837 ((eq type 'scheduled-or-deadline)
16838 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16840 (defun org-check-before-date (date)
16841 "Check if there are deadlines or scheduled entries before DATE."
16842 (interactive (list (org-read-date)))
16843 (let ((case-fold-search nil)
16844 (regexp (org-re-timestamp org-ts-type))
16845 (callback
16846 (lambda () (time-less-p
16847 (org-time-string-to-time (match-string 1))
16848 (org-time-string-to-time date)))))
16849 (message "%d entries before %s"
16850 (org-occur regexp nil callback) date)))
16852 (defun org-check-after-date (date)
16853 "Check if there are deadlines or scheduled entries after DATE."
16854 (interactive (list (org-read-date)))
16855 (let ((case-fold-search nil)
16856 (regexp (org-re-timestamp org-ts-type))
16857 (callback
16858 (lambda () (not
16859 (time-less-p
16860 (org-time-string-to-time (match-string 1))
16861 (org-time-string-to-time date))))))
16862 (message "%d entries after %s"
16863 (org-occur regexp nil callback) date)))
16865 (defun org-check-dates-range (start-date end-date)
16866 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16867 (interactive (list (org-read-date nil nil nil "Range starts")
16868 (org-read-date nil nil nil "Range end")))
16869 (let ((case-fold-search nil)
16870 (regexp (org-re-timestamp org-ts-type))
16871 (callback
16872 (lambda ()
16873 (let ((match (match-string 1)))
16874 (and
16875 (not (time-less-p
16876 (org-time-string-to-time match)
16877 (org-time-string-to-time start-date)))
16878 (time-less-p
16879 (org-time-string-to-time match)
16880 (org-time-string-to-time end-date)))))))
16881 (message "%d entries between %s and %s"
16882 (org-occur regexp nil callback) start-date end-date)))
16884 (defun org-evaluate-time-range (&optional to-buffer)
16885 "Evaluate a time range by computing the difference between start and end.
16886 Normally the result is just printed in the echo area, but with prefix arg
16887 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16888 If the time range is actually in a table, the result is inserted into the
16889 next column.
16890 For time difference computation, a year is assumed to be exactly 365
16891 days in order to avoid rounding problems."
16892 (interactive "P")
16894 (org-clock-update-time-maybe)
16895 (save-excursion
16896 (unless (org-at-date-range-p t)
16897 (goto-char (point-at-bol))
16898 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16899 (if (not (org-at-date-range-p t))
16900 (user-error "Not at a time-stamp range, and none found in current line")))
16901 (let* ((ts1 (match-string 1))
16902 (ts2 (match-string 2))
16903 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16904 (match-end (match-end 0))
16905 (time1 (org-time-string-to-time ts1))
16906 (time2 (org-time-string-to-time ts2))
16907 (t1 (org-float-time time1))
16908 (t2 (org-float-time time2))
16909 (diff (abs (- t2 t1)))
16910 (negative (< (- t2 t1) 0))
16911 ;; (ys (floor (* 365 24 60 60)))
16912 (ds (* 24 60 60))
16913 (hs (* 60 60))
16914 (fy "%dy %dd %02d:%02d")
16915 (fy1 "%dy %dd")
16916 (fd "%dd %02d:%02d")
16917 (fd1 "%dd")
16918 (fh "%02d:%02d")
16919 y d h m align)
16920 (if havetime
16921 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16923 d (floor (/ diff ds)) diff (mod diff ds)
16924 h (floor (/ diff hs)) diff (mod diff hs)
16925 m (floor (/ diff 60)))
16926 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16928 d (floor (+ (/ diff ds) 0.5))
16929 h 0 m 0))
16930 (if (not to-buffer)
16931 (message "%s" (org-make-tdiff-string y d h m))
16932 (if (org-at-table-p)
16933 (progn
16934 (goto-char match-end)
16935 (setq align t)
16936 (and (looking-at " *|") (goto-char (match-end 0))))
16937 (goto-char match-end))
16938 (if (looking-at
16939 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16940 (replace-match ""))
16941 (if negative (insert " -"))
16942 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16943 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16944 (insert " " (format fh h m))))
16945 (if align (org-table-align))
16946 (message "Time difference inserted")))))
16948 (defun org-make-tdiff-string (y d h m)
16949 (let ((fmt "")
16950 (l nil))
16951 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16952 l (push y l)))
16953 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16954 l (push d l)))
16955 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16956 l (push h l)))
16957 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16958 l (push m l)))
16959 (apply 'format fmt (nreverse l))))
16961 (defun org-time-string-to-time (s &optional buffer pos)
16962 "Convert a timestamp string into internal time."
16963 (condition-case errdata
16964 (apply 'encode-time (org-parse-time-string s))
16965 (error (error "Bad timestamp `%s'%s\nError was: %s"
16966 s (if (not (and buffer pos))
16968 (format " at %d in buffer `%s'" pos buffer))
16969 (cdr errdata)))))
16971 (defun org-time-string-to-seconds (s)
16972 "Convert a timestamp string to a number of seconds."
16973 (org-float-time (org-time-string-to-time s)))
16975 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16976 "Convert a time stamp to an absolute day number.
16977 If there is a specifier for a cyclic time stamp, get the closest
16978 date to DAYNR.
16979 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16980 The variable `date' is bound by the calendar when this is called."
16981 (cond
16982 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16983 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16984 daynr
16985 (+ daynr 1000)))
16986 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16987 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16988 (time-to-days (current-time))) (match-string 0 s)
16989 prefer show-all))
16990 (t (time-to-days
16991 (condition-case errdata
16992 (apply 'encode-time (org-parse-time-string s))
16993 (error (error "Bad timestamp `%s'%s\nError was: %s"
16994 s (if (not (and buffer pos))
16996 (format " at %d in buffer `%s'" pos buffer))
16997 (cdr errdata))))))))
16999 (defun org-days-to-iso-week (days)
17000 "Return the iso week number."
17001 (require 'cal-iso)
17002 (car (calendar-iso-from-absolute days)))
17004 (defun org-small-year-to-year (year)
17005 "Convert 2-digit years into 4-digit years.
17006 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17007 The year 2000 cannot be abbreviated. Any year larger than 99
17008 is returned unchanged."
17009 (if (< year 38)
17010 (setq year (+ 2000 year))
17011 (if (< year 100)
17012 (setq year (+ 1900 year))))
17013 year)
17015 (defun org-time-from-absolute (d)
17016 "Return the time corresponding to date D.
17017 D may be an absolute day number, or a calendar-type list (month day year)."
17018 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17019 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17021 (defun org-calendar-holiday ()
17022 "List of holidays, for Diary display in Org-mode."
17023 (require 'holidays)
17024 (let ((hl (funcall
17025 (if (fboundp 'calendar-check-holidays)
17026 'calendar-check-holidays 'check-calendar-holidays) date)))
17027 (if hl (mapconcat 'identity hl "; "))))
17029 (defun org-diary-sexp-entry (sexp entry date)
17030 "Process a SEXP diary ENTRY for DATE."
17031 (require 'diary-lib)
17032 (let ((result (if calendar-debug-sexp
17033 (let ((stack-trace-on-error t))
17034 (eval (car (read-from-string sexp))))
17035 (condition-case nil
17036 (eval (car (read-from-string sexp)))
17037 (error
17038 (beep)
17039 (message "Bad sexp at line %d in %s: %s"
17040 (org-current-line)
17041 (buffer-file-name) sexp)
17042 (sleep-for 2))))))
17043 (cond ((stringp result) (split-string result "; "))
17044 ((and (consp result)
17045 (not (consp (cdr result)))
17046 (stringp (cdr result))) (cdr result))
17047 ((and (consp result)
17048 (stringp (car result))) result)
17049 (result entry))))
17051 (defun org-diary-to-ical-string (frombuf)
17052 "Get iCalendar entries from diary entries in buffer FROMBUF.
17053 This uses the icalendar.el library."
17054 (let* ((tmpdir (if (featurep 'xemacs)
17055 (temp-directory)
17056 temporary-file-directory))
17057 (tmpfile (make-temp-name
17058 (expand-file-name "orgics" tmpdir)))
17059 buf rtn b e)
17060 (with-current-buffer frombuf
17061 (icalendar-export-region (point-min) (point-max) tmpfile)
17062 (setq buf (find-buffer-visiting tmpfile))
17063 (set-buffer buf)
17064 (goto-char (point-min))
17065 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17066 (setq b (match-beginning 0)))
17067 (goto-char (point-max))
17068 (if (re-search-backward "^END:VEVENT" nil t)
17069 (setq e (match-end 0)))
17070 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17071 (kill-buffer buf)
17072 (delete-file tmpfile)
17073 rtn))
17075 (defun org-closest-date (start current change prefer show-all)
17076 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17077 When PREFER is `past', return a date that is either CURRENT or past.
17078 When PREFER is `future', return a date that is either CURRENT or future.
17079 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17080 ;; Make the proper lists from the dates
17081 (catch 'exit
17082 (let ((a1 '(("h" . hour)
17083 ("d" . day)
17084 ("w" . week)
17085 ("m" . month)
17086 ("y" . year)))
17087 (shour (nth 2 (org-parse-time-string start)))
17088 dn dw sday cday n1 n2 n0
17089 d m y y1 y2 date1 date2 nmonths nm ny m2)
17091 (setq start (org-date-to-gregorian start)
17092 current (org-date-to-gregorian
17093 (if show-all
17094 current
17095 (time-to-days (current-time))))
17096 sday (calendar-absolute-from-gregorian start)
17097 cday (calendar-absolute-from-gregorian current))
17099 (if (<= cday sday) (throw 'exit sday))
17101 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17102 (setq dn (string-to-number (match-string 1 change))
17103 dw (cdr (assoc (match-string 2 change) a1)))
17104 (user-error "Invalid change specifier: %s" change))
17105 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17106 (cond
17107 ((eq dw 'hour)
17108 (let ((missing-hours
17109 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17110 dn)))
17111 (setq n1 (if (zerop missing-hours) cday
17112 (- cday (1+ (floor (/ missing-hours 24)))))
17113 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17114 ((eq dw 'day)
17115 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17116 n2 (+ n1 dn)))
17117 ((eq dw 'year)
17118 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17119 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17120 (setq date1 (list m d y1)
17121 n1 (calendar-absolute-from-gregorian date1)
17122 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17123 n2 (calendar-absolute-from-gregorian date2)))
17124 ((eq dw 'month)
17125 ;; approx number of month between the two dates
17126 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17127 ;; How often does dn fit in there?
17128 (setq d (nth 1 start) m (car start) y (nth 2 start)
17129 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17130 m (+ m nm)
17131 ny (floor (/ m 12))
17132 y (+ y ny)
17133 m (- m (* ny 12)))
17134 (while (> m 12) (setq m (- m 12) y (1+ y)))
17135 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17136 (setq m2 (+ m dn) y2 y)
17137 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17138 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17139 (while (<= n2 cday)
17140 (setq n1 n2 m m2 y y2)
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 ;; Make sure n1 is the earlier date
17145 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17146 (if show-all
17147 (cond
17148 ((eq prefer 'past) (if (= cday n2) n2 n1))
17149 ((eq prefer 'future) (if (= cday n1) n1 n2))
17150 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17151 (cond
17152 ((eq prefer 'past) (if (= cday n2) n2 n1))
17153 ((eq prefer 'future) (if (= cday n1) n1 n2))
17154 (t (if (= cday n1) n1 n2)))))))
17156 (defun org-date-to-gregorian (date)
17157 "Turn any specification of DATE into a Gregorian date for the calendar."
17158 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17159 ((and (listp date) (= (length date) 3)) date)
17160 ((stringp date)
17161 (setq date (org-parse-time-string date))
17162 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17163 ((listp date)
17164 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17166 (defun org-parse-time-string (s &optional nodefault)
17167 "Parse the standard Org-mode time string.
17168 This should be a lot faster than the normal `parse-time-string'.
17169 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17170 hour and minute fields will be nil if not given."
17171 (cond ((string-match org-ts-regexp0 s)
17172 (list 0
17173 (if (or (match-beginning 8) (not nodefault))
17174 (string-to-number (or (match-string 8 s) "0")))
17175 (if (or (match-beginning 7) (not nodefault))
17176 (string-to-number (or (match-string 7 s) "0")))
17177 (string-to-number (match-string 4 s))
17178 (string-to-number (match-string 3 s))
17179 (string-to-number (match-string 2 s))
17180 nil nil nil))
17181 ((string-match "^<[^>]+>$" s)
17182 (decode-time (seconds-to-time (org-matcher-time s))))
17183 (t (error "Not a standard Org-mode time string: %s" s))))
17185 (defun org-timestamp-up (&optional arg)
17186 "Increase the date item at the cursor by one.
17187 If the cursor is on the year, change the year. If it is on the month,
17188 the day or the time, change that.
17189 With prefix ARG, change by that many units."
17190 (interactive "p")
17191 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17193 (defun org-timestamp-down (&optional arg)
17194 "Decrease the date item at the cursor by one.
17195 If the cursor is on the year, change the year. If it is on the month,
17196 the day or the time, change that.
17197 With prefix ARG, change by that many units."
17198 (interactive "p")
17199 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17201 (defun org-timestamp-up-day (&optional arg)
17202 "Increase the date in the time stamp by one day.
17203 With prefix ARG, change that many days."
17204 (interactive "p")
17205 (if (and (not (org-at-timestamp-p t))
17206 (org-at-heading-p))
17207 (org-todo 'up)
17208 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17210 (defun org-timestamp-down-day (&optional arg)
17211 "Decrease the date in the time stamp by one day.
17212 With prefix ARG, change that many days."
17213 (interactive "p")
17214 (if (and (not (org-at-timestamp-p t))
17215 (org-at-heading-p))
17216 (org-todo 'down)
17217 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17219 (defun org-at-timestamp-p (&optional inactive-ok)
17220 "Determine if the cursor is in or at a timestamp."
17221 (interactive)
17222 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17223 (pos (point))
17224 (ans (or (looking-at tsr)
17225 (save-excursion
17226 (skip-chars-backward "^[<\n\r\t")
17227 (if (> (point) (point-min)) (backward-char 1))
17228 (and (looking-at tsr)
17229 (> (- (match-end 0) pos) -1))))))
17230 (and ans
17231 (boundp 'org-ts-what)
17232 (setq org-ts-what
17233 (cond
17234 ((= pos (match-beginning 0)) 'bracket)
17235 ;; Point is considered to be "on the bracket" whether
17236 ;; it's really on it or right after it.
17237 ((= pos (1- (match-end 0))) 'bracket)
17238 ((= pos (match-end 0)) 'after)
17239 ((org-pos-in-match-range pos 2) 'year)
17240 ((org-pos-in-match-range pos 3) 'month)
17241 ((org-pos-in-match-range pos 7) 'hour)
17242 ((org-pos-in-match-range pos 8) 'minute)
17243 ((or (org-pos-in-match-range pos 4)
17244 (org-pos-in-match-range pos 5)) 'day)
17245 ((and (> pos (or (match-end 8) (match-end 5)))
17246 (< pos (match-end 0)))
17247 (- pos (or (match-end 8) (match-end 5))))
17248 (t 'day))))
17249 ans))
17251 (defun org-toggle-timestamp-type ()
17252 "Toggle the type (<active> or [inactive]) of a time stamp."
17253 (interactive)
17254 (when (org-at-timestamp-p t)
17255 (let ((beg (match-beginning 0)) (end (match-end 0))
17256 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17257 (save-excursion
17258 (goto-char beg)
17259 (while (re-search-forward "[][<>]" end t)
17260 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17261 t t)))
17262 (message "Timestamp is now %sactive"
17263 (if (equal (char-after beg) ?<) "" "in")))))
17265 (defun org-at-clock-log-p nil
17266 "Is the cursor on the clock log line?"
17267 (save-excursion
17268 (move-beginning-of-line 1)
17269 (looking-at "^[ \t]*CLOCK:")))
17271 (defvar org-clock-history) ; defined in org-clock.el
17272 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17273 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17274 "Change the date in the time stamp at point.
17275 The date will be changed by N times WHAT. WHAT can be `day', `month',
17276 `year', `minute', `second'. If WHAT is not given, the cursor position
17277 in the timestamp determines what will be changed.
17278 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17279 (let ((origin (point)) origin-cat
17280 with-hm inactive
17281 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17282 org-ts-what
17283 extra rem
17284 ts time time0 fixnext clrgx)
17285 (if (not (org-at-timestamp-p t))
17286 (user-error "Not at a timestamp"))
17287 (if (and (not what) (eq org-ts-what 'bracket))
17288 (org-toggle-timestamp-type)
17289 ;; Point isn't on brackets. Remember the part of the time-stamp
17290 ;; the point was in. Indeed, size of time-stamps may change,
17291 ;; but point must be kept in the same category nonetheless.
17292 (setq origin-cat org-ts-what)
17293 (if (and (not what) (not (eq org-ts-what 'day))
17294 org-display-custom-times
17295 (get-text-property (point) 'display)
17296 (not (get-text-property (1- (point)) 'display)))
17297 (setq org-ts-what 'day))
17298 (setq org-ts-what (or what org-ts-what)
17299 inactive (= (char-after (match-beginning 0)) ?\[)
17300 ts (match-string 0))
17301 (replace-match "")
17302 (when (string-match
17303 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17305 (setq extra (match-string 1 ts))
17306 (if suppress-tmp-delay
17307 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17308 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17309 (setq with-hm t))
17310 (setq time0 (org-parse-time-string ts))
17311 (when (and updown
17312 (eq org-ts-what 'minute)
17313 (not current-prefix-arg))
17314 ;; This looks like s-up and s-down. Change by one rounding step.
17315 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17316 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17317 (setcar (cdr time0) (+ (nth 1 time0)
17318 (if (> n 0) (- rem) (- dm rem))))))
17319 (setq time
17320 (encode-time (or (car time0) 0)
17321 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17322 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17323 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17324 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17325 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17326 (nthcdr 6 time0)))
17327 (when (and (member org-ts-what '(hour minute))
17328 extra
17329 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17330 (setq extra (org-modify-ts-extra
17331 extra
17332 (if (eq org-ts-what 'hour) 2 5)
17333 n dm)))
17334 (when (integerp org-ts-what)
17335 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17336 (if (eq what 'calendar)
17337 (let ((cal-date (org-get-date-from-calendar)))
17338 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17339 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17340 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17341 (setcar time0 (or (car time0) 0))
17342 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17343 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17344 (setq time (apply 'encode-time time0))))
17345 ;; Insert the new time-stamp, and ensure point stays in the same
17346 ;; category as before (i.e. not after the last position in that
17347 ;; category).
17348 (let ((pos (point)))
17349 ;; Stay before inserted string. `save-excursion' is of no use.
17350 (setq org-last-changed-timestamp
17351 (org-insert-time-stamp time with-hm inactive nil nil extra))
17352 (goto-char pos))
17353 (save-match-data
17354 (looking-at org-ts-regexp3)
17355 (goto-char (cond
17356 ;; `day' category ends before `hour' if any, or at
17357 ;; the end of the day name.
17358 ((eq origin-cat 'day)
17359 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17360 ((eq origin-cat 'hour) (min (match-end 7) origin))
17361 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17362 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17363 ;; `year' and `month' have both fixed size: point
17364 ;; couldn't have moved into another part.
17365 (t origin))))
17366 ;; Update clock if on a CLOCK line.
17367 (org-clock-update-time-maybe)
17368 ;; Maybe adjust the closest clock in `org-clock-history'
17369 (when org-clock-adjust-closest
17370 (if (not (and (org-at-clock-log-p)
17371 (< 1 (length (delq nil (mapcar 'marker-position
17372 org-clock-history))))))
17373 (message "No clock to adjust")
17374 (cond ((save-excursion ; fix previous clock?
17375 (re-search-backward org-ts-regexp0 nil t)
17376 (org-looking-back (concat org-clock-string " \\[")))
17377 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17378 ((save-excursion ; fix next clock?
17379 (re-search-backward org-ts-regexp0 nil t)
17380 (looking-at (concat org-ts-regexp0 "\\] =>")))
17381 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17382 (save-window-excursion
17383 ;; Find closest clock to point, adjust the previous/next one in history
17384 (let* ((p (save-excursion (org-back-to-heading t)))
17385 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17386 (clfixnth
17387 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17388 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17389 (if (not clfixpos)
17390 (message "No clock to adjust")
17391 (save-excursion
17392 (org-goto-marker-or-bmk clfixpos)
17393 (org-show-subtree)
17394 (when (re-search-forward clrgx nil t)
17395 (goto-char (match-beginning 1))
17396 (let (org-clock-adjust-closest)
17397 (org-timestamp-change n org-ts-what updown))
17398 (message "Clock adjusted in %s for heading: %s"
17399 (file-name-nondirectory (buffer-file-name))
17400 (org-get-heading t t)))))))))
17401 ;; Try to recenter the calendar window, if any.
17402 (if (and org-calendar-follow-timestamp-change
17403 (get-buffer-window "*Calendar*" t)
17404 (memq org-ts-what '(day month year)))
17405 (org-recenter-calendar (time-to-days time))))))
17407 (defun org-modify-ts-extra (s pos n dm)
17408 "Change the different parts of the lead-time and repeat fields in timestamp."
17409 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17410 ng h m new rem)
17411 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17412 (cond
17413 ((or (org-pos-in-match-range pos 2)
17414 (org-pos-in-match-range pos 3))
17415 (setq m (string-to-number (match-string 3 s))
17416 h (string-to-number (match-string 2 s)))
17417 (if (org-pos-in-match-range pos 2)
17418 (setq h (+ h n))
17419 (setq n (* dm (org-no-warnings (signum n))))
17420 (when (not (= 0 (setq rem (% m dm))))
17421 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17422 (setq m (+ m n)))
17423 (if (< m 0) (setq m (+ m 60) h (1- h)))
17424 (if (> m 59) (setq m (- m 60) h (1+ h)))
17425 (setq h (min 24 (max 0 h)))
17426 (setq ng 1 new (format "-%02d:%02d" h m)))
17427 ((org-pos-in-match-range pos 6)
17428 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17429 ((org-pos-in-match-range pos 5)
17430 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17432 ((org-pos-in-match-range pos 9)
17433 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17434 ((org-pos-in-match-range pos 8)
17435 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17437 (when ng
17438 (setq s (concat
17439 (substring s 0 (match-beginning ng))
17441 (substring s (match-end ng))))))
17444 (defun org-recenter-calendar (date)
17445 "If the calendar is visible, recenter it to DATE."
17446 (let ((cwin (get-buffer-window "*Calendar*" t)))
17447 (when cwin
17448 (let ((calendar-move-hook nil))
17449 (with-selected-window cwin
17450 (calendar-goto-date (if (listp date) date
17451 (calendar-gregorian-from-absolute date))))))))
17453 (defun org-goto-calendar (&optional arg)
17454 "Go to the Emacs calendar at the current date.
17455 If there is a time stamp in the current line, go to that date.
17456 A prefix ARG can be used to force the current date."
17457 (interactive "P")
17458 (let ((tsr org-ts-regexp) diff
17459 (calendar-move-hook nil)
17460 (calendar-view-holidays-initially-flag nil)
17461 (calendar-view-diary-initially-flag nil))
17462 (if (or (org-at-timestamp-p)
17463 (save-excursion
17464 (beginning-of-line 1)
17465 (looking-at (concat ".*" tsr))))
17466 (let ((d1 (time-to-days (current-time)))
17467 (d2 (time-to-days
17468 (org-time-string-to-time (match-string 1)))))
17469 (setq diff (- d2 d1))))
17470 (calendar)
17471 (calendar-goto-today)
17472 (if (and diff (not arg)) (calendar-forward-day diff))))
17474 (defun org-get-date-from-calendar ()
17475 "Return a list (month day year) of date at point in calendar."
17476 (with-current-buffer "*Calendar*"
17477 (save-match-data
17478 (calendar-cursor-to-date))))
17480 (defun org-date-from-calendar ()
17481 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17482 If there is already a time stamp at the cursor position, update it."
17483 (interactive)
17484 (if (org-at-timestamp-p t)
17485 (org-timestamp-change 0 'calendar)
17486 (let ((cal-date (org-get-date-from-calendar)))
17487 (org-insert-time-stamp
17488 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17490 (defcustom org-effort-durations
17491 `(("h" . 60)
17492 ("d" . ,(* 60 8))
17493 ("w" . ,(* 60 8 5))
17494 ("m" . ,(* 60 8 5 4))
17495 ("y" . ,(* 60 8 5 40)))
17496 "Conversion factor to minutes for an effort modifier.
17498 Each entry has the form (MODIFIER . MINUTES).
17500 In an effort string, a number followed by MODIFIER is multiplied
17501 by the specified number of MINUTES to obtain an effort in
17502 minutes.
17504 For example, if the value of this variable is ((\"hours\" . 60)), then an
17505 effort string \"2hours\" is equivalent to 120 minutes."
17506 :group 'org-agenda
17507 :version "24.1"
17508 :type '(alist :key-type (string :tag "Modifier")
17509 :value-type (number :tag "Minutes")))
17511 (defun org-minutes-to-clocksum-string (m)
17512 "Format number of minutes as a clocksum string.
17513 The format is determined by `org-time-clocksum-format',
17514 `org-time-clocksum-use-fractional' and
17515 `org-time-clocksum-fractional-format' and
17516 `org-time-clocksum-use-effort-durations'."
17517 (let ((clocksum "")
17518 (m (round m)) ; Don't allow fractions of minutes
17519 h d w mo y fmt n)
17520 (setq h (if org-time-clocksum-use-effort-durations
17521 (cdr (assoc "h" org-effort-durations)) 60)
17522 d (if org-time-clocksum-use-effort-durations
17523 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17524 w (if org-time-clocksum-use-effort-durations
17525 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17526 mo (if org-time-clocksum-use-effort-durations
17527 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17528 y (if org-time-clocksum-use-effort-durations
17529 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17530 ;; fractional format
17531 (if org-time-clocksum-use-fractional
17532 (cond
17533 ;; single format string
17534 ((stringp org-time-clocksum-fractional-format)
17535 (format org-time-clocksum-fractional-format (/ m (float h))))
17536 ;; choice of fractional formats for different time units
17537 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17538 (> (/ (truncate m) (* y d h)) 0))
17539 (format fmt (/ m (* y d (float h)))))
17540 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17541 (> (/ (truncate m) (* mo d h)) 0))
17542 (format fmt (/ m (* mo d (float h)))))
17543 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17544 (> (/ (truncate m) (* w d h)) 0))
17545 (format fmt (/ m (* w d (float h)))))
17546 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17547 (> (/ (truncate m) (* d h)) 0))
17548 (format fmt (/ m (* d (float h)))))
17549 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17550 (> (/ (truncate m) h) 0))
17551 (format fmt (/ m (float h))))
17552 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17553 (format fmt m))
17554 ;; fall back to smallest time unit with a format
17555 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17556 (format fmt (/ m (float h))))
17557 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17558 (format fmt (/ m (* d (float h)))))
17559 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17560 (format fmt (/ m (* w d (float h)))))
17561 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17562 (format fmt (/ m (* mo d (float h)))))
17563 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17564 (format fmt (/ m (* y d (float h))))))
17565 ;; standard (non-fractional) format, with single format string
17566 (if (stringp org-time-clocksum-format)
17567 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17568 ;; separate formats components
17569 (and (setq fmt (plist-get org-time-clocksum-format :years))
17570 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17571 (plist-get org-time-clocksum-format :require-years))
17572 (setq clocksum (concat clocksum (format fmt n))
17573 m (- m (* n y d h))))
17574 (and (setq fmt (plist-get org-time-clocksum-format :months))
17575 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17576 (plist-get org-time-clocksum-format :require-months))
17577 (setq clocksum (concat clocksum (format fmt n))
17578 m (- m (* n mo d h))))
17579 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17580 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17581 (plist-get org-time-clocksum-format :require-weeks))
17582 (setq clocksum (concat clocksum (format fmt n))
17583 m (- m (* n w d h))))
17584 (and (setq fmt (plist-get org-time-clocksum-format :days))
17585 (or (> (setq n (/ (truncate m) (* d h))) 0)
17586 (plist-get org-time-clocksum-format :require-days))
17587 (setq clocksum (concat clocksum (format fmt n))
17588 m (- m (* n d h))))
17589 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17590 (or (> (setq n (/ (truncate m) h)) 0)
17591 (plist-get org-time-clocksum-format :require-hours))
17592 (setq clocksum (concat clocksum (format fmt n))
17593 m (- m (* n h))))
17594 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17595 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17596 (setq clocksum (concat clocksum (format fmt m))))
17597 ;; return formatted time duration
17598 clocksum))))
17600 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17601 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17602 "Org mode version 8.0")
17604 (defun org-hours-to-clocksum-string (n)
17605 (org-minutes-to-clocksum-string (* n 60)))
17607 (defun org-hh:mm-string-to-minutes (s)
17608 "Convert a string H:MM to a number of minutes.
17609 If the string is just a number, interpret it as minutes.
17610 In fact, the first hh:mm or number in the string will be taken,
17611 there can be extra stuff in the string.
17612 If no number is found, the return value is 0."
17613 (cond
17614 ((integerp s) s)
17615 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17616 (+ (* (string-to-number (match-string 1 s)) 60)
17617 (string-to-number (match-string 2 s))))
17618 ((string-match "\\([0-9]+\\)" s)
17619 (string-to-number (match-string 1 s)))
17620 (t 0)))
17622 (defcustom org-image-actual-width t
17623 "Should we use the actual width of images when inlining them?
17625 When set to `t', always use the image width.
17627 When set to a number, use imagemagick (when available) to set
17628 the image's width to this value.
17630 When set to a number in a list, try to get the width from any
17631 #+ATTR.* keyword if it matches a width specification like
17633 #+ATTR_HTML: :width 300px
17635 and fall back on that number if none is found.
17637 When set to nil, try to get the width from an #+ATTR.* keyword
17638 and fall back on the original width if none is found.
17640 This requires Emacs >= 24.1, build with imagemagick support."
17641 :group 'org-appearance
17642 :version "24.4"
17643 :package-version '(Org . "8.0")
17644 :type '(choice
17645 (const :tag "Use the image width" t)
17646 (integer :tag "Use a number of pixels")
17647 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17648 (const :tag "Use #+ATTR* or don't resize" nil)))
17650 (defcustom org-agenda-inhibit-startup nil
17651 "Inhibit startup when preparing agenda buffers.
17652 When this variable is `t' (the default), the initialization of
17653 the Org agenda buffers is inhibited: e.g. the visibility state
17654 is not set, the tables are not re-aligned, etc."
17655 :type 'boolean
17656 :version "24.3"
17657 :group 'org-agenda)
17659 (defun org-duration-string-to-minutes (s &optional output-to-string)
17660 "Convert a duration string S to minutes.
17662 A bare number is interpreted as minutes, modifiers can be set by
17663 customizing `org-effort-durations' (which see).
17665 Entries containing a colon are interpreted as H:MM by
17666 `org-hh:mm-string-to-minutes'."
17667 (let ((result 0)
17668 (re (concat "\\([0-9.]+\\) *\\("
17669 (regexp-opt (mapcar 'car org-effort-durations))
17670 "\\)")))
17671 (while (string-match re s)
17672 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17673 (string-to-number (match-string 1 s))))
17674 (setq s (replace-match "" nil t s)))
17675 (setq result (floor result))
17676 (incf result (org-hh:mm-string-to-minutes s))
17677 (if output-to-string (number-to-string result) result)))
17679 ;;;; Files
17681 (defun org-save-all-org-buffers ()
17682 "Save all Org-mode buffers without user confirmation."
17683 (interactive)
17684 (message "Saving all Org-mode buffers...")
17685 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17686 (when (featurep 'org-id) (org-id-locations-save))
17687 (message "Saving all Org-mode buffers... done"))
17689 (defun org-revert-all-org-buffers ()
17690 "Revert all Org-mode buffers.
17691 Prompt for confirmation when there are unsaved changes.
17692 Be sure you know what you are doing before letting this function
17693 overwrite your changes.
17695 This function is useful in a setup where one tracks org files
17696 with a version control system, to revert on one machine after pulling
17697 changes from another. I believe the procedure must be like this:
17699 1. M-x org-save-all-org-buffers
17700 2. Pull changes from the other machine, resolve conflicts
17701 3. M-x org-revert-all-org-buffers"
17702 (interactive)
17703 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17704 (user-error "Abort"))
17705 (save-excursion
17706 (save-window-excursion
17707 (mapc
17708 (lambda (b)
17709 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17710 (with-current-buffer b buffer-file-name))
17711 (org-pop-to-buffer-same-window b)
17712 (revert-buffer t 'no-confirm)))
17713 (buffer-list))
17714 (when (and (featurep 'org-id) org-id-track-globally)
17715 (org-id-locations-load)))))
17717 ;;;; Agenda files
17719 ;;;###autoload
17720 (defun org-switchb (&optional arg)
17721 "Switch between Org buffers.
17722 With one prefix argument, restrict available buffers to files.
17723 With two prefix arguments, restrict available buffers to agenda files.
17725 Defaults to `iswitchb' for buffer name completion.
17726 Set `org-completion-use-ido' to make it use ido instead."
17727 (interactive "P")
17728 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17729 ((equal arg '(16)) (org-buffer-list 'agenda))
17730 (t (org-buffer-list))))
17731 (org-completion-use-iswitchb org-completion-use-iswitchb)
17732 (org-completion-use-ido org-completion-use-ido))
17733 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17734 (setq org-completion-use-iswitchb t))
17735 (org-pop-to-buffer-same-window
17736 (org-icompleting-read "Org buffer: "
17737 (mapcar 'list (mapcar 'buffer-name blist))
17738 nil t))))
17740 ;;; Define some older names previously used for this functionality
17741 ;;;###autoload
17742 (defalias 'org-ido-switchb 'org-switchb)
17743 ;;;###autoload
17744 (defalias 'org-iswitchb 'org-switchb)
17746 (defun org-buffer-list (&optional predicate exclude-tmp)
17747 "Return a list of Org buffers.
17748 PREDICATE can be `export', `files' or `agenda'.
17750 export restrict the list to Export buffers.
17751 files restrict the list to buffers visiting Org files.
17752 agenda restrict the list to buffers visiting agenda files.
17754 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17755 (let* ((bfn nil)
17756 (agenda-files (and (eq predicate 'agenda)
17757 (mapcar 'file-truename (org-agenda-files t))))
17758 (filter
17759 (cond
17760 ((eq predicate 'files)
17761 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17762 ((eq predicate 'export)
17763 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17764 ((eq predicate 'agenda)
17765 (lambda (b)
17766 (with-current-buffer b
17767 (and (derived-mode-p 'org-mode)
17768 (setq bfn (buffer-file-name b))
17769 (member (file-truename bfn) agenda-files)))))
17770 (t (lambda (b) (with-current-buffer b
17771 (or (derived-mode-p 'org-mode)
17772 (string-match "\*Org .*Export"
17773 (buffer-name b)))))))))
17774 (delq nil
17775 (mapcar
17776 (lambda(b)
17777 (if (and (funcall filter b)
17778 (or (not exclude-tmp)
17779 (not (string-match "tmp" (buffer-name b)))))
17781 nil))
17782 (buffer-list)))))
17784 (defun org-agenda-files (&optional unrestricted archives)
17785 "Get the list of agenda files.
17786 Optional UNRESTRICTED means return the full list even if a restriction
17787 is currently in place.
17788 When ARCHIVES is t, include all archive files that are really being
17789 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17790 `org-agenda-archives-mode' is t."
17791 (let ((files
17792 (cond
17793 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17794 ((stringp org-agenda-files) (org-read-agenda-file-list))
17795 ((listp org-agenda-files) org-agenda-files)
17796 (t (error "Invalid value of `org-agenda-files'")))))
17797 (setq files (apply 'append
17798 (mapcar (lambda (f)
17799 (if (file-directory-p f)
17800 (directory-files
17801 f t org-agenda-file-regexp)
17802 (list f)))
17803 files)))
17804 (when org-agenda-skip-unavailable-files
17805 (setq files (delq nil
17806 (mapcar (function
17807 (lambda (file)
17808 (and (file-readable-p file) file)))
17809 files))))
17810 (when (or (eq archives t)
17811 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17812 (setq files (org-add-archive-files files)))
17813 files))
17815 (defun org-agenda-file-p (&optional file)
17816 "Return non-nil, if FILE is an agenda file.
17817 If FILE is omitted, use the file associated with the current
17818 buffer."
17819 (member (or file (buffer-file-name))
17820 (org-agenda-files t)))
17822 (defun org-edit-agenda-file-list ()
17823 "Edit the list of agenda files.
17824 Depending on setup, this either uses customize to edit the variable
17825 `org-agenda-files', or it visits the file that is holding the list. In the
17826 latter case, the buffer is set up in a way that saving it automatically kills
17827 the buffer and restores the previous window configuration."
17828 (interactive)
17829 (if (stringp org-agenda-files)
17830 (let ((cw (current-window-configuration)))
17831 (find-file org-agenda-files)
17832 (org-set-local 'org-window-configuration cw)
17833 (org-add-hook 'after-save-hook
17834 (lambda ()
17835 (set-window-configuration
17836 (prog1 org-window-configuration
17837 (kill-buffer (current-buffer))))
17838 (org-install-agenda-files-menu)
17839 (message "New agenda file list installed"))
17840 nil 'local)
17841 (message "%s" (substitute-command-keys
17842 "Edit list and finish with \\[save-buffer]")))
17843 (customize-variable 'org-agenda-files)))
17845 (defun org-store-new-agenda-file-list (list)
17846 "Set new value for the agenda file list and save it correctly."
17847 (if (stringp org-agenda-files)
17848 (let ((fe (org-read-agenda-file-list t)) b u)
17849 (while (setq b (find-buffer-visiting org-agenda-files))
17850 (kill-buffer b))
17851 (with-temp-file org-agenda-files
17852 (insert
17853 (mapconcat
17854 (lambda (f) ;; Keep un-expanded entries.
17855 (if (setq u (assoc f fe))
17856 (cdr u)
17858 list "\n")
17859 "\n")))
17860 (let ((org-mode-hook nil) (org-inhibit-startup t)
17861 (org-insert-mode-line-in-empty-file nil))
17862 (setq org-agenda-files list)
17863 (customize-save-variable 'org-agenda-files org-agenda-files))))
17865 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17866 "Read the list of agenda files from a file.
17867 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17868 filenames, used by `org-store-new-agenda-file-list' to write back
17869 un-expanded file names."
17870 (when (file-directory-p org-agenda-files)
17871 (error "`org-agenda-files' cannot be a single directory"))
17872 (when (stringp org-agenda-files)
17873 (with-temp-buffer
17874 (insert-file-contents org-agenda-files)
17875 (mapcar
17876 (lambda (f)
17877 (let ((e (expand-file-name (substitute-in-file-name f)
17878 org-directory)))
17879 (if pair-with-expansion
17880 (cons e f)
17881 e)))
17882 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17884 ;;;###autoload
17885 (defun org-cycle-agenda-files ()
17886 "Cycle through the files in `org-agenda-files'.
17887 If the current buffer visits an agenda file, find the next one in the list.
17888 If the current buffer does not, find the first agenda file."
17889 (interactive)
17890 (let* ((fs (org-agenda-files t))
17891 (files (append fs (list (car fs))))
17892 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17893 file)
17894 (unless files (user-error "No agenda files"))
17895 (catch 'exit
17896 (while (setq file (pop files))
17897 (if (equal (file-truename file) tcf)
17898 (when (car files)
17899 (find-file (car files))
17900 (throw 'exit t))))
17901 (find-file (car fs)))
17902 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17904 (defun org-agenda-file-to-front (&optional to-end)
17905 "Move/add the current file to the top of the agenda file list.
17906 If the file is not present in the list, it is added to the front. If it is
17907 present, it is moved there. With optional argument TO-END, add/move to the
17908 end of the list."
17909 (interactive "P")
17910 (let ((org-agenda-skip-unavailable-files nil)
17911 (file-alist (mapcar (lambda (x)
17912 (cons (file-truename x) x))
17913 (org-agenda-files t)))
17914 (ctf (file-truename
17915 (or buffer-file-name
17916 (user-error "Please save the current buffer to a file"))))
17917 x had)
17918 (setq x (assoc ctf file-alist) had x)
17920 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17921 (if to-end
17922 (setq file-alist (append (delq x file-alist) (list x)))
17923 (setq file-alist (cons x (delq x file-alist))))
17924 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17925 (org-install-agenda-files-menu)
17926 (message "File %s to %s of agenda file list"
17927 (if had "moved" "added") (if to-end "end" "front"))))
17929 (defun org-remove-file (&optional file)
17930 "Remove current file from the list of files in variable `org-agenda-files'.
17931 These are the files which are being checked for agenda entries.
17932 Optional argument FILE means use this file instead of the current."
17933 (interactive)
17934 (let* ((org-agenda-skip-unavailable-files nil)
17935 (file (or file buffer-file-name
17936 (user-error "Current buffer does not visit a file")))
17937 (true-file (file-truename file))
17938 (afile (abbreviate-file-name file))
17939 (files (delq nil (mapcar
17940 (lambda (x)
17941 (if (equal true-file
17942 (file-truename x))
17943 nil x))
17944 (org-agenda-files t)))))
17945 (if (not (= (length files) (length (org-agenda-files t))))
17946 (progn
17947 (org-store-new-agenda-file-list files)
17948 (org-install-agenda-files-menu)
17949 (message "Removed file: %s" afile))
17950 (message "File was not in list: %s (not removed)" afile))))
17952 (defun org-file-menu-entry (file)
17953 (vector file (list 'find-file file) t))
17955 (defun org-check-agenda-file (file)
17956 "Make sure FILE exists. If not, ask user what to do."
17957 (when (not (file-exists-p file))
17958 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17959 (abbreviate-file-name file))
17960 (let ((r (downcase (read-char-exclusive))))
17961 (cond
17962 ((equal r ?r)
17963 (org-remove-file file)
17964 (throw 'nextfile t))
17965 (t (error "Abort"))))))
17967 (defun org-get-agenda-file-buffer (file)
17968 "Get a buffer visiting FILE. If the buffer needs to be created, add
17969 it to the list of buffers which might be released later."
17970 (let ((buf (org-find-base-buffer-visiting file)))
17971 (if buf
17972 buf ; just return it
17973 ;; Make a new buffer and remember it
17974 (setq buf (find-file-noselect file))
17975 (if buf (push buf org-agenda-new-buffers))
17976 buf)))
17978 (defun org-release-buffers (blist)
17979 "Release all buffers in list, asking the user for confirmation when needed.
17980 When a buffer is unmodified, it is just killed. When modified, it is saved
17981 \(if the user agrees) and then killed."
17982 (let (buf file)
17983 (while (setq buf (pop blist))
17984 (setq file (buffer-file-name buf))
17985 (when (and (buffer-modified-p buf)
17986 file
17987 (y-or-n-p (format "Save file %s? " file)))
17988 (with-current-buffer buf (save-buffer)))
17989 (kill-buffer buf))))
17991 (defun org-agenda-prepare-buffers (files)
17992 "Create buffers for all agenda files, protect archived trees and comments."
17993 (interactive)
17994 (let ((pa '(:org-archived t))
17995 (pc '(:org-comment t))
17996 (pall '(:org-archived t :org-comment t))
17997 (inhibit-read-only t)
17998 (org-inhibit-startup org-agenda-inhibit-startup)
17999 (rea (concat ":" org-archive-tag ":"))
18000 file re)
18001 (setq org-tag-alist-for-agenda nil
18002 org-tag-groups-alist-for-agenda nil)
18003 (save-excursion
18004 (save-restriction
18005 (while (setq file (pop files))
18006 (catch 'nextfile
18007 (if (bufferp file)
18008 (set-buffer file)
18009 (org-check-agenda-file file)
18010 (set-buffer (org-get-agenda-file-buffer file)))
18011 (widen)
18012 (org-set-regexps-and-options-for-tags)
18013 (goto-char (point-min))
18014 (let ((case-fold-search t))
18015 (when (search-forward "#+setupfile" nil t)
18016 ;; Don't set all regexps and options systematically as
18017 ;; this is only run for setting agenda tags from setup
18018 ;; file
18019 (org-set-regexps-and-options)))
18020 (org-refresh-category-properties)
18021 (org-refresh-properties org-effort-property 'org-effort)
18022 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18023 (setq org-todo-keywords-for-agenda
18024 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18025 (setq org-done-keywords-for-agenda
18026 (append org-done-keywords-for-agenda org-done-keywords))
18027 (setq org-todo-keyword-alist-for-agenda
18028 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18029 (setq org-drawers-for-agenda
18030 (append org-drawers-for-agenda org-drawers))
18031 (setq org-tag-alist-for-agenda
18032 (org-uniquify
18033 (append org-tag-alist-for-agenda
18034 org-tag-alist
18035 org-tag-persistent-alist)))
18036 (if org-group-tags
18037 (setq org-tag-groups-alist-for-agenda
18038 (org-uniquify-alist
18039 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18040 (org-with-silent-modifications
18041 (save-excursion
18042 (remove-text-properties (point-min) (point-max) pall)
18043 (when org-agenda-skip-archived-trees
18044 (goto-char (point-min))
18045 (while (re-search-forward rea nil t)
18046 (if (org-at-heading-p t)
18047 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18048 (goto-char (point-min))
18049 (setq re (format org-heading-keyword-regexp-format
18050 org-comment-string))
18051 (while (re-search-forward re nil t)
18052 (add-text-properties
18053 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18054 (setq org-todo-keywords-for-agenda
18055 (org-uniquify org-todo-keywords-for-agenda))
18056 (setq org-todo-keyword-alist-for-agenda
18057 (org-uniquify org-todo-keyword-alist-for-agenda))))
18060 ;;;; CDLaTeX minor mode
18062 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18063 "Keymap for the minor `org-cdlatex-mode'.")
18065 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18066 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18067 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18068 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18069 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18071 (defvar org-cdlatex-texmathp-advice-is-done nil
18072 "Flag remembering if we have applied the advice to texmathp already.")
18074 (define-minor-mode org-cdlatex-mode
18075 "Toggle the minor `org-cdlatex-mode'.
18076 This mode supports entering LaTeX environment and math in LaTeX fragments
18077 in Org-mode.
18078 \\{org-cdlatex-mode-map}"
18079 nil " OCDL" nil
18080 (when org-cdlatex-mode
18081 (require 'cdlatex)
18082 (run-hooks 'cdlatex-mode-hook)
18083 (cdlatex-compute-tables))
18084 (unless org-cdlatex-texmathp-advice-is-done
18085 (setq org-cdlatex-texmathp-advice-is-done t)
18086 (defadvice texmathp (around org-math-always-on activate)
18087 "Always return t in org-mode buffers.
18088 This is because we want to insert math symbols without dollars even outside
18089 the LaTeX math segments. If Orgmode thinks that point is actually inside
18090 an embedded LaTeX fragment, let texmathp do its job.
18091 \\[org-cdlatex-mode-map]"
18092 (interactive)
18093 (let (p)
18094 (cond
18095 ((not (derived-mode-p 'org-mode)) ad-do-it)
18096 ((eq this-command 'cdlatex-math-symbol)
18097 (setq ad-return-value t
18098 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18100 (let ((p (org-inside-LaTeX-fragment-p)))
18101 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18102 (setq ad-return-value t
18103 texmathp-why '("Org-mode embedded math" . 0))
18104 (if p ad-do-it)))))))))
18106 (defun turn-on-org-cdlatex ()
18107 "Unconditionally turn on `org-cdlatex-mode'."
18108 (org-cdlatex-mode 1))
18110 (defun org-try-cdlatex-tab ()
18111 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18112 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18113 - inside a LaTeX fragment, or
18114 - after the first word in a line, where an abbreviation expansion could
18115 insert a LaTeX environment."
18116 (when org-cdlatex-mode
18117 (cond
18118 ;; Before any word on the line: No expansion possible.
18119 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18120 ;; Just after first word on the line: Expand it. Make sure it
18121 ;; cannot happen on headlines, though.
18122 ((save-excursion
18123 (skip-chars-backward "a-zA-Z0-9*")
18124 (skip-chars-backward " \t")
18125 (and (bolp) (not (org-at-heading-p))))
18126 (cdlatex-tab) t)
18127 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18129 (defun org-cdlatex-underscore-caret (&optional arg)
18130 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18131 Revert to the normal definition outside of these fragments."
18132 (interactive "P")
18133 (if (org-inside-LaTeX-fragment-p)
18134 (call-interactively 'cdlatex-sub-superscript)
18135 (let (org-cdlatex-mode)
18136 (call-interactively (key-binding (vector last-input-event))))))
18138 (defun org-cdlatex-math-modify (&optional arg)
18139 "Execute `cdlatex-math-modify' in LaTeX fragments.
18140 Revert to the normal definition outside of these fragments."
18141 (interactive "P")
18142 (if (org-inside-LaTeX-fragment-p)
18143 (call-interactively 'cdlatex-math-modify)
18144 (let (org-cdlatex-mode)
18145 (call-interactively (key-binding (vector last-input-event))))))
18149 ;;;; LaTeX fragments
18151 (defvar org-latex-regexps
18152 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18153 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18154 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18155 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18156 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18157 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18158 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18159 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18160 "Regular expressions for matching embedded LaTeX.")
18162 (defun org-inside-LaTeX-fragment-p ()
18163 "Test if point is inside a LaTeX fragment.
18164 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18165 sequence appearing also before point.
18166 Even though the matchers for math are configurable, this function assumes
18167 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18168 delimiters are skipped when they have been removed by customization.
18169 The return value is nil, or a cons cell with the delimiter and the
18170 position of this delimiter.
18172 This function does a reasonably good job, but can locally be fooled by
18173 for example currency specifications. For example it will assume being in
18174 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18175 fragments that are properly closed, but during editing, we have to live
18176 with the uncertainty caused by missing closing delimiters. This function
18177 looks only before point, not after."
18178 (catch 'exit
18179 (let ((pos (point))
18180 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18181 (lim (progn
18182 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18183 (point)))
18184 dd-on str (start 0) m re)
18185 (goto-char pos)
18186 (when dodollar
18187 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18188 re (nth 1 (assoc "$" org-latex-regexps)))
18189 (while (string-match re str start)
18190 (cond
18191 ((= (match-end 0) (length str))
18192 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18193 ((= (match-end 0) (- (length str) 5))
18194 (throw 'exit nil))
18195 (t (setq start (match-end 0))))))
18196 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18197 (goto-char pos)
18198 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18199 (and (match-beginning 2) (throw 'exit nil))
18200 ;; count $$
18201 (while (re-search-backward "\\$\\$" lim t)
18202 (setq dd-on (not dd-on)))
18203 (goto-char pos)
18204 (if dd-on (cons "$$" m))))))
18206 (defun org-inside-latex-macro-p ()
18207 "Is point inside a LaTeX macro or its arguments?"
18208 (save-match-data
18209 (org-in-regexp
18210 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18212 (defvar org-latex-fragment-image-overlays nil
18213 "List of overlays carrying the images of latex fragments.")
18214 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18216 (defun org-remove-latex-fragment-image-overlays ()
18217 "Remove all overlays with LaTeX fragment images in current buffer."
18218 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18219 (setq org-latex-fragment-image-overlays nil))
18221 (defun org-preview-latex-fragment (&optional subtree)
18222 "Preview the LaTeX fragment at point, or all locally or globally.
18223 If the cursor is in a LaTeX fragment, create the image and overlay
18224 it over the source code. If there is no fragment at point, display
18225 all fragments in the current text, from one headline to the next. With
18226 prefix SUBTREE, display all fragments in the current subtree. With a
18227 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18228 the cursor is before the first headline,
18229 display all fragments in the buffer.
18230 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18231 (interactive "P")
18232 (unless buffer-file-name
18233 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18234 (when (display-graphic-p)
18235 (org-remove-latex-fragment-image-overlays)
18236 (save-excursion
18237 (save-restriction
18238 (let (beg end at msg)
18239 (cond
18240 ((or (equal subtree '(16))
18241 (not (save-excursion
18242 (re-search-backward org-outline-regexp-bol nil t))))
18243 (setq beg (point-min) end (point-max)
18244 msg "Creating images for buffer...%s"))
18245 ((equal subtree '(4))
18246 (org-back-to-heading)
18247 (setq beg (point) end (org-end-of-subtree t)
18248 msg "Creating images for subtree...%s"))
18250 (if (setq at (org-inside-LaTeX-fragment-p))
18251 (goto-char (max (point-min) (- (cdr at) 2)))
18252 (org-back-to-heading))
18253 (setq beg (point) end (progn (outline-next-heading) (point))
18254 msg (if at "Creating image...%s"
18255 "Creating images for entry...%s"))))
18256 (message msg "")
18257 (narrow-to-region beg end)
18258 (goto-char beg)
18259 (org-format-latex
18260 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18261 (file-name-nondirectory
18262 buffer-file-name)))
18263 default-directory 'overlays msg at 'forbuffer
18264 org-latex-create-formula-image-program)
18265 (message msg "done. Use `C-c C-c' to remove images."))))))
18267 (defun org-format-latex (prefix &optional dir overlays msg at
18268 forbuffer processing-type)
18269 "Replace LaTeX fragments with links to an image, and produce images.
18270 Some of the options can be changed using the variable
18271 `org-format-latex-options'."
18272 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18273 (let* ((prefixnodir (file-name-nondirectory prefix))
18274 (absprefix (expand-file-name prefix dir))
18275 (todir (file-name-directory absprefix))
18276 (opt org-format-latex-options)
18277 (optnew org-format-latex-options)
18278 (matchers (plist-get opt :matchers))
18279 (re-list org-latex-regexps)
18280 (cnt 0) txt hash link beg end re e checkdir
18281 string
18282 m n block-type block linkfile movefile ov)
18283 ;; Check the different regular expressions
18284 (while (setq e (pop re-list))
18285 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18286 block (if block-type "\n\n" ""))
18287 (when (member m matchers)
18288 (goto-char (point-min))
18289 (while (re-search-forward re nil t)
18290 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18291 (or (not overlays)
18292 (not (eq (get-char-property (match-beginning n)
18293 'org-overlay-type)
18294 'org-latex-overlay))))
18295 (cond
18296 ((eq processing-type 'verbatim))
18297 ((eq processing-type 'mathjax)
18298 ;; Prepare for MathJax processing.
18299 (setq string (match-string n))
18300 (when (member m '("$" "$1"))
18301 (save-excursion
18302 (delete-region (match-beginning n) (match-end n))
18303 (goto-char (match-beginning n))
18304 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18305 ((or (eq processing-type 'dvipng)
18306 (eq processing-type 'imagemagick))
18307 ;; Process to an image.
18308 (setq txt (match-string n)
18309 beg (match-beginning n) end (match-end n)
18310 cnt (1+ cnt))
18311 (let ((face (face-at-point))
18312 (fg (plist-get opt :foreground))
18313 (bg (plist-get opt :background))
18314 ;; Ensure full list is printed.
18315 print-length print-level)
18316 (when forbuffer
18317 ;; Get the colors from the face at point.
18318 (goto-char beg)
18319 (when (eq fg 'auto)
18320 (setq fg (face-attribute face :foreground nil 'default)))
18321 (when (eq bg 'auto)
18322 (setq bg (face-attribute face :background nil 'default)))
18323 (setq optnew (copy-sequence opt))
18324 (plist-put optnew :foreground fg)
18325 (plist-put optnew :background bg))
18326 (setq hash (sha1 (prin1-to-string
18327 (list org-format-latex-header
18328 org-latex-default-packages-alist
18329 org-latex-packages-alist
18330 org-format-latex-options
18331 forbuffer txt fg bg)))
18332 linkfile (format "%s_%s.png" prefix hash)
18333 movefile (format "%s_%s.png" absprefix hash)))
18334 (setq link (concat block "[[file:" linkfile "]]" block))
18335 (if msg (message msg cnt))
18336 (goto-char beg)
18337 (unless checkdir ; Ensure the directory exists.
18338 (setq checkdir t)
18339 (or (file-directory-p todir) (make-directory todir t)))
18340 (unless (file-exists-p movefile)
18341 (org-create-formula-image
18342 txt movefile optnew forbuffer processing-type))
18343 (if overlays
18344 (progn
18345 (mapc (lambda (o)
18346 (if (eq (overlay-get o 'org-overlay-type)
18347 'org-latex-overlay)
18348 (delete-overlay o)))
18349 (overlays-in beg end))
18350 (setq ov (make-overlay beg end))
18351 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18352 (if (featurep 'xemacs)
18353 (progn
18354 (overlay-put ov 'invisible t)
18355 (overlay-put
18356 ov 'end-glyph
18357 (make-glyph (vector 'png :file movefile))))
18358 (overlay-put
18359 ov 'display
18360 (list 'image :type 'png :file movefile :ascent 'center)))
18361 (push ov org-latex-fragment-image-overlays)
18362 (goto-char end))
18363 (delete-region beg end)
18364 (insert (org-add-props link
18365 (list 'org-latex-src
18366 (replace-regexp-in-string
18367 "\"" "" txt)
18368 'org-latex-src-embed-type
18369 (if block-type 'paragraph 'character))))))
18370 ((eq processing-type 'mathml)
18371 ;; Process to MathML
18372 (unless (save-match-data (org-format-latex-mathml-available-p))
18373 (user-error "LaTeX to MathML converter not configured"))
18374 (setq txt (match-string n)
18375 beg (match-beginning n) end (match-end n)
18376 cnt (1+ cnt))
18377 (if msg (message msg cnt))
18378 (goto-char beg)
18379 (delete-region beg end)
18380 (insert (org-format-latex-as-mathml
18381 txt block-type prefix dir)))
18383 (error "Unknown conversion type %s for LaTeX fragments"
18384 processing-type)))))))))
18386 (defun org-create-math-formula (latex-frag &optional mathml-file)
18387 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18388 Use `org-latex-to-mathml-convert-command'. If the conversion is
18389 sucessful, return the portion between \"<math...> </math>\"
18390 elements otherwise return nil. When MATHML-FILE is specified,
18391 write the results in to that file. When invoked as an
18392 interactive command, prompt for LATEX-FRAG, with initial value
18393 set to the current active region and echo the results for user
18394 inspection."
18395 (interactive (list (let ((frag (when (org-region-active-p)
18396 (buffer-substring-no-properties
18397 (region-beginning) (region-end)))))
18398 (read-string "LaTeX Fragment: " frag nil frag))))
18399 (unless latex-frag (error "Invalid LaTeX fragment"))
18400 (let* ((tmp-in-file (file-relative-name
18401 (make-temp-name (expand-file-name "ltxmathml-in"))))
18402 (ignore (write-region latex-frag nil tmp-in-file))
18403 (tmp-out-file (file-relative-name
18404 (make-temp-name (expand-file-name "ltxmathml-out"))))
18405 (cmd (format-spec
18406 org-latex-to-mathml-convert-command
18407 `((?j . ,(shell-quote-argument
18408 (expand-file-name org-latex-to-mathml-jar-file)))
18409 (?I . ,(shell-quote-argument tmp-in-file))
18410 (?o . ,(shell-quote-argument tmp-out-file)))))
18411 mathml shell-command-output)
18412 (when (org-called-interactively-p 'any)
18413 (unless (org-format-latex-mathml-available-p)
18414 (user-error "LaTeX to MathML converter not configured")))
18415 (message "Running %s" cmd)
18416 (setq shell-command-output (shell-command-to-string cmd))
18417 (setq mathml
18418 (when (file-readable-p tmp-out-file)
18419 (with-current-buffer (find-file-noselect tmp-out-file t)
18420 (goto-char (point-min))
18421 (when (re-search-forward
18422 (concat
18423 (regexp-quote
18424 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18425 "\\(.\\|\n\\)*"
18426 (regexp-quote "</math>")) nil t)
18427 (prog1 (match-string 0) (kill-buffer))))))
18428 (cond
18429 (mathml
18430 (setq mathml
18431 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18432 (when mathml-file
18433 (write-region mathml nil mathml-file))
18434 (when (org-called-interactively-p 'any)
18435 (message mathml)))
18436 ((message "LaTeX to MathML conversion failed")
18437 (message shell-command-output)))
18438 (delete-file tmp-in-file)
18439 (when (file-exists-p tmp-out-file)
18440 (delete-file tmp-out-file))
18441 mathml))
18443 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18444 prefix &optional dir)
18445 "Use `org-create-math-formula' but check local cache first."
18446 (let* ((absprefix (expand-file-name prefix dir))
18447 (print-length nil) (print-level nil)
18448 (formula-id (concat
18449 "formula-"
18450 (sha1
18451 (prin1-to-string
18452 (list latex-frag
18453 org-latex-to-mathml-convert-command)))))
18454 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18455 (formula-cache-dir (file-name-directory formula-cache)))
18457 (unless (file-directory-p formula-cache-dir)
18458 (make-directory formula-cache-dir t))
18460 (unless (file-exists-p formula-cache)
18461 (org-create-math-formula latex-frag formula-cache))
18463 (if (file-exists-p formula-cache)
18464 ;; Successful conversion. Return the link to MathML file.
18465 (org-add-props
18466 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18467 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18468 'org-latex-src-embed-type (if latex-frag-type
18469 'paragraph 'character)))
18470 ;; Failed conversion. Return the LaTeX fragment verbatim
18471 latex-frag)))
18473 (defun org-create-formula-image (string tofile options buffer &optional type)
18474 "Create an image from LaTeX source using dvipng or convert.
18475 This function calls either `org-create-formula-image-with-dvipng'
18476 or `org-create-formula-image-with-imagemagick' depending on the
18477 value of `org-latex-create-formula-image-program' or on the value
18478 of the optional TYPE variable.
18480 Note: ultimately these two function should be combined as they
18481 share a good deal of logic."
18482 (org-check-external-command
18483 "latex" "needed to convert LaTeX fragments to images")
18484 (funcall
18485 (case (or type org-latex-create-formula-image-program)
18486 ('dvipng
18487 (org-check-external-command
18488 "dvipng" "needed to convert LaTeX fragments to images")
18489 #'org-create-formula-image-with-dvipng)
18490 ('imagemagick
18491 (org-check-external-command
18492 "convert" "you need to install imagemagick")
18493 #'org-create-formula-image-with-imagemagick)
18494 (t (error
18495 "Invalid value of `org-latex-create-formula-image-program'")))
18496 string tofile options buffer))
18498 (declare-function org-export-get-backend "ox" (name))
18499 (declare-function org-export--get-global-options "ox" (&optional backend))
18500 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18501 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18502 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18503 (defun org-create-formula--latex-header ()
18504 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18505 (let ((info (org-combine-plists (org-export--get-global-options
18506 (org-export-get-backend 'latex))
18507 (org-export--get-inbuffer-options
18508 (org-export-get-backend 'latex)))))
18509 (org-latex-guess-babel-language
18510 (org-latex-guess-inputenc
18511 (org-splice-latex-header
18512 org-format-latex-header
18513 org-latex-default-packages-alist
18514 org-latex-packages-alist t
18515 (plist-get info :latex-header)))
18516 info)))
18518 ;; This function borrows from Ganesh Swami's latex2png.el
18519 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18520 "This calls dvipng."
18521 (require 'ox-latex)
18522 (let* ((tmpdir (if (featurep 'xemacs)
18523 (temp-directory)
18524 temporary-file-directory))
18525 (texfilebase (make-temp-name
18526 (expand-file-name "orgtex" tmpdir)))
18527 (texfile (concat texfilebase ".tex"))
18528 (dvifile (concat texfilebase ".dvi"))
18529 (pngfile (concat texfilebase ".png"))
18530 (fnh (if (featurep 'xemacs)
18531 (font-height (face-font 'default))
18532 (face-attribute 'default :height nil)))
18533 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18534 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18535 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18536 "Black"))
18537 (bg (or (plist-get options (if buffer :background :html-background))
18538 "Transparent")))
18539 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18540 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18541 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18542 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18543 (let ((latex-header (org-create-formula--latex-header)))
18544 (with-temp-file texfile
18545 (insert latex-header)
18546 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18547 (let ((dir default-directory))
18548 (condition-case nil
18549 (progn
18550 (cd tmpdir)
18551 (call-process "latex" nil nil nil texfile))
18552 (error nil))
18553 (cd dir))
18554 (if (not (file-exists-p dvifile))
18555 (progn (message "Failed to create dvi file from %s" texfile) nil)
18556 (condition-case nil
18557 (if (featurep 'xemacs)
18558 (call-process "dvipng" nil nil nil
18559 "-fg" fg "-bg" bg
18560 "-T" "tight"
18561 "-o" pngfile
18562 dvifile)
18563 (call-process "dvipng" nil nil nil
18564 "-fg" fg "-bg" bg
18565 "-D" dpi
18566 ;;"-x" scale "-y" scale
18567 "-T" "tight"
18568 "-o" pngfile
18569 dvifile))
18570 (error nil))
18571 (if (not (file-exists-p pngfile))
18572 (if org-format-latex-signal-error
18573 (error "Failed to create png file from %s" texfile)
18574 (message "Failed to create png file from %s" texfile)
18575 nil)
18576 ;; Use the requested file name and clean up
18577 (copy-file pngfile tofile 'replace)
18578 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18579 (if (file-exists-p (concat texfilebase e))
18580 (delete-file (concat texfilebase e))))
18581 pngfile))))
18583 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18584 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18585 "This calls convert, which is included into imagemagick."
18586 (require 'ox-latex)
18587 (let* ((tmpdir (if (featurep 'xemacs)
18588 (temp-directory)
18589 temporary-file-directory))
18590 (texfilebase (make-temp-name
18591 (expand-file-name "orgtex" tmpdir)))
18592 (texfile (concat texfilebase ".tex"))
18593 (pdffile (concat texfilebase ".pdf"))
18594 (pngfile (concat texfilebase ".png"))
18595 (fnh (if (featurep 'xemacs)
18596 (font-height (face-font 'default))
18597 (face-attribute 'default :height nil)))
18598 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18599 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18600 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18601 "black"))
18602 (bg (or (plist-get options (if buffer :background :html-background))
18603 "white")))
18604 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18605 (setq fg (org-latex-color-format fg)))
18606 (if (eq bg 'default) (setq bg (org-latex-color :background))
18607 (setq bg (org-latex-color-format
18608 (if (string= bg "Transparent") "white" bg))))
18609 (let ((latex-header (org-create-formula--latex-header)))
18610 (with-temp-file texfile
18611 (insert latex-header)
18612 (insert "\n\\begin{document}\n"
18613 "\\definecolor{fg}{rgb}{" fg "}\n"
18614 "\\definecolor{bg}{rgb}{" bg "}\n"
18615 "\n\\pagecolor{bg}\n"
18616 "\n{\\color{fg}\n"
18617 string
18618 "\n}\n"
18619 "\n\\end{document}\n")))
18620 (org-latex-compile texfile t)
18621 (if (not (file-exists-p pdffile))
18622 (progn (message "Failed to create pdf file from %s" texfile) nil)
18623 (condition-case nil
18624 (if (featurep 'xemacs)
18625 (call-process "convert" nil nil nil
18626 "-density" "96"
18627 "-trim"
18628 "-antialias"
18629 pdffile
18630 "-quality" "100"
18631 ;; "-sharpen" "0x1.0"
18632 pngfile)
18633 (call-process "convert" nil nil nil
18634 "-density" dpi
18635 "-trim"
18636 "-antialias"
18637 pdffile
18638 "-quality" "100"
18639 ;; "-sharpen" "0x1.0"
18640 pngfile))
18641 (error nil))
18642 (if (not (file-exists-p pngfile))
18643 (if org-format-latex-signal-error
18644 (error "Failed to create png file from %s" texfile)
18645 (message "Failed to create png file from %s" texfile)
18646 nil)
18647 ;; Use the requested file name and clean up
18648 (copy-file pngfile tofile 'replace)
18649 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18650 (if (file-exists-p (concat texfilebase e))
18651 (delete-file (concat texfilebase e))))
18652 pngfile))))
18654 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18655 "Fill a LaTeX header template TPL.
18656 In the template, the following place holders will be recognized:
18658 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18659 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18660 [PACKAGES] \\usepackage statements for PKG
18661 [NO-PACKAGES] do not include PKG
18662 [EXTRA] the string EXTRA
18663 [NO-EXTRA] do not include EXTRA
18665 For backward compatibility, if both the positive and the negative place
18666 holder is missing, the positive one (without the \"NO-\") will be
18667 assumed to be present at the end of the template.
18668 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18669 EXTRA is a string.
18670 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18671 (let (rpl (end ""))
18672 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18673 (setq rpl (if (or (match-end 1) (not def-pkg))
18674 "" (org-latex-packages-to-string def-pkg snippets-p t))
18675 tpl (replace-match rpl t t tpl))
18676 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18678 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18679 (setq rpl (if (or (match-end 1) (not pkg))
18680 "" (org-latex-packages-to-string pkg snippets-p t))
18681 tpl (replace-match rpl t t tpl))
18682 (if pkg (setq end
18683 (concat end "\n"
18684 (org-latex-packages-to-string pkg snippets-p)))))
18686 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18687 (setq rpl (if (or (match-end 1) (not extra))
18688 "" (concat extra "\n"))
18689 tpl (replace-match rpl t t tpl))
18690 (if (and extra (string-match "\\S-" extra))
18691 (setq end (concat end "\n" extra))))
18693 (if (string-match "\\S-" end)
18694 (concat tpl "\n" end)
18695 tpl)))
18697 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18698 "Turn an alist of packages into a string with the \\usepackage macros."
18699 (setq pkg (mapconcat (lambda(p)
18700 (cond
18701 ((stringp p) p)
18702 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18703 (format "%% Package %s omitted" (cadr p)))
18704 ((equal "" (car p))
18705 (format "\\usepackage{%s}" (cadr p)))
18707 (format "\\usepackage[%s]{%s}"
18708 (car p) (cadr p)))))
18710 "\n"))
18711 (if newline (concat pkg "\n") pkg))
18713 (defun org-dvipng-color (attr)
18714 "Return a RGB color specification for dvipng."
18715 (apply 'format "rgb %s %s %s"
18716 (mapcar 'org-normalize-color
18717 (if (featurep 'xemacs)
18718 (color-rgb-components
18719 (face-property 'default
18720 (cond ((eq attr :foreground) 'foreground)
18721 ((eq attr :background) 'background))))
18722 (color-values (face-attribute 'default attr nil))))))
18724 (defun org-dvipng-color-format (color-name)
18725 "Convert COLOR-NAME to a RGB color value for dvipng."
18726 (apply 'format "rgb %s %s %s"
18727 (mapcar 'org-normalize-color
18728 (color-values color-name))))
18730 (defun org-latex-color (attr)
18731 "Return a RGB color for the LaTeX color package."
18732 (apply 'format "%s,%s,%s"
18733 (mapcar 'org-normalize-color
18734 (if (featurep 'xemacs)
18735 (color-rgb-components
18736 (face-property 'default
18737 (cond ((eq attr :foreground) 'foreground)
18738 ((eq attr :background) 'background))))
18739 (color-values (face-attribute 'default attr nil))))))
18741 (defun org-latex-color-format (color-name)
18742 "Convert COLOR-NAME to a RGB color value."
18743 (apply 'format "%s,%s,%s"
18744 (mapcar 'org-normalize-color
18745 (color-values color-name))))
18747 (defun org-normalize-color (value)
18748 "Return string to be used as color value for an RGB component."
18749 (format "%g" (/ value 65535.0)))
18753 ;; Image display
18755 (defvar org-inline-image-overlays nil)
18756 (make-variable-buffer-local 'org-inline-image-overlays)
18758 (defun org-toggle-inline-images (&optional include-linked)
18759 "Toggle the display of inline images.
18760 INCLUDE-LINKED is passed to `org-display-inline-images'."
18761 (interactive "P")
18762 (if org-inline-image-overlays
18763 (progn
18764 (org-remove-inline-images)
18765 (message "Inline image display turned off"))
18766 (org-display-inline-images include-linked)
18767 (if (and (org-called-interactively-p)
18768 org-inline-image-overlays)
18769 (message "%d images displayed inline"
18770 (length org-inline-image-overlays))
18771 (message "No images to display inline"))))
18773 (defun org-redisplay-inline-images ()
18774 "Refresh the display of inline images."
18775 (interactive)
18776 (if (not org-inline-image-overlays)
18777 (org-toggle-inline-images)
18778 (org-toggle-inline-images)
18779 (org-toggle-inline-images)))
18781 (defun org-display-inline-images (&optional include-linked refresh beg end)
18782 "Display inline images.
18783 Normally only links without a description part are inlined, because this
18784 is how it will work for export. When INCLUDE-LINKED is set, also links
18785 with a description part will be inlined. This can be nice for a quick
18786 look at those images, but it does not reflect what exported files will look
18787 like.
18788 When REFRESH is set, refresh existing images between BEG and END.
18789 This will create new image displays only if necessary.
18790 BEG and END default to the buffer boundaries."
18791 (interactive "P")
18792 (when (display-graphic-p)
18793 (unless refresh
18794 (org-remove-inline-images)
18795 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18796 (save-excursion
18797 (save-restriction
18798 (widen)
18799 (setq beg (or beg (point-min)) end (or end (point-max)))
18800 (goto-char beg)
18801 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18802 (substring (org-image-file-name-regexp) 0 -2)
18803 "\\)\\]" (if include-linked "" "\\]")))
18804 (case-fold-search t)
18805 old file ov img type attrwidth width)
18806 (while (re-search-forward re end t)
18807 (setq old (get-char-property-and-overlay (match-beginning 1)
18808 'org-image-overlay)
18809 file (expand-file-name
18810 (concat (or (match-string 3) "") (match-string 4))))
18811 (when (image-type-available-p 'imagemagick)
18812 (setq attrwidth (if (or (listp org-image-actual-width)
18813 (null org-image-actual-width))
18814 (save-excursion
18815 (save-match-data
18816 (when (re-search-backward
18817 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18818 (save-excursion
18819 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18820 (string-to-number (match-string 1))))))
18821 width (cond ((eq org-image-actual-width t) nil)
18822 ((null org-image-actual-width) attrwidth)
18823 ((numberp org-image-actual-width)
18824 org-image-actual-width)
18825 ((listp org-image-actual-width)
18826 (or attrwidth (car org-image-actual-width))))
18827 type (if width 'imagemagick)))
18828 (when (file-exists-p file)
18829 (if (and (car-safe old) refresh)
18830 (image-refresh (overlay-get (cdr old) 'display))
18831 (setq img (save-match-data (create-image file type nil :width width)))
18832 (when img
18833 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18834 (overlay-put ov 'display img)
18835 (overlay-put ov 'face 'default)
18836 (overlay-put ov 'org-image-overlay t)
18837 (overlay-put ov 'modification-hooks
18838 (list 'org-display-inline-remove-overlay))
18839 (push ov org-inline-image-overlays))))))))))
18841 (define-obsolete-function-alias
18842 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18844 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18845 "Remove inline-display overlay if a corresponding region is modified."
18846 (let ((inhibit-modification-hooks t))
18847 (when (and ov after)
18848 (delete ov org-inline-image-overlays)
18849 (delete-overlay ov))))
18851 (defun org-remove-inline-images ()
18852 "Remove inline display of images."
18853 (interactive)
18854 (mapc 'delete-overlay org-inline-image-overlays)
18855 (setq org-inline-image-overlays nil))
18857 ;;;; Key bindings
18859 ;; Outline functions from `outline-mode-prefix-map'
18860 ;; that can be remapped in Org:
18861 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18862 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18863 (define-key org-mode-map [remap outline-forward-same-level]
18864 'org-forward-heading-same-level)
18865 (define-key org-mode-map [remap outline-backward-same-level]
18866 'org-backward-heading-same-level)
18867 (define-key org-mode-map [remap show-branches]
18868 'org-kill-note-or-show-branches)
18869 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18870 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18871 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18873 ;; Outline functions from `outline-mode-prefix-map' that can not
18874 ;; be remapped in Org:
18876 ;; - the column "key binding" shows whether the Outline function is still
18877 ;; available in Org mode on the same key that it has been bound to in
18878 ;; Outline mode:
18879 ;; - "overridden": key used for a different functionality in Org mode
18880 ;; - else: key still bound to the same Outline function in Org mode
18882 ;; | Outline function | key binding | Org replacement |
18883 ;; |------------------------------------+-------------+-----------------------|
18884 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18885 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18886 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18887 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18888 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18889 ;; | `show-entry' | overridden | no replacement |
18890 ;; | `show-children' | `C-c C-i' | visibility cycling |
18891 ;; | `show-branches' | `C-c C-k' | still same function |
18892 ;; | `show-subtree' | overridden | visibility cycling |
18893 ;; | `show-all' | overridden | no replacement |
18894 ;; | `hide-subtree' | overridden | visibility cycling |
18895 ;; | `hide-body' | overridden | no replacement |
18896 ;; | `hide-entry' | overridden | visibility cycling |
18897 ;; | `hide-leaves' | overridden | no replacement |
18898 ;; | `hide-sublevels' | overridden | no replacement |
18899 ;; | `hide-other' | overridden | no replacement |
18901 ;; Make `C-c C-x' a prefix key
18902 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18904 ;; TAB key with modifiers
18905 (org-defkey org-mode-map "\C-i" 'org-cycle)
18906 (org-defkey org-mode-map [(tab)] 'org-cycle)
18907 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18908 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18909 ;; The following line is necessary under Suse GNU/Linux
18910 (unless (featurep 'xemacs)
18911 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18912 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18913 (define-key org-mode-map [backtab] 'org-shifttab)
18915 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18916 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18917 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18919 ;; Cursor keys with modifiers
18920 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18921 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18922 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18923 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18925 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18926 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18927 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18928 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18930 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18931 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18932 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18933 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18935 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18936 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18937 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18938 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18940 ;; Babel keys
18941 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18942 (mapc (lambda (pair)
18943 (define-key org-babel-map (car pair) (cdr pair)))
18944 org-babel-key-bindings)
18946 ;;; Extra keys for tty access.
18947 ;; We only set them when really needed because otherwise the
18948 ;; menus don't show the simple keys
18950 (when (or org-use-extra-keys
18951 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18952 (not window-system))
18953 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18954 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18955 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18956 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18957 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18958 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18959 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18960 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18961 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18962 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18963 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18964 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18965 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18966 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18967 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18968 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18969 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18970 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18971 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18972 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18973 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18974 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18975 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18976 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18977 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18978 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18979 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18980 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18982 ;; All the other keys
18984 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18985 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18986 (if (boundp 'narrow-map)
18987 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18988 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18989 (if (boundp 'narrow-map)
18990 (org-defkey narrow-map "b" 'org-narrow-to-block)
18991 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18992 (if (boundp 'narrow-map)
18993 (org-defkey narrow-map "e" 'org-narrow-to-element)
18994 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18995 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18996 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18997 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18998 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18999 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19000 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19001 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19002 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19003 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19004 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19005 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19006 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19007 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19008 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19009 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19010 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19011 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19012 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19013 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19014 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19015 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19016 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19017 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19018 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19019 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19020 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19021 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19022 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19023 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19024 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19025 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19026 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19027 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19028 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19029 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19030 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19031 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19032 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19033 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19034 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19035 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19036 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19037 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19038 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19039 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19040 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19041 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19042 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19043 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19044 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19045 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19046 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19047 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19048 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19049 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19050 (org-defkey org-mode-map "\C-c^" 'org-sort)
19051 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19052 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19053 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19054 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19055 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-element)
19056 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-element)
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 ((ignore-errors (goto-char (org-in-item-p)))
22010 (goto-char (org-list-get-top-point (org-list-struct)))
22011 (setq column (org-get-indentation)))
22012 ;; There was an heading above.
22013 ((looking-at "\\*+[ \t]+")
22014 (if (not org-adapt-indentation)
22015 (setq column 0)
22016 (goto-char (match-end 0))
22017 (setq column (current-column))))
22018 ;; A drawer had started and is unfinished
22019 ((looking-at org-drawer-regexp)
22020 (goto-char (1- (match-beginning 1)))
22021 (setq column (current-column)))
22022 ;; Else, nothing noticeable found: get indentation and go on.
22023 (t (setq column (org-get-indentation))))))
22024 ;; Now apply indentation and move cursor accordingly
22025 (goto-char pos)
22026 (if (<= (current-column) (current-indentation))
22027 (org-indent-line-to column)
22028 (save-excursion (org-indent-line-to column)))
22029 ;; Special polishing for properties, see `org-property-format'
22030 (setq column (current-column))
22031 (beginning-of-line 1)
22032 (if (looking-at org-property-re)
22033 (replace-match (concat (match-string 4)
22034 (format org-property-format
22035 (match-string 1) (match-string 3)))
22036 t t))
22037 (org-move-to-column column))))
22039 (defun org-indent-drawer ()
22040 "Indent the drawer at point."
22041 (interactive)
22042 (let ((p (point))
22043 (e (and (save-excursion (re-search-forward ":END:" nil t))
22044 (match-end 0)))
22045 (folded
22046 (save-excursion
22047 (end-of-line)
22048 (when (overlays-at (point))
22049 (member 'invisible (overlay-properties
22050 (car (overlays-at (point)))))))))
22051 (when folded (org-cycle))
22052 (indent-for-tab-command)
22053 (while (and (move-beginning-of-line 2) (< (point) e))
22054 (indent-for-tab-command))
22055 (goto-char p)
22056 (when folded (org-cycle)))
22057 (message "Drawer at point indented"))
22059 (defun org-indent-block ()
22060 "Indent the block at point."
22061 (interactive)
22062 (let ((p (point))
22063 (case-fold-search t)
22064 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22065 (match-end 0)))
22066 (folded
22067 (save-excursion
22068 (end-of-line)
22069 (when (overlays-at (point))
22070 (member 'invisible (overlay-properties
22071 (car (overlays-at (point)))))))))
22072 (when folded (org-cycle))
22073 (indent-for-tab-command)
22074 (while (and (move-beginning-of-line 2) (< (point) e))
22075 (indent-for-tab-command))
22076 (goto-char p)
22077 (when folded (org-cycle)))
22078 (message "Block at point indented"))
22080 (defun org-indent-region (start end)
22081 "Indent region."
22082 (interactive "r")
22083 (save-excursion
22084 (let ((line-end (org-current-line end)))
22085 (goto-char start)
22086 (while (< (org-current-line) line-end)
22087 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22088 (t (call-interactively 'org-indent-line)))
22089 (move-beginning-of-line 2)))))
22092 ;;; Filling
22094 ;; We use our own fill-paragraph and auto-fill functions.
22096 ;; `org-fill-paragraph' relies on adaptive filling and context
22097 ;; checking. Appropriate `fill-prefix' is computed with
22098 ;; `org-adaptive-fill-function'.
22100 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22101 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22102 ;; `org-adaptive-fill-function' value. Internally,
22103 ;; `org-comment-line-break-function' breaks the line.
22105 ;; `org-setup-filling' installs filling and auto-filling related
22106 ;; variables during `org-mode' initialization.
22108 (defvar org-element-paragraph-separate) ; org-element.el
22109 (defun org-setup-filling ()
22110 (require 'org-element)
22111 ;; Prevent auto-fill from inserting unwanted new items.
22112 (when (boundp 'fill-nobreak-predicate)
22113 (org-set-local
22114 'fill-nobreak-predicate
22115 (org-uniquify
22116 (append fill-nobreak-predicate
22117 '(org-fill-line-break-nobreak-p
22118 org-fill-paragraph-with-timestamp-nobreak-p)))))
22119 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22120 (org-set-local 'paragraph-start paragraph-ending)
22121 (org-set-local 'paragraph-separate paragraph-ending))
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 (defun org-fill-line-break-nobreak-p ()
22129 "Non-nil when a new line at point would create an Org line break."
22130 (save-excursion
22131 (skip-chars-backward "[ \t]")
22132 (skip-chars-backward "\\\\")
22133 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22135 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22136 "Non-nil when a new line at point would split a timestamp."
22137 (and (org-at-timestamp-p t)
22138 (not (looking-at org-ts-regexp-both))))
22140 (declare-function message-in-body-p "message" ())
22141 (defvar orgtbl-line-start-regexp) ; From org-table.el
22142 (defun org-adaptive-fill-function ()
22143 "Compute a fill prefix for the current line.
22144 Return fill prefix, as a string, or nil if current line isn't
22145 meant to be filled. For convenience, if `adaptive-fill-regexp'
22146 matches in paragraphs or comments, use it."
22147 (let (prefix)
22148 (catch 'exit
22149 (when (derived-mode-p 'message-mode)
22150 (save-excursion
22151 (beginning-of-line)
22152 (cond ((or (not (message-in-body-p))
22153 (looking-at orgtbl-line-start-regexp))
22154 (throw 'exit nil))
22155 ((looking-at message-cite-prefix-regexp)
22156 (throw 'exit (match-string-no-properties 0)))
22157 ((looking-at org-outline-regexp)
22158 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22159 (org-with-wide-buffer
22160 (let* ((p (line-beginning-position))
22161 (element (save-excursion
22162 (beginning-of-line)
22163 (or (ignore-errors (org-element-at-point))
22164 (user-error "An element cannot be parsed line %d"
22165 (line-number-at-pos (point))))))
22166 (type (org-element-type element))
22167 (post-affiliated (org-element-property :post-affiliated element)))
22168 (unless (and post-affiliated (< p post-affiliated))
22169 (case type
22170 (comment
22171 (save-excursion
22172 (beginning-of-line)
22173 (looking-at "[ \t]*#")
22174 (goto-char (match-end 0))
22175 (let ((comment-prefix (match-string 0)))
22176 (if (looking-at adaptive-fill-regexp)
22177 (concat comment-prefix (match-string 0))
22178 comment-prefix))))
22179 (footnote-definition "")
22180 ((item plain-list)
22181 (make-string (org-list-item-body-column
22182 (or post-affiliated
22183 (org-element-property :begin element)))
22184 ? ))
22185 (paragraph
22186 ;; Fill prefix is usually the same as the current line,
22187 ;; unless the paragraph is at the beginning of an item.
22188 (let ((parent (org-element-property :parent element)))
22189 (save-excursion
22190 (beginning-of-line)
22191 (cond ((eq (org-element-type parent) 'item)
22192 (make-string (org-list-item-body-column
22193 (org-element-property :begin parent))
22194 ? ))
22195 ((looking-at adaptive-fill-regexp) (match-string 0))
22196 ((looking-at "[ \t]+") (match-string 0))
22197 (t "")))))
22198 (comment-block
22199 ;; Only fill contents if P is within block boundaries.
22200 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22201 (forward-line)
22202 (point)))
22203 (cend (save-excursion
22204 (goto-char (org-element-property :end element))
22205 (skip-chars-backward " \r\t\n")
22206 (line-beginning-position))))
22207 (when (and (>= p cbeg) (< p cend))
22208 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22209 (match-string 0)
22210 "")))))))))))
22212 (declare-function message-goto-body "message" ())
22213 (defvar message-cite-prefix-regexp) ; From message.el
22214 (defun org-fill-paragraph (&optional justify)
22215 "Fill element at point, when applicable.
22217 This function only applies to comment blocks, comments, example
22218 blocks and paragraphs. Also, as a special case, re-align table
22219 when point is at one.
22221 If JUSTIFY is non-nil (interactively, with prefix argument),
22222 justify as well. If `sentence-end-double-space' is non-nil, then
22223 period followed by one space does not end a sentence, so don't
22224 break a line there. The variable `fill-column' controls the
22225 width for filling.
22227 For convenience, when point is at a plain list, an item or
22228 a footnote definition, try to fill the first paragraph within."
22229 (interactive)
22230 (if (and (derived-mode-p 'message-mode)
22231 (or (not (message-in-body-p))
22232 (save-excursion (move-beginning-of-line 1)
22233 (looking-at message-cite-prefix-regexp))))
22234 ;; First ensure filling is correct in message-mode.
22235 (let ((fill-paragraph-function
22236 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22237 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22238 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22239 (paragraph-separate
22240 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22241 (fill-paragraph nil))
22242 (with-syntax-table org-mode-transpose-word-syntax-table
22243 ;; Move to end of line in order to get the first paragraph
22244 ;; within a plain list or a footnote definition.
22245 (let ((element (save-excursion
22246 (end-of-line)
22247 (or (ignore-errors (org-element-at-point))
22248 (user-error "An element cannot be parsed line %d"
22249 (line-number-at-pos (point)))))))
22250 ;; First check if point is in a blank line at the beginning of
22251 ;; the buffer. In that case, ignore filling.
22252 (case (org-element-type element)
22253 ;; Use major mode filling function is src blocks.
22254 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22255 ;; Align Org tables, leave table.el tables as-is.
22256 (table-row (org-table-align) t)
22257 (table
22258 (when (eq (org-element-property :type element) 'org)
22259 (save-excursion
22260 (goto-char (org-element-property :post-affiliated element))
22261 (org-table-align)))
22263 (paragraph
22264 ;; Paragraphs may contain `line-break' type objects.
22265 (let ((beg (max (point-min)
22266 (org-element-property :contents-begin element)))
22267 (end (min (point-max)
22268 (org-element-property :contents-end element))))
22269 ;; Do nothing if point is at an affiliated keyword.
22270 (if (< (line-end-position) beg) t
22271 (when (derived-mode-p 'message-mode)
22272 ;; In `message-mode', do not fill following citation
22273 ;; in current paragraph nor text before message body.
22274 (let ((body-start (save-excursion (message-goto-body))))
22275 (when body-start (setq beg (max body-start beg))))
22276 (when (save-excursion
22277 (re-search-forward
22278 (concat "^" message-cite-prefix-regexp) end t))
22279 (setq end (match-beginning 0))))
22280 ;; Fill paragraph, taking line breaks into account.
22281 ;; For that, slice the paragraph using line breaks as
22282 ;; separators, and fill the parts in reverse order to
22283 ;; avoid messing with markers.
22284 (save-excursion
22285 (goto-char end)
22286 (mapc
22287 (lambda (pos)
22288 (fill-region-as-paragraph pos (point) justify)
22289 (goto-char pos))
22290 ;; Find the list of ending positions for line breaks
22291 ;; in the current paragraph. Add paragraph
22292 ;; beginning to include first slice.
22293 (nreverse
22294 (cons beg
22295 (org-element-map
22296 (org-element--parse-objects
22297 beg end nil (org-element-restriction 'paragraph))
22298 'line-break
22299 (lambda (lb) (org-element-property :end lb)))))))
22300 t)))
22301 ;; Contents of `comment-block' type elements should be
22302 ;; filled as plain text, but only if point is within block
22303 ;; markers.
22304 (comment-block
22305 (let* ((case-fold-search t)
22306 (beg (save-excursion
22307 (goto-char (org-element-property :begin element))
22308 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22309 (forward-line)
22310 (point)))
22311 (end (save-excursion
22312 (goto-char (org-element-property :end element))
22313 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22314 (line-beginning-position))))
22315 (if (or (< (point) beg) (> (point) end)) t
22316 (fill-region-as-paragraph
22317 (save-excursion (end-of-line)
22318 (re-search-backward "^[ \t]*$" beg 'move)
22319 (line-beginning-position))
22320 (save-excursion (beginning-of-line)
22321 (re-search-forward "^[ \t]*$" end 'move)
22322 (line-beginning-position))
22323 justify))))
22324 ;; Fill comments.
22325 (comment
22326 (let ((begin (org-element-property :post-affiliated element))
22327 (end (org-element-property :end element)))
22328 (when (and (>= (point) begin) (<= (point) end))
22329 (let ((begin (save-excursion
22330 (end-of-line)
22331 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22332 (progn (forward-line) (point))
22333 begin)))
22334 (end (save-excursion
22335 (end-of-line)
22336 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22337 (1- (line-beginning-position))
22338 (skip-chars-backward " \r\t\n")
22339 (line-end-position)))))
22340 ;; Do not fill comments when at a blank line.
22341 (when (> end begin)
22342 (let ((fill-prefix
22343 (save-excursion
22344 (beginning-of-line)
22345 (looking-at "[ \t]*#")
22346 (let ((comment-prefix (match-string 0)))
22347 (goto-char (match-end 0))
22348 (if (looking-at adaptive-fill-regexp)
22349 (concat comment-prefix (match-string 0))
22350 (concat comment-prefix " "))))))
22351 (save-excursion
22352 (fill-region-as-paragraph begin end justify))))))
22354 ;; Ignore every other element.
22355 (otherwise t))))))
22357 (defun org-auto-fill-function ()
22358 "Auto-fill function."
22359 ;; Check if auto-filling is meaningful.
22360 (let ((fc (current-fill-column)))
22361 (when (and fc (> (current-column) fc))
22362 (let* ((fill-prefix (org-adaptive-fill-function))
22363 ;; Enforce empty fill prefix, if required. Otherwise, it
22364 ;; will be computed again.
22365 (adaptive-fill-mode (not (equal fill-prefix ""))))
22366 (when fill-prefix (do-auto-fill))))))
22368 (defun org-comment-line-break-function (&optional soft)
22369 "Break line at point and indent, continuing comment if within one.
22370 The inserted newline is marked hard if variable
22371 `use-hard-newlines' is true, unless optional argument SOFT is
22372 non-nil."
22373 (if soft (insert-and-inherit ?\n) (newline 1))
22374 (save-excursion (forward-char -1) (delete-horizontal-space))
22375 (delete-horizontal-space)
22376 (indent-to-left-margin)
22377 (insert-before-markers-and-inherit fill-prefix))
22380 ;;; Comments
22382 ;; Org comments syntax is quite complex. It requires the entire line
22383 ;; to be just a comment. Also, even with the right syntax at the
22384 ;; beginning of line, some some elements (i.e. verse-block or
22385 ;; example-block) don't accept comments. Usual Emacs comment commands
22386 ;; cannot cope with those requirements. Therefore, Org replaces them.
22388 ;; Org still relies on `comment-dwim', but cannot trust
22389 ;; `comment-only-p'. So, `comment-region-function' and
22390 ;; `uncomment-region-function' both point
22391 ;; to`org-comment-or-uncomment-region'. Eventually,
22392 ;; `org-insert-comment' takes care of insertion of comments at the
22393 ;; beginning of line.
22395 ;; `org-setup-comments-handling' install comments related variables
22396 ;; during `org-mode' initialization.
22398 (defun org-setup-comments-handling ()
22399 (interactive)
22400 (org-set-local 'comment-use-syntax nil)
22401 (org-set-local 'comment-start "# ")
22402 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22403 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22404 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22405 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22407 (defun org-insert-comment ()
22408 "Insert an empty comment above current line.
22409 If the line is empty, insert comment at its beginning."
22410 (beginning-of-line)
22411 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22412 (org-indent-line)
22413 (insert "# "))
22415 (defvar comment-empty-lines) ; From newcomment.el.
22416 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22417 "Comment or uncomment each non-blank line in the region.
22418 Uncomment each non-blank line between BEG and END if it only
22419 contains commented lines. Otherwise, comment them."
22420 (save-restriction
22421 ;; Restrict region
22422 (narrow-to-region (save-excursion (goto-char beg)
22423 (skip-chars-forward " \r\t\n" end)
22424 (line-beginning-position))
22425 (save-excursion (goto-char end)
22426 (skip-chars-backward " \r\t\n" beg)
22427 (line-end-position)))
22428 (let ((uncommentp
22429 ;; UNCOMMENTP is non-nil when every non blank line between
22430 ;; BEG and END is a comment.
22431 (save-excursion
22432 (goto-char (point-min))
22433 (while (and (not (eobp))
22434 (let ((element (org-element-at-point)))
22435 (and (eq (org-element-type element) 'comment)
22436 (goto-char (min (point-max)
22437 (org-element-property
22438 :end element)))))))
22439 (eobp))))
22440 (if uncommentp
22441 ;; Only blank lines and comments in region: uncomment it.
22442 (save-excursion
22443 (goto-char (point-min))
22444 (while (not (eobp))
22445 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22446 (replace-match "" nil nil nil 1))
22447 (forward-line)))
22448 ;; Comment each line in region.
22449 (let ((min-indent (point-max)))
22450 ;; First find the minimum indentation across all lines.
22451 (save-excursion
22452 (goto-char (point-min))
22453 (while (and (not (eobp)) (not (zerop min-indent)))
22454 (unless (looking-at "[ \t]*$")
22455 (setq min-indent (min min-indent (current-indentation))))
22456 (forward-line)))
22457 ;; Then loop over all lines.
22458 (save-excursion
22459 (goto-char (point-min))
22460 (while (not (eobp))
22461 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22462 ;; Don't get fooled by invisible text (e.g. link path)
22463 ;; when moving to column MIN-INDENT.
22464 (let ((buffer-invisibility-spec nil))
22465 (org-move-to-column min-indent t))
22466 (insert comment-start))
22467 (forward-line))))))))
22470 ;;; Planning
22472 ;; This section contains tools to operate on timestamp objects, as
22473 ;; returned by, e.g. `org-element-context'.
22475 (defun org-timestamp-has-time-p (timestamp)
22476 "Non-nil when TIMESTAMP has a time specified."
22477 (org-element-property :hour-start timestamp))
22479 (defun org-timestamp-format (timestamp format &optional end utc)
22480 "Format a TIMESTAMP element into a string.
22482 FORMAT is a format specifier to be passed to
22483 `format-time-string'.
22485 When optional argument END is non-nil, use end of date-range or
22486 time-range, if possible.
22488 When optional argument UTC is non-nil, time will be expressed as
22489 Universal Time."
22490 (format-time-string
22491 format
22492 (apply 'encode-time
22493 (cons 0
22494 (mapcar
22495 (lambda (prop) (or (org-element-property prop timestamp) 0))
22496 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22497 '(:minute-start :hour-start :day-start :month-start
22498 :year-start)))))
22499 utc))
22501 (defun org-timestamp-split-range (timestamp &optional end)
22502 "Extract a timestamp object from a date or time range.
22504 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22505 the end of the range. Otherwise, extract its start.
22507 Return a new timestamp object sharing the same parent as
22508 TIMESTAMP."
22509 (let ((type (org-element-property :type timestamp)))
22510 (if (memq type '(active inactive diary)) timestamp
22511 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22512 ;; Set new type.
22513 (org-element-put-property
22514 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22515 ;; Copy start properties over end properties if END is
22516 ;; non-nil. Otherwise, copy end properties over `start' ones.
22517 (let ((p-alist '((:minute-start . :minute-end)
22518 (:hour-start . :hour-end)
22519 (:day-start . :day-end)
22520 (:month-start . :month-end)
22521 (:year-start . :year-end))))
22522 (dolist (p-cell p-alist)
22523 (org-element-put-property
22524 split-ts
22525 (funcall (if end 'car 'cdr) p-cell)
22526 (org-element-property
22527 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22528 ;; Eventually refresh `:raw-value'.
22529 (org-element-put-property split-ts :raw-value nil)
22530 (org-element-put-property
22531 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22533 (defun org-timestamp-translate (timestamp &optional boundary)
22534 "Apply `org-translate-time' on a TIMESTAMP object.
22535 When optional argument BOUNDARY is non-nil, it is either the
22536 symbol `start' or `end'. In this case, only translate the
22537 starting or ending part of TIMESTAMP if it is a date or time
22538 range. Otherwise, translate both parts."
22539 (if (and (not boundary)
22540 (memq (org-element-property :type timestamp)
22541 '(active-range inactive-range)))
22542 (concat
22543 (org-translate-time
22544 (org-element-property :raw-value
22545 (org-timestamp-split-range timestamp)))
22546 "--"
22547 (org-translate-time
22548 (org-element-property :raw-value
22549 (org-timestamp-split-range timestamp t))))
22550 (org-translate-time
22551 (org-element-property
22552 :raw-value
22553 (if (not boundary) timestamp
22554 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22558 ;;; Other stuff.
22560 (defun org-toggle-fixed-width-section (arg)
22561 "Toggle the fixed-width export.
22562 If there is no active region, the QUOTE keyword at the current headline is
22563 inserted or removed. When present, it causes the text between this headline
22564 and the next to be exported as fixed-width text, and unmodified.
22565 If there is an active region, this command adds or removes a colon as the
22566 first character of this line. If the first character of a line is a colon,
22567 this line is also exported in fixed-width font."
22568 (interactive "P")
22569 (let* ((cc 0)
22570 (regionp (org-region-active-p))
22571 (beg (if regionp (region-beginning) (point)))
22572 (end (if regionp (region-end)))
22573 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22574 (case-fold-search nil)
22575 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22576 off)
22577 (if regionp
22578 (save-excursion
22579 (goto-char beg)
22580 (setq cc (current-column))
22581 (beginning-of-line 1)
22582 (setq off (looking-at re))
22583 (while (> nlines 0)
22584 (setq nlines (1- nlines))
22585 (beginning-of-line 1)
22586 (cond
22587 (arg
22588 (org-move-to-column cc t)
22589 (insert ": \n")
22590 (forward-line -1))
22591 ((and off (looking-at re))
22592 (replace-match "" t t nil 1))
22593 ((not off) (org-move-to-column cc t) (insert ": ")))
22594 (forward-line 1)))
22595 (save-excursion
22596 (org-back-to-heading)
22597 (cond
22598 ((looking-at (format org-heading-keyword-regexp-format
22599 org-quote-string))
22600 (goto-char (match-end 1))
22601 (looking-at (concat " +" org-quote-string))
22602 (replace-match "" t t)
22603 (when (eolp) (insert " ")))
22604 ((looking-at org-outline-regexp)
22605 (goto-char (match-end 0))
22606 (insert org-quote-string " ")))))))
22608 (defun org-reftex-citation ()
22609 "Use reftex-citation to insert a citation into the buffer.
22610 This looks for a line like
22612 #+BIBLIOGRAPHY: foo plain option:-d
22614 and derives from it that foo.bib is the bibliography file relevant
22615 for this document. It then installs the necessary environment for RefTeX
22616 to work in this buffer and calls `reftex-citation' to insert a citation
22617 into the buffer.
22619 Export of such citations to both LaTeX and HTML is handled by the contributed
22620 package ox-bibtex by Taru Karttunen."
22621 (interactive)
22622 (let ((reftex-docstruct-symbol 'rds)
22623 (reftex-cite-format "\\cite{%l}")
22624 rds bib)
22625 (save-excursion
22626 (save-restriction
22627 (widen)
22628 (let ((case-fold-search t)
22629 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22630 (if (not (save-excursion
22631 (or (re-search-forward re nil t)
22632 (re-search-backward re nil t))))
22633 (error "No bibliography defined in file")
22634 (setq bib (concat (match-string 1) ".bib")
22635 rds (list (list 'bib bib)))))))
22636 (call-interactively 'reftex-citation)))
22638 ;;;; Functions extending outline functionality
22640 (defun org-beginning-of-line (&optional arg)
22641 "Go to the beginning of the current line. If that is invisible, continue
22642 to a visible line beginning. This makes the function of C-a more intuitive.
22643 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22644 first attempt, and only move to after the tags when the cursor is already
22645 beyond the end of the headline."
22646 (interactive "P")
22647 (let ((pos (point))
22648 (special (if (consp org-special-ctrl-a/e)
22649 (car org-special-ctrl-a/e)
22650 org-special-ctrl-a/e))
22651 refpos)
22652 (if (org-bound-and-true-p visual-line-mode)
22653 (beginning-of-visual-line 1)
22654 (beginning-of-line 1))
22655 (if (and arg (fboundp 'move-beginning-of-line))
22656 (call-interactively 'move-beginning-of-line)
22657 (if (bobp)
22659 (backward-char 1)
22660 (if (org-truely-invisible-p)
22661 (while (and (not (bobp)) (org-truely-invisible-p))
22662 (backward-char 1)
22663 (beginning-of-line 1))
22664 (forward-char 1))))
22665 (when special
22666 (cond
22667 ((and (looking-at org-complex-heading-regexp)
22668 (= (char-after (match-end 1)) ?\ ))
22669 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22670 (point-at-eol)))
22671 (goto-char
22672 (if (eq special t)
22673 (cond ((> pos refpos) refpos)
22674 ((= pos (point)) refpos)
22675 (t (point)))
22676 (cond ((> pos (point)) (point))
22677 ((not (eq last-command this-command)) (point))
22678 (t refpos)))))
22679 ((org-at-item-p)
22680 ;; Being at an item and not looking at an the item means point
22681 ;; was previously moved to beginning of a visual line, which
22682 ;; doesn't contain the item. Therefore, do nothing special,
22683 ;; just stay here.
22684 (when (looking-at org-list-full-item-re)
22685 ;; Set special position at first white space character after
22686 ;; bullet, and check-box, if any.
22687 (let ((after-bullet
22688 (let ((box (match-end 3)))
22689 (if (not box) (match-end 1)
22690 (let ((after (char-after box)))
22691 (if (and after (= after ? )) (1+ box) box))))))
22692 ;; Special case: Move point to special position when
22693 ;; currently after it or at beginning of line.
22694 (if (eq special t)
22695 (when (or (> pos after-bullet) (= (point) pos))
22696 (goto-char after-bullet))
22697 ;; Reversed case: Move point to special position when
22698 ;; point was already at beginning of line and command is
22699 ;; repeated.
22700 (when (and (= (point) pos) (eq last-command this-command))
22701 (goto-char after-bullet))))))))
22702 (org-no-warnings
22703 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22704 (setq disable-point-adjustment
22705 (or (not (invisible-p (point)))
22706 (not (invisible-p (max (point-min) (1- (point))))))))
22708 (defun org-end-of-line (&optional arg)
22709 "Go to the end of the line.
22710 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22711 tags on the first attempt, and only move to after the tags when
22712 the cursor is already beyond the end of the headline."
22713 (interactive "P")
22714 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22715 org-special-ctrl-a/e))
22716 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22717 'end-of-visual-line)
22718 ((fboundp 'move-end-of-line) 'move-end-of-line)
22719 (t 'end-of-line))))
22720 (if (or (not special) arg) (call-interactively move-fun)
22721 (let* ((element (save-excursion (beginning-of-line)
22722 (org-element-at-point)))
22723 (type (org-element-type element)))
22724 (cond
22725 ((memq type '(headline inlinetask))
22726 (let ((pos (point)))
22727 (beginning-of-line 1)
22728 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22729 (if (eq special t)
22730 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22731 (goto-char (match-beginning 1))
22732 (goto-char (match-end 0)))
22733 (if (or (< pos (match-end 0))
22734 (not (eq this-command last-command)))
22735 (goto-char (match-end 0))
22736 (goto-char (match-beginning 1))))
22737 (call-interactively move-fun))))
22738 ((org-element-property :hiddenp element)
22739 ;; If element is hidden, `move-end-of-line' would put point
22740 ;; after it. Use `end-of-line' to stay on current line.
22741 (call-interactively 'end-of-line))
22742 (t (call-interactively move-fun)))))
22743 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22744 (setq disable-point-adjustment
22745 (or (not (invisible-p (point)))
22746 (not (invisible-p (max (point-min) (1- (point))))))))
22748 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22749 (define-key org-mode-map "\C-e" 'org-end-of-line)
22751 (defun org-backward-sentence (&optional arg)
22752 "Go to beginning of sentence, or beginning of table field.
22753 This will call `backward-sentence' or `org-table-beginning-of-field',
22754 depending on context."
22755 (interactive "P")
22756 (cond
22757 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22758 (t (call-interactively 'backward-sentence))))
22760 (defun org-forward-sentence (&optional arg)
22761 "Go to end of sentence, or end of table field.
22762 This will call `forward-sentence' or `org-table-end-of-field',
22763 depending on context."
22764 (interactive "P")
22765 (cond
22766 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22767 (t (call-interactively 'forward-sentence))))
22769 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22770 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22772 (defun org-kill-line (&optional arg)
22773 "Kill line, to tags or end of line."
22774 (interactive "P")
22775 (cond
22776 ((or (not org-special-ctrl-k)
22777 (bolp)
22778 (not (org-at-heading-p)))
22779 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22780 org-ctrl-k-protect-subtree)
22781 (if (or (eq org-ctrl-k-protect-subtree 'error)
22782 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22783 (user-error "C-k aborted as it would kill a hidden subtree")))
22784 (call-interactively
22785 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22786 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22787 (kill-region (point) (match-beginning 1))
22788 (org-set-tags nil t))
22789 (t (kill-region (point) (point-at-eol)))))
22791 (define-key org-mode-map "\C-k" 'org-kill-line)
22793 (defun org-yank (&optional arg)
22794 "Yank. If the kill is a subtree, treat it specially.
22795 This command will look at the current kill and check if is a single
22796 subtree, or a series of subtrees[1]. If it passes the test, and if the
22797 cursor is at the beginning of a line or after the stars of a currently
22798 empty headline, then the yank is handled specially. How exactly depends
22799 on the value of the following variables, both set by default.
22801 org-yank-folded-subtrees
22802 When set, the subtree(s) will be folded after insertion, but only
22803 if doing so would now swallow text after the yanked text.
22805 org-yank-adjusted-subtrees
22806 When set, the subtree will be promoted or demoted in order to
22807 fit into the local outline tree structure, which means that the level
22808 will be adjusted so that it becomes the smaller one of the two
22809 *visible* surrounding headings.
22811 Any prefix to this command will cause `yank' to be called directly with
22812 no special treatment. In particular, a simple \\[universal-argument] prefix \
22813 will just
22814 plainly yank the text as it is.
22816 \[1] The test checks if the first non-white line is a heading
22817 and if there are no other headings with fewer stars."
22818 (interactive "P")
22819 (org-yank-generic 'yank arg))
22821 (defun org-yank-generic (command arg)
22822 "Perform some yank-like command.
22824 This function implements the behavior described in the `org-yank'
22825 documentation. However, it has been generalized to work for any
22826 interactive command with similar behavior."
22828 ;; pretend to be command COMMAND
22829 (setq this-command command)
22831 (if arg
22832 (call-interactively command)
22834 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22835 (and (org-kill-is-subtree-p)
22836 (or (bolp)
22837 (and (looking-at "[ \t]*$")
22838 (string-match
22839 "\\`\\*+\\'"
22840 (buffer-substring (point-at-bol) (point)))))))
22841 swallowp)
22842 (cond
22843 ((and subtreep org-yank-folded-subtrees)
22844 (let ((beg (point))
22845 end)
22846 (if (and subtreep org-yank-adjusted-subtrees)
22847 (org-paste-subtree nil nil 'for-yank)
22848 (call-interactively command))
22850 (setq end (point))
22851 (goto-char beg)
22852 (when (and (bolp) subtreep
22853 (not (setq swallowp
22854 (org-yank-folding-would-swallow-text beg end))))
22855 (org-with-limited-levels
22856 (or (looking-at org-outline-regexp)
22857 (re-search-forward org-outline-regexp-bol end t))
22858 (while (and (< (point) end) (looking-at org-outline-regexp))
22859 (hide-subtree)
22860 (org-cycle-show-empty-lines 'folded)
22861 (condition-case nil
22862 (outline-forward-same-level 1)
22863 (error (goto-char end))))))
22864 (when swallowp
22865 (message
22866 "Inserted text not folded because that would swallow text"))
22868 (goto-char end)
22869 (skip-chars-forward " \t\n\r")
22870 (beginning-of-line 1)
22871 (push-mark beg 'nomsg)))
22872 ((and subtreep org-yank-adjusted-subtrees)
22873 (let ((beg (point-at-bol)))
22874 (org-paste-subtree nil nil 'for-yank)
22875 (push-mark beg 'nomsg)))
22877 (call-interactively command))))))
22879 (defun org-yank-folding-would-swallow-text (beg end)
22880 "Would hide-subtree at BEG swallow any text after END?"
22881 (let (level)
22882 (org-with-limited-levels
22883 (save-excursion
22884 (goto-char beg)
22885 (when (or (looking-at org-outline-regexp)
22886 (re-search-forward org-outline-regexp-bol end t))
22887 (setq level (org-outline-level)))
22888 (goto-char end)
22889 (skip-chars-forward " \t\r\n\v\f")
22890 (if (or (eobp)
22891 (and (bolp) (looking-at org-outline-regexp)
22892 (<= (org-outline-level) level)))
22893 nil ; Nothing would be swallowed
22894 t))))) ; something would swallow
22896 (define-key org-mode-map "\C-y" 'org-yank)
22898 (defun org-truely-invisible-p ()
22899 "Check if point is at a character currently not visible.
22900 This version does not only check the character property, but also
22901 `visible-mode'."
22902 ;; Early versions of noutline don't have `outline-invisible-p'.
22903 (if (org-bound-and-true-p visible-mode)
22905 (outline-invisible-p)))
22907 (defun org-invisible-p2 ()
22908 "Check if point is at a character currently not visible."
22909 (save-excursion
22910 (if (and (eolp) (not (bobp))) (backward-char 1))
22911 ;; Early versions of noutline don't have `outline-invisible-p'.
22912 (outline-invisible-p)))
22914 (defun org-back-to-heading (&optional invisible-ok)
22915 "Call `outline-back-to-heading', but provide a better error message."
22916 (condition-case nil
22917 (outline-back-to-heading invisible-ok)
22918 (error (error "Before first headline at position %d in buffer %s"
22919 (point) (current-buffer)))))
22921 (defun org-before-first-heading-p ()
22922 "Before first heading?"
22923 (save-excursion
22924 (end-of-line)
22925 (null (re-search-backward org-outline-regexp-bol nil t))))
22927 (defun org-at-heading-p (&optional ignored)
22928 (outline-on-heading-p t))
22929 ;; Compatibility alias with Org versions < 7.8.03
22930 (defalias 'org-on-heading-p 'org-at-heading-p)
22932 (defun org-at-comment-p nil
22933 "Is cursor in a line starting with a # character?"
22934 (save-excursion
22935 (beginning-of-line)
22936 (looking-at "^#")))
22938 (defun org-at-drawer-p nil
22939 "Is cursor at a drawer keyword?"
22940 (save-excursion
22941 (move-beginning-of-line 1)
22942 (looking-at org-drawer-regexp)))
22944 (defun org-at-block-p nil
22945 "Is cursor at a block keyword?"
22946 (save-excursion
22947 (move-beginning-of-line 1)
22948 (looking-at org-block-regexp)))
22950 (defun org-point-at-end-of-empty-headline ()
22951 "If point is at the end of an empty headline, return t, else nil.
22952 If the heading only contains a TODO keyword, it is still still considered
22953 empty."
22954 (and (looking-at "[ \t]*$")
22955 (when org-todo-line-regexp
22956 (save-excursion
22957 (beginning-of-line 1)
22958 (let ((case-fold-search nil))
22959 (looking-at org-todo-line-regexp)
22960 (string= (match-string 3) ""))))))
22962 (defun org-at-heading-or-item-p ()
22963 (or (org-at-heading-p) (org-at-item-p)))
22965 (defun org-at-target-p ()
22966 (or (org-in-regexp org-radio-target-regexp)
22967 (org-in-regexp org-target-regexp)))
22968 ;; Compatibility alias with Org versions < 7.8.03
22969 (defalias 'org-on-target-p 'org-at-target-p)
22971 (defun org-up-heading-all (arg)
22972 "Move to the heading line of which the present line is a subheading.
22973 This function considers both visible and invisible heading lines.
22974 With argument, move up ARG levels."
22975 (if (fboundp 'outline-up-heading-all)
22976 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22977 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22979 (defun org-up-heading-safe ()
22980 "Move to the heading line of which the present line is a subheading.
22981 This version will not throw an error. It will return the level of the
22982 headline found, or nil if no higher level is found.
22984 Also, this function will be a lot faster than `outline-up-heading',
22985 because it relies on stars being the outline starters. This can really
22986 make a significant difference in outlines with very many siblings."
22987 (let (start-level re)
22988 (org-back-to-heading t)
22989 (setq start-level (funcall outline-level))
22990 (if (equal start-level 1)
22992 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22993 (if (re-search-backward re nil t)
22994 (funcall outline-level)))))
22996 (defun org-first-sibling-p ()
22997 "Is this heading the first child of its parents?"
22998 (interactive)
22999 (let ((re org-outline-regexp-bol)
23000 level l)
23001 (unless (org-at-heading-p t)
23002 (user-error "Not at a heading"))
23003 (setq level (funcall outline-level))
23004 (save-excursion
23005 (if (not (re-search-backward re nil t))
23007 (setq l (funcall outline-level))
23008 (< l level)))))
23010 (defun org-goto-sibling (&optional previous)
23011 "Goto the next sibling, even if it is invisible.
23012 When PREVIOUS is set, go to the previous sibling instead. Returns t
23013 when a sibling was found. When none is found, return nil and don't
23014 move point."
23015 (let ((fun (if previous 're-search-backward 're-search-forward))
23016 (pos (point))
23017 (re org-outline-regexp-bol)
23018 level l)
23019 (when (condition-case nil (org-back-to-heading t) (error nil))
23020 (setq level (funcall outline-level))
23021 (catch 'exit
23022 (or previous (forward-char 1))
23023 (while (funcall fun re nil t)
23024 (setq l (funcall outline-level))
23025 (when (< l level) (goto-char pos) (throw 'exit nil))
23026 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23027 (goto-char pos)
23028 nil))))
23030 (defun org-show-siblings ()
23031 "Show all siblings of the current headline."
23032 (save-excursion
23033 (while (org-goto-sibling) (org-flag-heading nil)))
23034 (save-excursion
23035 (while (org-goto-sibling 'previous)
23036 (org-flag-heading nil))))
23038 (defun org-goto-first-child ()
23039 "Goto the first child, even if it is invisible.
23040 Return t when a child was found. Otherwise don't move point and
23041 return nil."
23042 (let (level (pos (point)) (re org-outline-regexp-bol))
23043 (when (condition-case nil (org-back-to-heading t) (error nil))
23044 (setq level (outline-level))
23045 (forward-char 1)
23046 (if (and (re-search-forward re nil t) (> (outline-level) level))
23047 (progn (goto-char (match-beginning 0)) t)
23048 (goto-char pos) nil))))
23050 (defun org-show-hidden-entry ()
23051 "Show an entry where even the heading is hidden."
23052 (save-excursion
23053 (org-show-entry)))
23055 (defun org-flag-heading (flag &optional entry)
23056 "Flag the current heading. FLAG non-nil means make invisible.
23057 When ENTRY is non-nil, show the entire entry."
23058 (save-excursion
23059 (org-back-to-heading t)
23060 ;; Check if we should show the entire entry
23061 (if entry
23062 (progn
23063 (org-show-entry)
23064 (save-excursion
23065 (and (outline-next-heading)
23066 (org-flag-heading nil))))
23067 (outline-flag-region (max (point-min) (1- (point)))
23068 (save-excursion (outline-end-of-heading) (point))
23069 flag))))
23071 (defun org-get-next-sibling ()
23072 "Move to next heading of the same level, and return point.
23073 If there is no such heading, return nil.
23074 This is like outline-next-sibling, but invisible headings are ok."
23075 (let ((level (funcall outline-level)))
23076 (outline-next-heading)
23077 (while (and (not (eobp)) (> (funcall outline-level) level))
23078 (outline-next-heading))
23079 (if (or (eobp) (< (funcall outline-level) level))
23081 (point))))
23083 (defun org-get-last-sibling ()
23084 "Move to previous heading of the same level, and return point.
23085 If there is no such heading, return nil."
23086 (let ((opoint (point))
23087 (level (funcall outline-level)))
23088 (outline-previous-heading)
23089 (when (and (/= (point) opoint) (outline-on-heading-p t))
23090 (while (and (> (funcall outline-level) level)
23091 (not (bobp)))
23092 (outline-previous-heading))
23093 (if (< (funcall outline-level) level)
23095 (point)))))
23097 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23098 "Goto to the end of a subtree."
23099 ;; This contains an exact copy of the original function, but it uses
23100 ;; `org-back-to-heading', to make it work also in invisible
23101 ;; trees. And is uses an invisible-ok argument.
23102 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23103 ;; Furthermore, when used inside Org, finding the end of a large subtree
23104 ;; with many children and grandchildren etc, this can be much faster
23105 ;; than the outline version.
23106 (org-back-to-heading invisible-ok)
23107 (let ((first t)
23108 (level (funcall outline-level)))
23109 (if (and (derived-mode-p 'org-mode) (< level 1000))
23110 ;; A true heading (not a plain list item), in Org-mode
23111 ;; This means we can easily find the end by looking
23112 ;; only for the right number of stars. Using a regexp to do
23113 ;; this is so much faster than using a Lisp loop.
23114 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23115 (forward-char 1)
23116 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23117 ;; something else, do it the slow way
23118 (while (and (not (eobp))
23119 (or first (> (funcall outline-level) level)))
23120 (setq first nil)
23121 (outline-next-heading)))
23122 (unless to-heading
23123 (if (memq (preceding-char) '(?\n ?\^M))
23124 (progn
23125 ;; Go to end of line before heading
23126 (forward-char -1)
23127 (if (memq (preceding-char) '(?\n ?\^M))
23128 ;; leave blank line before heading
23129 (forward-char -1))))))
23130 (point))
23132 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23133 "Use Org version in org-mode, for dramatic speed-up."
23134 (if (derived-mode-p 'org-mode)
23135 (progn
23136 (org-end-of-subtree nil t)
23137 (unless (eobp) (backward-char 1)))
23138 ad-do-it))
23140 (defun org-end-of-meta-data-and-drawers ()
23141 "Jump to the first text after meta data and drawers in the current entry.
23142 This will move over empty lines, lines with planning time stamps,
23143 clocking lines, and drawers."
23144 (org-back-to-heading t)
23145 (let ((end (save-excursion (outline-next-heading) (point)))
23146 (re (concat "\\(" org-drawer-regexp "\\)"
23147 "\\|" "[ \t]*" org-keyword-time-regexp)))
23148 (forward-line 1)
23149 (while (re-search-forward re end t)
23150 (if (not (match-end 1))
23151 ;; empty or planning line
23152 (forward-line 1)
23153 ;; a drawer, find the end
23154 (re-search-forward "^[ \t]*:END:" end 'move)
23155 (forward-line 1)))
23156 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23157 (point)))
23159 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23160 "Move forward to the ARG'th subheading at same level as this one.
23161 Stop at the first and last subheadings of a superior heading.
23162 Normally this only looks at visible headings, but when INVISIBLE-OK is
23163 non-nil it will also look at invisible ones."
23164 (interactive "p")
23165 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23166 (if (and arg (< arg 0))
23167 (goto-char (point-min))
23168 (outline-next-heading))
23169 (org-at-heading-p)
23170 (let ((level (- (match-end 0) (match-beginning 0) 1))
23171 (f (if (and arg (< arg 0))
23172 're-search-backward
23173 're-search-forward))
23174 (count (if arg (abs arg) 1))
23175 (result (point)))
23176 (while (and (prog1 (> count 0)
23177 (forward-char (if (and arg (< arg 0)) -1 1)))
23178 (funcall f org-outline-regexp-bol nil 'move))
23179 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23180 (cond ((< l level) (setq count 0))
23181 ((and (= l level)
23182 (or invisible-ok
23183 (progn
23184 (goto-char (line-beginning-position))
23185 (not (outline-invisible-p)))))
23186 (setq count (1- count))
23187 (when (eq l level)
23188 (setq result (point)))))))
23189 (goto-char result))
23190 (beginning-of-line 1)))
23192 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23193 "Move backward to the ARG'th subheading at same level as this one.
23194 Stop at the first and last subheadings of a superior heading."
23195 (interactive "p")
23196 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23198 (defun org-next-block (arg &optional backward block-regexp)
23199 "Jump to the next block.
23200 With a prefix argument ARG, jump forward ARG many source blocks.
23201 When BACKWARD is non-nil, jump to the previous block.
23202 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23203 (interactive "p")
23204 (let ((re (or block-regexp org-block-regexp))
23205 (re-search-fn (or (and backward 're-search-backward)
23206 're-search-forward)))
23207 (if (looking-at re) (forward-char 1))
23208 (condition-case nil
23209 (funcall re-search-fn re nil nil arg)
23210 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23211 (goto-char (match-beginning 0)) (org-show-context)))
23213 (defun org-previous-block (arg &optional block-regexp)
23214 "Jump to the previous block.
23215 With a prefix argument ARG, jump backward ARG many source blocks.
23216 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23217 (interactive "p")
23218 (org-next-block arg t block-regexp))
23220 (defun org-forward-element ()
23221 "Move forward by one element.
23222 Move to the next element at the same level, when possible."
23223 (interactive)
23224 (cond ((eobp) (user-error "Cannot move further down"))
23225 ((org-with-limited-levels (org-at-heading-p))
23226 (let ((origin (point)))
23227 (goto-char (org-end-of-subtree nil t))
23228 (unless (org-with-limited-levels (org-at-heading-p))
23229 (goto-char origin)
23230 (user-error "Cannot move further down"))))
23232 (let* ((elem (org-element-at-point))
23233 (end (org-element-property :end elem))
23234 (parent (org-element-property :parent elem)))
23235 (cond ((and parent (= (org-element-property :contents-end parent) end))
23236 (goto-char (org-element-property :end parent)))
23237 ((integer-or-marker-p end) (goto-char end))
23238 (t (message "No element at point")))))))
23240 (defun org-backward-element ()
23241 "Move backward by one element.
23242 Move to the previous element at the same level, when possible."
23243 (interactive)
23244 (cond ((bobp) (user-error "Cannot move further up"))
23245 ((org-with-limited-levels (org-at-heading-p))
23246 ;; At a headline, move to the previous one, if any, or stay
23247 ;; here.
23248 (let ((origin (point)))
23249 (org-with-limited-levels (org-backward-heading-same-level 1))
23250 ;; When current headline has no sibling above, move to its
23251 ;; parent.
23252 (when (= (point) origin)
23253 (or (org-with-limited-levels (org-up-heading-safe))
23254 (progn (goto-char origin)
23255 (user-error "Cannot move further up"))))))
23257 (let* ((trail (org-element-at-point 'keep-trail))
23258 (elem (car trail))
23259 (prev-elem (nth 1 trail))
23260 (beg (org-element-property :begin elem)))
23261 (cond
23262 ;; Move to beginning of current element if point isn't
23263 ;; there already.
23264 ((null beg) (message "No element at point"))
23265 ((/= (point) beg) (goto-char beg))
23266 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23267 ((org-before-first-heading-p) (goto-char (point-min)))
23268 (t (org-back-to-heading)))))))
23270 (defun org-up-element ()
23271 "Move to upper element."
23272 (interactive)
23273 (if (org-with-limited-levels (org-at-heading-p))
23274 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23275 (let* ((elem (org-element-at-point))
23276 (parent (org-element-property :parent elem)))
23277 (if parent (goto-char (org-element-property :begin parent))
23278 (if (org-with-limited-levels (org-before-first-heading-p))
23279 (user-error "No surrounding element")
23280 (org-with-limited-levels (org-back-to-heading)))))))
23282 (defvar org-element-greater-elements)
23283 (defun org-down-element ()
23284 "Move to inner element."
23285 (interactive)
23286 (let ((element (org-element-at-point)))
23287 (cond
23288 ((memq (org-element-type element) '(plain-list table))
23289 (goto-char (org-element-property :contents-begin element))
23290 (forward-char))
23291 ((memq (org-element-type element) org-element-greater-elements)
23292 ;; If contents are hidden, first disclose them.
23293 (when (org-element-property :hiddenp element) (org-cycle))
23294 (goto-char (or (org-element-property :contents-begin element)
23295 (user-error "No content for this element"))))
23296 (t (user-error "No inner element")))))
23298 (defun org-drag-element-backward ()
23299 "Move backward element at point."
23300 (interactive)
23301 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23302 (let* ((trail (org-element-at-point 'keep-trail))
23303 (elem (car trail))
23304 (prev-elem (nth 1 trail)))
23305 ;; Error out if no previous element or previous element is
23306 ;; a parent of the current one.
23307 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23308 (user-error "Cannot drag element backward")
23309 (let ((pos (point)))
23310 (org-element-swap-A-B prev-elem elem)
23311 (goto-char (+ (org-element-property :begin prev-elem)
23312 (- pos (org-element-property :begin elem)))))))))
23314 (defun org-drag-element-forward ()
23315 "Move forward element at point."
23316 (interactive)
23317 (let* ((pos (point))
23318 (elem (org-element-at-point)))
23319 (when (= (point-max) (org-element-property :end elem))
23320 (user-error "Cannot drag element forward"))
23321 (goto-char (org-element-property :end elem))
23322 (let ((next-elem (org-element-at-point)))
23323 (when (or (org-element-nested-p elem next-elem)
23324 (and (eq (org-element-type next-elem) 'headline)
23325 (not (eq (org-element-type elem) 'headline))))
23326 (goto-char pos)
23327 (user-error "Cannot drag element forward"))
23328 ;; Compute new position of point: it's shifted by NEXT-ELEM
23329 ;; body's length (without final blanks) and by the length of
23330 ;; blanks between ELEM and NEXT-ELEM.
23331 (let ((size-next (- (save-excursion
23332 (goto-char (org-element-property :end next-elem))
23333 (skip-chars-backward " \r\t\n")
23334 (forward-line)
23335 ;; Small correction if buffer doesn't end
23336 ;; with a newline character.
23337 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23338 (org-element-property :begin next-elem)))
23339 (size-blank (- (org-element-property :end elem)
23340 (save-excursion
23341 (goto-char (org-element-property :end elem))
23342 (skip-chars-backward " \r\t\n")
23343 (forward-line)
23344 (point)))))
23345 (org-element-swap-A-B elem next-elem)
23346 (goto-char (+ pos size-next size-blank))))))
23348 (defun org-drag-line-forward (arg)
23349 "Drag the line at point ARG lines forward."
23350 (interactive "p")
23351 (dotimes (n (abs arg))
23352 (let ((c (current-column)))
23353 (if (< 0 arg)
23354 (progn
23355 (beginning-of-line 2)
23356 (transpose-lines 1)
23357 (beginning-of-line 0))
23358 (transpose-lines 1)
23359 (beginning-of-line -1))
23360 (org-move-to-column c))))
23362 (defun org-drag-line-backward (arg)
23363 "Drag the line at point ARG lines backward."
23364 (interactive "p")
23365 (org-drag-line-forward (- arg)))
23367 (defun org-mark-element ()
23368 "Put point at beginning of this element, mark at end.
23370 Interactively, if this command is repeated or (in Transient Mark
23371 mode) if the mark is active, it marks the next element after the
23372 ones already marked."
23373 (interactive)
23374 (let (deactivate-mark)
23375 (if (and (org-called-interactively-p 'any)
23376 (or (and (eq last-command this-command) (mark t))
23377 (and transient-mark-mode mark-active)))
23378 (set-mark
23379 (save-excursion
23380 (goto-char (mark))
23381 (goto-char (org-element-property :end (org-element-at-point)))))
23382 (let ((element (org-element-at-point)))
23383 (end-of-line)
23384 (push-mark (org-element-property :end element) t t)
23385 (goto-char (org-element-property :begin element))))))
23387 (defun org-narrow-to-element ()
23388 "Narrow buffer to current element."
23389 (interactive)
23390 (let ((elem (org-element-at-point)))
23391 (cond
23392 ((eq (car elem) 'headline)
23393 (narrow-to-region
23394 (org-element-property :begin elem)
23395 (org-element-property :end elem)))
23396 ((memq (car elem) org-element-greater-elements)
23397 (narrow-to-region
23398 (org-element-property :contents-begin elem)
23399 (org-element-property :contents-end elem)))
23401 (narrow-to-region
23402 (org-element-property :begin elem)
23403 (org-element-property :end elem))))))
23405 (defun org-transpose-element ()
23406 "Transpose current and previous elements, keeping blank lines between.
23407 Point is moved after both elements."
23408 (interactive)
23409 (org-skip-whitespace)
23410 (let ((end (org-element-property :end (org-element-at-point))))
23411 (org-drag-element-backward)
23412 (goto-char end)))
23414 (defun org-unindent-buffer ()
23415 "Un-indent the visible part of the buffer.
23416 Relative indentation (between items, inside blocks, etc.) isn't
23417 modified."
23418 (interactive)
23419 (unless (eq major-mode 'org-mode)
23420 (user-error "Cannot un-indent a buffer not in Org mode"))
23421 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23422 unindent-tree ; For byte-compiler.
23423 (unindent-tree
23424 (function
23425 (lambda (contents)
23426 (mapc
23427 (lambda (element)
23428 (if (memq (org-element-type element) '(headline section))
23429 (funcall unindent-tree (org-element-contents element))
23430 (save-excursion
23431 (save-restriction
23432 (narrow-to-region
23433 (org-element-property :begin element)
23434 (org-element-property :end element))
23435 (org-do-remove-indentation)))))
23436 (reverse contents))))))
23437 (funcall unindent-tree (org-element-contents parse-tree))))
23439 (defun org-show-subtree ()
23440 "Show everything after this heading at deeper levels."
23441 (interactive)
23442 (outline-flag-region
23443 (point)
23444 (save-excursion
23445 (org-end-of-subtree t t))
23446 nil))
23448 (defun org-show-entry ()
23449 "Show the body directly following this heading.
23450 Show the heading too, if it is currently invisible."
23451 (interactive)
23452 (save-excursion
23453 (condition-case nil
23454 (progn
23455 (org-back-to-heading t)
23456 (outline-flag-region
23457 (max (point-min) (1- (point)))
23458 (save-excursion
23459 (if (re-search-forward
23460 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23461 (match-beginning 1)
23462 (point-max)))
23463 nil)
23464 (org-cycle-hide-drawers 'children))
23465 (error nil))))
23467 (defun org-make-options-regexp (kwds &optional extra)
23468 "Make a regular expression for keyword lines."
23469 (concat
23470 "^#\\+\\("
23471 (mapconcat 'regexp-quote kwds "\\|")
23472 (if extra (concat "\\|" extra))
23473 "\\):[ \t]*\\(.*\\)"))
23475 ;; Make isearch reveal the necessary context
23476 (defun org-isearch-end ()
23477 "Reveal context after isearch exits."
23478 (when isearch-success ; only if search was successful
23479 (if (featurep 'xemacs)
23480 ;; Under XEmacs, the hook is run in the correct place,
23481 ;; we directly show the context.
23482 (org-show-context 'isearch)
23483 ;; In Emacs the hook runs *before* restoring the overlays.
23484 ;; So we have to use a one-time post-command-hook to do this.
23485 ;; (Emacs 22 has a special variable, see function `org-mode')
23486 (unless (and (boundp 'isearch-mode-end-hook-quit)
23487 isearch-mode-end-hook-quit)
23488 ;; Only when the isearch was not quitted.
23489 (org-add-hook 'post-command-hook 'org-isearch-post-command
23490 'append 'local)))
23491 (org-fix-ellipsis-at-bol)))
23493 (defun org-isearch-post-command ()
23494 "Remove self from hook, and show context."
23495 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23496 (org-show-context 'isearch))
23499 ;;;; Integration with and fixes for other packages
23501 ;;; Imenu support
23503 (defvar org-imenu-markers nil
23504 "All markers currently used by Imenu.")
23505 (make-variable-buffer-local 'org-imenu-markers)
23507 (defun org-imenu-new-marker (&optional pos)
23508 "Return a new marker for use by Imenu, and remember the marker."
23509 (let ((m (make-marker)))
23510 (move-marker m (or pos (point)))
23511 (push m org-imenu-markers)
23514 (defun org-imenu-get-tree ()
23515 "Produce the index for Imenu."
23516 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23517 (setq org-imenu-markers nil)
23518 (let* ((n org-imenu-depth)
23519 (re (concat "^" (org-get-limited-outline-regexp)))
23520 (subs (make-vector (1+ n) nil))
23521 (last-level 0)
23522 m level head0 head)
23523 (save-excursion
23524 (save-restriction
23525 (widen)
23526 (goto-char (point-max))
23527 (while (re-search-backward re nil t)
23528 (setq level (org-reduced-level (funcall outline-level)))
23529 (when (and (<= level n)
23530 (looking-at org-complex-heading-regexp)
23531 (setq head0 (org-match-string-no-properties 4)))
23532 (setq head (org-link-display-format head0)
23533 m (org-imenu-new-marker))
23534 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23535 (if (>= level last-level)
23536 (push (cons head m) (aref subs level))
23537 (push (cons head (aref subs (1+ level))) (aref subs level))
23538 (loop for i from (1+ level) to n do (aset subs i nil)))
23539 (setq last-level level)))))
23540 (aref subs 1)))
23542 (eval-after-load "imenu"
23543 '(progn
23544 (add-hook 'imenu-after-jump-hook
23545 (lambda ()
23546 (if (derived-mode-p 'org-mode)
23547 (org-show-context 'org-goto))))))
23549 (defun org-link-display-format (link)
23550 "Replace a link with its the description.
23551 If there is no description, use the link target."
23552 (save-match-data
23553 (if (string-match org-bracket-link-analytic-regexp link)
23554 (replace-match (if (match-end 5)
23555 (match-string 5 link)
23556 (concat (match-string 1 link)
23557 (match-string 3 link)))
23558 nil t link)
23559 link)))
23561 (defun org-toggle-link-display ()
23562 "Toggle the literal or descriptive display of links."
23563 (interactive)
23564 (if org-descriptive-links
23565 (progn (org-remove-from-invisibility-spec '(org-link))
23566 (org-restart-font-lock)
23567 (setq org-descriptive-links nil))
23568 (progn (add-to-invisibility-spec '(org-link))
23569 (org-restart-font-lock)
23570 (setq org-descriptive-links t))))
23572 ;; Speedbar support
23574 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23575 "Overlay marking the agenda restriction line in speedbar.")
23576 (overlay-put org-speedbar-restriction-lock-overlay
23577 'face 'org-agenda-restriction-lock)
23578 (overlay-put org-speedbar-restriction-lock-overlay
23579 'help-echo "Agendas are currently limited to this item.")
23580 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23582 (defun org-speedbar-set-agenda-restriction ()
23583 "Restrict future agenda commands to the location at point in speedbar.
23584 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23585 (interactive)
23586 (require 'org-agenda)
23587 (let (p m tp np dir txt)
23588 (cond
23589 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23590 'org-imenu t))
23591 (setq m (get-text-property p 'org-imenu-marker))
23592 (with-current-buffer (marker-buffer m)
23593 (goto-char m)
23594 (org-agenda-set-restriction-lock 'subtree)))
23595 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23596 'speedbar-function 'speedbar-find-file))
23597 (setq tp (previous-single-property-change
23598 (1+ p) 'speedbar-function)
23599 np (next-single-property-change
23600 tp 'speedbar-function)
23601 dir (speedbar-line-directory)
23602 txt (buffer-substring-no-properties (or tp (point-min))
23603 (or np (point-max))))
23604 (with-current-buffer (find-file-noselect
23605 (let ((default-directory dir))
23606 (expand-file-name txt)))
23607 (unless (derived-mode-p 'org-mode)
23608 (user-error "Cannot restrict to non-Org-mode file"))
23609 (org-agenda-set-restriction-lock 'file)))
23610 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23611 (move-overlay org-speedbar-restriction-lock-overlay
23612 (point-at-bol) (point-at-eol))
23613 (setq current-prefix-arg nil)
23614 (org-agenda-maybe-redo)))
23616 (defvar speedbar-file-key-map)
23617 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23618 (eval-after-load "speedbar"
23619 '(progn
23620 (speedbar-add-supported-extension ".org")
23621 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23622 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23623 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23624 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23625 (add-hook 'speedbar-visiting-tag-hook
23626 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23628 ;;; Fixes and Hacks for problems with other packages
23630 ;; Make flyspell not check words in links, to not mess up our keymap
23631 (defvar org-element-affiliated-keywords) ; From org-element.el
23632 (defvar org-element-block-name-alist) ; From org-element.el
23633 (defun org-mode-flyspell-verify ()
23634 "Don't let flyspell put overlays at active buttons, or on
23635 {todo,all-time,additional-option-like}-keywords."
23636 (require 'org-element) ; For `org-element-affiliated-keywords'
23637 (let ((pos (max (1- (point)) (point-min)))
23638 (word (thing-at-point 'word)))
23639 (and (not (get-text-property pos 'keymap))
23640 (not (get-text-property pos 'org-no-flyspell))
23641 (not (member word org-todo-keywords-1))
23642 (not (member word org-all-time-keywords))
23643 (not (member word org-options-keywords))
23644 (not (member word (mapcar 'car org-startup-options)))
23645 (not (member-ignore-case word org-element-affiliated-keywords))
23646 (not (member-ignore-case word (org-get-export-keywords)))
23647 (not (member-ignore-case
23648 word (mapcar 'car org-element-block-name-alist)))
23649 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23650 (not (org-in-src-block-p)))))
23652 (defun org-remove-flyspell-overlays-in (beg end)
23653 "Remove flyspell overlays in region."
23654 (and (org-bound-and-true-p flyspell-mode)
23655 (fboundp 'flyspell-delete-region-overlays)
23656 (flyspell-delete-region-overlays beg end))
23657 (add-text-properties beg end '(org-no-flyspell t)))
23659 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23660 (eval-after-load "bookmark"
23661 '(if (boundp 'bookmark-after-jump-hook)
23662 ;; We can use the hook
23663 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23664 ;; Hook not available, use advice
23665 (defadvice bookmark-jump (after org-make-visible activate)
23666 "Make the position visible."
23667 (org-bookmark-jump-unhide))))
23669 ;; Make sure saveplace shows the location if it was hidden
23670 (eval-after-load "saveplace"
23671 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23672 "Make the position visible."
23673 (org-bookmark-jump-unhide)))
23675 ;; Make sure ecb shows the location if it was hidden
23676 (eval-after-load "ecb"
23677 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23678 "Make hierarchy visible when jumping into location from ECB tree buffer."
23679 (if (derived-mode-p 'org-mode)
23680 (org-show-context))))
23682 (defun org-bookmark-jump-unhide ()
23683 "Unhide the current position, to show the bookmark location."
23684 (and (derived-mode-p 'org-mode)
23685 (or (outline-invisible-p)
23686 (save-excursion (goto-char (max (point-min) (1- (point))))
23687 (outline-invisible-p)))
23688 (org-show-context 'bookmark-jump)))
23690 ;; Make session.el ignore our circular variable
23691 (defvar session-globals-exclude)
23692 (eval-after-load "session"
23693 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23695 ;;;; Finish up
23697 (provide 'org)
23699 (run-hooks 'org-load-hook)
23701 ;;; org.el ends here