Revert "org.el (org-sort-entries): Allow to sort by clocking time"
[org-mode.git] / lisp / org.el
blob3c7afd20d52ac58894c41b3bd6493ca0403fd989
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2014 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-bound 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 (setq exported-file
202 (car (org-babel-tangle-file file exported-file "emacs-lisp"))))
203 (message "%s %s"
204 (if compile
205 (progn (byte-compile-file exported-file 'load)
206 "Compiled and loaded")
207 (progn (load-file exported-file) "Loaded"))
208 exported-file)))
210 (defcustom org-babel-load-languages '((emacs-lisp . t))
211 "Languages which can be evaluated in Org-mode buffers.
212 This list can be used to load support for any of the languages
213 below, note that each language will depend on a different set of
214 system executables and/or Emacs modes. When a language is
215 \"loaded\", then code blocks in that language can be evaluated
216 with `org-babel-execute-src-block' bound by default to C-c
217 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
218 be set to remove code block evaluation from the C-c C-c
219 keybinding. By default only Emacs Lisp (which has no
220 requirements) is loaded."
221 :group 'org-babel
222 :set 'org-babel-do-load-languages
223 :version "24.1"
224 :type '(alist :tag "Babel Languages"
225 :key-type
226 (choice
227 (const :tag "Awk" awk)
228 (const :tag "C" C)
229 (const :tag "R" R)
230 (const :tag "Asymptote" asymptote)
231 (const :tag "Calc" calc)
232 (const :tag "Clojure" clojure)
233 (const :tag "CSS" css)
234 (const :tag "Ditaa" ditaa)
235 (const :tag "Dot" dot)
236 (const :tag "Emacs Lisp" emacs-lisp)
237 (const :tag "Fortran" fortran)
238 (const :tag "Gnuplot" gnuplot)
239 (const :tag "Haskell" haskell)
240 (const :tag "IO" io)
241 (const :tag "Java" java)
242 (const :tag "Javascript" js)
243 (const :tag "LaTeX" latex)
244 (const :tag "Ledger" ledger)
245 (const :tag "Lilypond" lilypond)
246 (const :tag "Lisp" lisp)
247 (const :tag "Makefile" makefile)
248 (const :tag "Maxima" maxima)
249 (const :tag "Matlab" matlab)
250 (const :tag "Mscgen" mscgen)
251 (const :tag "Ocaml" ocaml)
252 (const :tag "Octave" octave)
253 (const :tag "Org" org)
254 (const :tag "Perl" perl)
255 (const :tag "Pico Lisp" picolisp)
256 (const :tag "PlantUML" plantuml)
257 (const :tag "Python" python)
258 (const :tag "Ruby" ruby)
259 (const :tag "Sass" sass)
260 (const :tag "Scala" scala)
261 (const :tag "Scheme" scheme)
262 (const :tag "Screen" screen)
263 (const :tag "Shell Script" sh)
264 (const :tag "Shen" shen)
265 (const :tag "Sql" sql)
266 (const :tag "Sqlite" sqlite))
267 :value-type (boolean :tag "Activate" :value t)))
269 ;;;; Customization variables
270 (defcustom org-clone-delete-id nil
271 "Remove ID property of clones of a subtree.
272 When non-nil, clones of a subtree don't inherit the ID property.
273 Otherwise they inherit the ID property with a new unique
274 identifier."
275 :type 'boolean
276 :version "24.1"
277 :group 'org-id)
279 ;;; Version
280 (org-check-version)
282 ;;;###autoload
283 (defun org-version (&optional here full message)
284 "Show the org-mode version in the echo area.
285 With prefix argument HERE, insert it at point.
286 When FULL is non-nil, use a verbose version string.
287 When MESSAGE is non-nil, display a message with the version."
288 (interactive "P")
289 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
290 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
291 (load-suffixes (list ".el"))
292 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
293 (org-trash (or
294 (and (fboundp 'org-release) (fboundp 'org-git-version))
295 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
296 (load-suffixes save-load-suffixes)
297 (org-version (org-release))
298 (git-version (org-git-version))
299 (version (format "Org-mode version %s (%s @ %s)"
300 org-version
301 git-version
302 (if org-install-dir
303 (if (string= org-dir org-install-dir)
304 org-install-dir
305 (concat "mixed installation! " org-install-dir " and " org-dir))
306 "org-loaddefs.el can not be found!")))
307 (version1 (if full version org-version)))
308 (if (org-called-interactively-p 'interactive)
309 (if here
310 (insert version)
311 (message version))
312 (if message (message version1))
313 version1)))
315 (defconst org-version (org-version))
317 ;;; Compatibility constants
319 ;;; The custom variables
321 (defgroup org nil
322 "Outline-based notes management and organizer."
323 :tag "Org"
324 :group 'outlines
325 :group 'calendar)
327 (defcustom org-mode-hook nil
328 "Mode hook for Org-mode, run after the mode was turned on."
329 :group 'org
330 :type 'hook)
332 (defcustom org-load-hook nil
333 "Hook that is run after org.el has been loaded."
334 :group 'org
335 :type 'hook)
337 (defcustom org-log-buffer-setup-hook nil
338 "Hook that is run after an Org log buffer is created."
339 :group 'org
340 :version "24.1"
341 :type 'hook)
343 (defvar org-modules) ; defined below
344 (defvar org-modules-loaded nil
345 "Have the modules been loaded already?")
347 (defun org-load-modules-maybe (&optional force)
348 "Load all extensions listed in `org-modules'."
349 (when (or force (not org-modules-loaded))
350 (mapc (lambda (ext)
351 (condition-case nil (require ext)
352 (error (message "Problems while trying to load feature `%s'" ext))))
353 org-modules)
354 (setq org-modules-loaded t)))
356 (defun org-set-modules (var value)
357 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
358 (set var value)
359 (when (featurep 'org)
360 (org-load-modules-maybe 'force)))
362 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
363 "Modules that should always be loaded together with org.el.
365 If a description starts with <C>, the file is not part of Emacs
366 and loading it will require that you have downloaded and properly
367 installed the Org mode distribution.
369 You can also use this system to load external packages (i.e. neither Org
370 core modules, nor modules from the CONTRIB directory). Just add symbols
371 to the end of the list. If the package is called org-xyz.el, then you need
372 to add the symbol `xyz', and the package must have a call to:
374 \(provide 'org-xyz)
376 For export specific modules, see also `org-export-backends'."
377 :group 'org
378 :set 'org-set-modules
379 :version "24.4"
380 :package-version '(Org . "8.0")
381 :type
382 '(set :greedy t
383 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
384 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
385 (const :tag " crypt: Encryption of subtrees" org-crypt)
386 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
387 (const :tag " docview: Links to doc-view buffers" org-docview)
388 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
389 (const :tag " habit: Track your consistency with habits" org-habit)
390 (const :tag " id: Global IDs for identifying entries" org-id)
391 (const :tag " info: Links to Info nodes" org-info)
392 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
393 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
394 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
395 (const :tag " mouse: Additional mouse support" org-mouse)
396 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
397 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
398 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
400 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
401 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
402 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
403 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
404 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
405 (const :tag "C collector: Collect properties into tables" org-collector)
406 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
407 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
408 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
409 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
410 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
411 (const :tag "C eval: Include command output as text" org-eval)
412 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
413 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
414 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
415 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
416 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
417 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
418 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
419 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
420 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
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.
658 If you want to control how Org exports those characters, see
659 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
660 used to be an alias for `org-export-with-sub-superscripts' in
661 Org <8.0, it is not anymore.
663 When this option is turned on, you can use TeX-like syntax for
664 sub- and superscripts within the buffer. Several characters after
665 \"_\" or \"^\" will be considered as a single item - so grouping
666 with {} is normally not needed. For example, the following things
667 will be parsed as single sub- or superscripts:
669 10^24 or 10^tau several digits will be considered 1 item.
670 10^-12 or 10^-tau a leading sign with digits or a word
671 x^2-y^3 will be read as x^2 - y^3, because items are
672 terminated by almost any nonword/nondigit char.
673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
675 Still, ambiguity is possible. So when in doubt, use {} to enclose
676 the sub/superscript. If you set this variable to the symbol `{}',
677 the braces are *required* in order to trigger interpretations as
678 sub/superscript. This can be helpful in documents that need \"_\"
679 frequently in plain text."
680 :group 'org-startup
681 :version "24.4"
682 :package-version '(Org . "8.0")
683 :type '(choice
684 (const :tag "Always interpret" t)
685 (const :tag "Only with braces" {})
686 (const :tag "Never interpret" nil)))
688 (defcustom org-startup-with-beamer-mode nil
689 "Non-nil means turn on `org-beamer-mode' on startup.
690 This can also be configured on a per-file basis by adding one of
691 the following lines anywhere in the buffer:
693 #+STARTUP: beamer"
694 :group 'org-startup
695 :version "24.1"
696 :type 'boolean)
698 (defcustom org-startup-align-all-tables nil
699 "Non-nil means align all tables when visiting a file.
700 This is useful when the column width in tables is forced with <N> cookies
701 in table fields. Such tables will look correct only after the first re-align.
702 This can also be configured on a per-file basis by adding one of
703 the following lines anywhere in the buffer:
704 #+STARTUP: align
705 #+STARTUP: noalign"
706 :group 'org-startup
707 :type 'boolean)
709 (defcustom org-startup-with-inline-images nil
710 "Non-nil means show inline images when loading a new Org file.
711 This can also be configured on a per-file basis by adding one of
712 the following lines anywhere in the buffer:
713 #+STARTUP: inlineimages
714 #+STARTUP: noinlineimages"
715 :group 'org-startup
716 :version "24.1"
717 :type 'boolean)
719 (defcustom org-startup-with-latex-preview nil
720 "Non-nil means preview LaTeX fragments when loading a new Org file.
722 This can also be configured on a per-file basis by adding one of
723 the following lines anywhere in the buffer:
724 #+STARTUP: latexpreview
725 #+STARTUP: nolatexpreview"
726 :group 'org-startup
727 :version "24.4"
728 :package-version '(Org . "8.0")
729 :type 'boolean)
731 (defcustom org-insert-mode-line-in-empty-file nil
732 "Non-nil means insert the first line setting Org-mode in empty files.
733 When the function `org-mode' is called interactively in an empty file, this
734 normally means that the file name does not automatically trigger Org-mode.
735 To ensure that the file will always be in Org-mode in the future, a
736 line enforcing Org-mode will be inserted into the buffer, if this option
737 has been set."
738 :group 'org-startup
739 :type 'boolean)
741 (defcustom org-replace-disputed-keys nil
742 "Non-nil means use alternative key bindings for some keys.
743 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
744 These keys are also used by other packages like shift-selection-mode'
745 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
746 If you want to use Org-mode together with one of these other modes,
747 or more generally if you would like to move some Org-mode commands to
748 other keys, set this variable and configure the keys with the variable
749 `org-disputed-keys'.
751 This option is only relevant at load-time of Org-mode, and must be set
752 *before* org.el is loaded. Changing it requires a restart of Emacs to
753 become effective."
754 :group 'org-startup
755 :type 'boolean)
757 (defcustom org-use-extra-keys nil
758 "Non-nil means use extra key sequence definitions for certain commands.
759 This happens automatically if you run XEmacs or if `window-system'
760 is nil. This variable lets you do the same manually. You must
761 set it before loading org.
763 Example: on Carbon Emacs 22 running graphically, with an external
764 keyboard on a Powerbook, the default way of setting M-left might
765 not work for either Alt or ESC. Setting this variable will make
766 it work for ESC."
767 :group 'org-startup
768 :type 'boolean)
770 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
772 (defcustom org-disputed-keys
773 '(([(shift up)] . [(meta p)])
774 ([(shift down)] . [(meta n)])
775 ([(shift left)] . [(meta -)])
776 ([(shift right)] . [(meta +)])
777 ([(control shift right)] . [(meta shift +)])
778 ([(control shift left)] . [(meta shift -)]))
779 "Keys for which Org-mode and other modes compete.
780 This is an alist, cars are the default keys, second element specifies
781 the alternative to use when `org-replace-disputed-keys' is t.
783 Keys can be specified in any syntax supported by `define-key'.
784 The value of this option takes effect only at Org-mode's startup,
785 therefore you'll have to restart Emacs to apply it after changing."
786 :group 'org-startup
787 :type 'alist)
789 (defun org-key (key)
790 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
791 Or return the original if not disputed.
792 Also apply the translations defined in `org-xemacs-key-equivalents'."
793 (when org-replace-disputed-keys
794 (let* ((nkey (key-description key))
795 (x (org-find-if (lambda (x)
796 (equal (key-description (car x)) nkey))
797 org-disputed-keys)))
798 (setq key (if x (cdr x) key))))
799 (when (featurep 'xemacs)
800 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
801 key)
803 (defun org-find-if (predicate seq)
804 (catch 'exit
805 (while seq
806 (if (funcall predicate (car seq))
807 (throw 'exit (car seq))
808 (pop seq)))))
810 (defun org-defkey (keymap key def)
811 "Define a key, possibly translated, as returned by `org-key'."
812 (define-key keymap (org-key key) def))
814 (defcustom org-ellipsis nil
815 "The ellipsis to use in the Org-mode outline.
816 When nil, just use the standard three dots.
817 When a string, use that string instead.
818 When a face, use the standard 3 dots, but with the specified face.
819 The change affects only Org-mode (which will then use its own display table).
820 Changing this requires executing `M-x org-mode RET' in a buffer to become
821 effective."
822 :group 'org-startup
823 :type '(choice (const :tag "Default" nil)
824 (face :tag "Face" :value org-warning)
825 (string :tag "String" :value "...#")))
827 (defvar org-display-table nil
828 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
830 (defgroup org-keywords nil
831 "Keywords in Org-mode."
832 :tag "Org Keywords"
833 :group 'org)
835 (defcustom org-deadline-string "DEADLINE:"
836 "String to mark deadline entries.
837 A deadline is this string, followed by a time stamp. Should be a word,
838 terminated by a colon. You can insert a schedule keyword and
839 a timestamp with \\[org-deadline].
840 Changes become only effective after restarting Emacs."
841 :group 'org-keywords
842 :type 'string)
844 (defcustom org-scheduled-string "SCHEDULED:"
845 "String to mark scheduled TODO entries.
846 A schedule is this string, followed by a time stamp. Should be a word,
847 terminated by a colon. You can insert a schedule keyword and
848 a timestamp with \\[org-schedule].
849 Changes become only effective after restarting Emacs."
850 :group 'org-keywords
851 :type 'string)
853 (defcustom org-closed-string "CLOSED:"
854 "String used as the prefix for timestamps logging closing a TODO entry."
855 :group 'org-keywords
856 :type 'string)
858 (defcustom org-clock-string "CLOCK:"
859 "String used as prefix for timestamps clocking work hours on an item."
860 :group 'org-keywords
861 :type 'string)
863 (defcustom org-closed-keep-when-no-todo nil
864 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
865 :group 'org-todo
866 :group 'org-keywords
867 :version "24.4"
868 :package-version '(Org . "8.0")
869 :type 'boolean)
871 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
872 org-scheduled-string "\\|"
873 org-deadline-string "\\|"
874 org-closed-string "\\|"
875 org-clock-string "\\)")
876 "Matches a line with planning or clock info.")
878 (defcustom org-comment-string "COMMENT"
879 "Entries starting with this keyword will never be exported.
880 An entry can be toggled between COMMENT and normal with
881 \\[org-toggle-comment].
882 Changes become only effective after restarting Emacs."
883 :group 'org-keywords
884 :type 'string)
886 (defcustom org-quote-string "QUOTE"
887 "Entries starting with this keyword will be exported in fixed-width font.
888 Quoting applies only to the text in the entry following the headline, and does
889 not extend beyond the next headline, even if that is lower level.
890 An entry can be toggled between QUOTE and normal with
891 \\[org-toggle-fixed-width-section]."
892 :group 'org-keywords
893 :type 'string)
895 (defconst org-repeat-re
896 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
897 "Regular expression for specifying repeated events.
898 After a match, group 1 contains the repeat expression.")
900 (defgroup org-structure nil
901 "Options concerning the general structure of Org-mode files."
902 :tag "Org Structure"
903 :group 'org)
905 (defgroup org-reveal-location nil
906 "Options about how to make context of a location visible."
907 :tag "Org Reveal Location"
908 :group 'org-structure)
910 (defconst org-context-choice
911 '(choice
912 (const :tag "Always" t)
913 (const :tag "Never" nil)
914 (repeat :greedy t :tag "Individual contexts"
915 (cons
916 (choice :tag "Context"
917 (const agenda)
918 (const org-goto)
919 (const occur-tree)
920 (const tags-tree)
921 (const link-search)
922 (const mark-goto)
923 (const bookmark-jump)
924 (const isearch)
925 (const default))
926 (boolean))))
927 "Contexts for the reveal options.")
929 (defcustom org-show-hierarchy-above '((default . t))
930 "Non-nil means show full hierarchy when revealing a location.
931 Org-mode often shows locations in an org-mode file which might have
932 been invisible before. When this is set, the hierarchy of headings
933 above the exposed location is shown.
934 Turning this off for example for sparse trees makes them very compact.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. Valid contexts are
937 agenda when exposing an entry from the agenda
938 org-goto when using the command `org-goto' on key C-c C-j
939 occur-tree when using the command `org-occur' on key C-c /
940 tags-tree when constructing a sparse tree based on tags matches
941 link-search when exposing search matches associated with a link
942 mark-goto when exposing the jump goal of a mark
943 bookmark-jump when exposing a bookmark location
944 isearch when exiting from an incremental search
945 default default for all contexts not set explicitly"
946 :group 'org-reveal-location
947 :type org-context-choice)
949 (defcustom org-show-following-heading '((default . nil))
950 "Non-nil means show following heading when revealing a location.
951 Org-mode often shows locations in an org-mode file which might have
952 been invisible before. When this is set, the heading following the
953 match is shown.
954 Turning this off for example for sparse trees makes them very compact,
955 but makes it harder to edit the location of the match. In such a case,
956 use the command \\[org-reveal] to show more context.
957 Instead of t, this can also be an alist specifying this option for different
958 contexts. See `org-show-hierarchy-above' for valid contexts."
959 :group 'org-reveal-location
960 :type org-context-choice)
962 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
963 "Non-nil means show all sibling heading when revealing a location.
964 Org-mode often shows locations in an org-mode file which might have
965 been invisible before. When this is set, the sibling of the current entry
966 heading are all made visible. If `org-show-hierarchy-above' is t,
967 the same happens on each level of the hierarchy above the current entry.
969 By default this is on for the isearch context, off for all other contexts.
970 Turning this off for example for sparse trees makes them very compact,
971 but makes it harder to edit the location of the match. In such a case,
972 use the command \\[org-reveal] to show more context.
973 Instead of t, this can also be an alist specifying this option for different
974 contexts. See `org-show-hierarchy-above' for valid contexts."
975 :group 'org-reveal-location
976 :type org-context-choice
977 :version "24.4"
978 :package-version '(Org . "8.0"))
980 (defcustom org-show-entry-below '((default . nil))
981 "Non-nil means show the entry below a headline when revealing a location.
982 Org-mode often shows locations in an org-mode file which might have
983 been invisible before. When this is set, the text below the headline that is
984 exposed is also shown.
986 By default this is off for all contexts.
987 Instead of t, this can also be an alist specifying this option for different
988 contexts. See `org-show-hierarchy-above' for valid contexts."
989 :group 'org-reveal-location
990 :type org-context-choice)
992 (defcustom org-indirect-buffer-display 'other-window
993 "How should indirect tree buffers be displayed?
994 This applies to indirect buffers created with the commands
995 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
996 Valid values are:
997 current-window Display in the current window
998 other-window Just display in another window.
999 dedicated-frame Create one new frame, and re-use it each time.
1000 new-frame Make a new frame each time. Note that in this case
1001 previously-made indirect buffers are kept, and you need to
1002 kill these buffers yourself."
1003 :group 'org-structure
1004 :group 'org-agenda-windows
1005 :type '(choice
1006 (const :tag "In current window" current-window)
1007 (const :tag "In current frame, other window" other-window)
1008 (const :tag "Each time a new frame" new-frame)
1009 (const :tag "One dedicated frame" dedicated-frame)))
1011 (defcustom org-use-speed-commands nil
1012 "Non-nil means activate single letter commands at beginning of a headline.
1013 This may also be a function to test for appropriate locations where speed
1014 commands should be active."
1015 :group 'org-structure
1016 :type '(choice
1017 (const :tag "Never" nil)
1018 (const :tag "At beginning of headline stars" t)
1019 (function)))
1021 (defcustom org-speed-commands-user nil
1022 "Alist of additional speed commands.
1023 This list will be checked before `org-speed-commands-default'
1024 when the variable `org-use-speed-commands' is non-nil
1025 and when the cursor is at the beginning of a headline.
1026 The car if each entry is a string with a single letter, which must
1027 be assigned to `self-insert-command' in the global map.
1028 The cdr is either a command to be called interactively, a function
1029 to be called, or a form to be evaluated.
1030 An entry that is just a list with a single string will be interpreted
1031 as a descriptive headline that will be added when listing the speed
1032 commands in the Help buffer using the `?' speed command."
1033 :group 'org-structure
1034 :type '(repeat :value ("k" . ignore)
1035 (choice :value ("k" . ignore)
1036 (list :tag "Descriptive Headline" (string :tag "Headline"))
1037 (cons :tag "Letter and Command"
1038 (string :tag "Command letter")
1039 (choice
1040 (function)
1041 (sexp))))))
1043 (defcustom org-bookmark-names-plist
1044 '(:last-capture "org-capture-last-stored"
1045 :last-refile "org-refile-last-stored"
1046 :last-capture-marker "org-capture-last-stored-marker")
1047 "Names for bookmarks automatically set by some Org commands.
1048 This can provide strings as names for a number of bookmarks Org sets
1049 automatically. The following keys are currently implemented:
1050 :last-capture
1051 :last-capture-marker
1052 :last-refile
1053 When a key does not show up in the property list, the corresponding bookmark
1054 is not set."
1055 :group 'org-structure
1056 :type 'plist)
1058 (defgroup org-cycle nil
1059 "Options concerning visibility cycling in Org-mode."
1060 :tag "Org Cycle"
1061 :group 'org-structure)
1063 (defcustom org-cycle-skip-children-state-if-no-children t
1064 "Non-nil means skip CHILDREN state in entries that don't have any."
1065 :group 'org-cycle
1066 :type 'boolean)
1068 (defcustom org-cycle-max-level nil
1069 "Maximum level which should still be subject to visibility cycling.
1070 Levels higher than this will, for cycling, be treated as text, not a headline.
1071 When `org-odd-levels-only' is set, a value of N in this variable actually
1072 means 2N-1 stars as the limiting headline.
1073 When nil, cycle all levels.
1074 Note that the limiting level of cycling is also influenced by
1075 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1076 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1077 than its value."
1078 :group 'org-cycle
1079 :type '(choice
1080 (const :tag "No limit" nil)
1081 (integer :tag "Maximum level")))
1083 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1084 "Names of drawers. Drawers are not opened by cycling on the headline above.
1085 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1086 this:
1087 :DRAWERNAME:
1088 .....
1089 :END:
1090 The drawer \"PROPERTIES\" is special for capturing properties through
1091 the property API.
1093 Drawers can be defined on the per-file basis with a line like:
1095 #+DRAWERS: HIDDEN STATE PROPERTIES"
1096 :group 'org-structure
1097 :group 'org-cycle
1098 :type '(repeat (string :tag "Drawer Name")))
1100 (defcustom org-hide-block-startup nil
1101 "Non-nil means entering Org-mode will fold all blocks.
1102 This can also be set in on a per-file basis with
1104 #+STARTUP: hideblocks
1105 #+STARTUP: showblocks"
1106 :group 'org-startup
1107 :group 'org-cycle
1108 :type 'boolean)
1110 (defcustom org-cycle-global-at-bob nil
1111 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1112 This makes it possible to do global cycling without having to use S-TAB or
1113 \\[universal-argument] TAB. For this special case to work, the first line
1114 of the buffer must not be a headline -- it may be empty or some other text.
1115 When used in this way, `org-cycle-hook' is disabled temporarily to make
1116 sure the cursor stays at the beginning of the buffer. When this option is
1117 nil, don't do anything special at the beginning of the buffer."
1118 :group 'org-cycle
1119 :type 'boolean)
1121 (defcustom org-cycle-level-after-item/entry-creation t
1122 "Non-nil means cycle entry level or item indentation in new empty entries.
1124 When the cursor is at the end of an empty headline, i.e., with only stars
1125 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1126 and then all possible ancestor states, before returning to the original state.
1127 This makes data entry extremely fast: M-RET to create a new headline,
1128 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1130 When the cursor is at the end of an empty plain list item, one TAB will
1131 make it a subitem, two or more tabs will back up to make this an item
1132 higher up in the item hierarchy."
1133 :group 'org-cycle
1134 :type 'boolean)
1136 (defcustom org-cycle-emulate-tab t
1137 "Where should `org-cycle' emulate TAB.
1138 nil Never
1139 white Only in completely white lines
1140 whitestart Only at the beginning of lines, before the first non-white char
1141 t Everywhere except in headlines
1142 exc-hl-bol Everywhere except at the start of a headline
1143 If TAB is used in a place where it does not emulate TAB, the current subtree
1144 visibility is cycled."
1145 :group 'org-cycle
1146 :type '(choice (const :tag "Never" nil)
1147 (const :tag "Only in completely white lines" white)
1148 (const :tag "Before first char in a line" whitestart)
1149 (const :tag "Everywhere except in headlines" t)
1150 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1152 (defcustom org-cycle-separator-lines 2
1153 "Number of empty lines needed to keep an empty line between collapsed trees.
1154 If you leave an empty line between the end of a subtree and the following
1155 headline, this empty line is hidden when the subtree is folded.
1156 Org-mode will leave (exactly) one empty line visible if the number of
1157 empty lines is equal or larger to the number given in this variable.
1158 So the default 2 means at least 2 empty lines after the end of a subtree
1159 are needed to produce free space between a collapsed subtree and the
1160 following headline.
1162 If the number is negative, and the number of empty lines is at least -N,
1163 all empty lines are shown.
1165 Special case: when 0, never leave empty lines in collapsed view."
1166 :group 'org-cycle
1167 :type 'integer)
1168 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1170 (defcustom org-pre-cycle-hook nil
1171 "Hook that is run before visibility cycling is happening.
1172 The function(s) in this hook must accept a single argument which indicates
1173 the new state that will be set right after running this hook. The
1174 argument is a symbol. Before a global state change, it can have the values
1175 `overview', `content', or `all'. Before a local state change, it can have
1176 the values `folded', `children', or `subtree'."
1177 :group 'org-cycle
1178 :type 'hook)
1180 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1181 org-cycle-hide-drawers
1182 org-cycle-hide-inline-tasks
1183 org-cycle-show-empty-lines
1184 org-optimize-window-after-visibility-change)
1185 "Hook that is run after `org-cycle' has changed the buffer visibility.
1186 The function(s) in this hook must accept a single argument which indicates
1187 the new state that was set by the most recent `org-cycle' command. The
1188 argument is a symbol. After a global state change, it can have the values
1189 `overview', `contents', or `all'. After a local state change, it can have
1190 the values `folded', `children', or `subtree'."
1191 :group 'org-cycle
1192 :type 'hook)
1194 (defgroup org-edit-structure nil
1195 "Options concerning structure editing in Org-mode."
1196 :tag "Org Edit Structure"
1197 :group 'org-structure)
1199 (defcustom org-odd-levels-only nil
1200 "Non-nil means skip even levels and only use odd levels for the outline.
1201 This has the effect that two stars are being added/taken away in
1202 promotion/demotion commands. It also influences how levels are
1203 handled by the exporters.
1204 Changing it requires restart of `font-lock-mode' to become effective
1205 for fontification also in regions already fontified.
1206 You may also set this on a per-file basis by adding one of the following
1207 lines to the buffer:
1209 #+STARTUP: odd
1210 #+STARTUP: oddeven"
1211 :group 'org-edit-structure
1212 :group 'org-appearance
1213 :type 'boolean)
1215 (defcustom org-adapt-indentation t
1216 "Non-nil means adapt indentation to outline node level.
1218 When this variable is set, Org assumes that you write outlines by
1219 indenting text in each node to align with the headline (after the stars).
1220 The following issues are influenced by this variable:
1222 - When this is set and the *entire* text in an entry is indented, the
1223 indentation is increased by one space in a demotion command, and
1224 decreased by one in a promotion command. If any line in the entry
1225 body starts with text at column 0, indentation is not changed at all.
1227 - Property drawers and planning information is inserted indented when
1228 this variable s set. When nil, they will not be indented.
1230 - TAB indents a line relative to context. The lines below a headline
1231 will be indented when this variable is set.
1233 Note that this is all about true indentation, by adding and removing
1234 space characters. See also `org-indent.el' which does level-dependent
1235 indentation in a virtual way, i.e. at display time in Emacs."
1236 :group 'org-edit-structure
1237 :type 'boolean)
1239 (defcustom org-special-ctrl-a/e nil
1240 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1242 When t, `C-a' will bring back the cursor to the beginning of the
1243 headline text, i.e. after the stars and after a possible TODO
1244 keyword. In an item, this will be the position after bullet and
1245 check-box, if any. When the cursor is already at that position,
1246 another `C-a' will bring it to the beginning of the line.
1248 `C-e' will jump to the end of the headline, ignoring the presence
1249 of tags in the headline. A second `C-e' will then jump to the
1250 true end of the line, after any tags. This also means that, when
1251 this variable is non-nil, `C-e' also will never jump beyond the
1252 end of the heading of a folded section, i.e. not after the
1253 ellipses.
1255 When set to the symbol `reversed', the first `C-a' or `C-e' works
1256 normally, going to the true line boundary first. Only a directly
1257 following, identical keypress will bring the cursor to the
1258 special positions.
1260 This may also be a cons cell where the behavior for `C-a' and
1261 `C-e' is set separately."
1262 :group 'org-edit-structure
1263 :type '(choice
1264 (const :tag "off" nil)
1265 (const :tag "on: after stars/bullet and before tags first" t)
1266 (const :tag "reversed: true line boundary first" reversed)
1267 (cons :tag "Set C-a and C-e separately"
1268 (choice :tag "Special C-a"
1269 (const :tag "off" nil)
1270 (const :tag "on: after stars/bullet first" t)
1271 (const :tag "reversed: before stars/bullet first" reversed))
1272 (choice :tag "Special C-e"
1273 (const :tag "off" nil)
1274 (const :tag "on: before tags first" t)
1275 (const :tag "reversed: after tags first" reversed)))))
1276 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1278 (defcustom org-special-ctrl-k nil
1279 "Non-nil means `C-k' will behave specially in headlines.
1280 When nil, `C-k' will call the default `kill-line' command.
1281 When t, the following will happen while the cursor is in the headline:
1283 - When the cursor is at the beginning of a headline, kill the entire
1284 line and possible the folded subtree below the line.
1285 - When in the middle of the headline text, kill the headline up to the tags.
1286 - When after the headline text, kill the tags."
1287 :group 'org-edit-structure
1288 :type 'boolean)
1290 (defcustom org-ctrl-k-protect-subtree nil
1291 "Non-nil means, do not delete a hidden subtree with C-k.
1292 When set to the symbol `error', simply throw an error when C-k is
1293 used to kill (part-of) a headline that has hidden text behind it.
1294 Any other non-nil value will result in a query to the user, if it is
1295 OK to kill that hidden subtree. When nil, kill without remorse."
1296 :group 'org-edit-structure
1297 :version "24.1"
1298 :type '(choice
1299 (const :tag "Do not protect hidden subtrees" nil)
1300 (const :tag "Protect hidden subtrees with a security query" t)
1301 (const :tag "Never kill a hidden subtree with C-k" error)))
1303 (defcustom org-special-ctrl-o t
1304 "Non-nil means, make `C-o' insert a row in tables."
1305 :group 'org-edit-structure
1306 :type 'boolean)
1308 (defcustom org-catch-invisible-edits nil
1309 "Check if in invisible region before inserting or deleting a character.
1310 Valid values are:
1312 nil Do not check, so just do invisible edits.
1313 error Throw an error and do nothing.
1314 show Make point visible, and do the requested edit.
1315 show-and-error Make point visible, then throw an error and abort the edit.
1316 smart Make point visible, and do insertion/deletion if it is
1317 adjacent to visible text and the change feels predictable.
1318 Never delete a previously invisible character or add in the
1319 middle or right after an invisible region. Basically, this
1320 allows insertion and backward-delete right before ellipses.
1321 FIXME: maybe in this case we should not even show?"
1322 :group 'org-edit-structure
1323 :version "24.1"
1324 :type '(choice
1325 (const :tag "Do not check" nil)
1326 (const :tag "Throw error when trying to edit" error)
1327 (const :tag "Unhide, but do not do the edit" show-and-error)
1328 (const :tag "Show invisible part and do the edit" show)
1329 (const :tag "Be smart and do the right thing" smart)))
1331 (defcustom org-yank-folded-subtrees t
1332 "Non-nil means when yanking subtrees, fold them.
1333 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1334 it starts with a heading and all other headings in it are either children
1335 or siblings, then fold all the subtrees. However, do this only if no
1336 text after the yank would be swallowed into a folded tree by this action."
1337 :group 'org-edit-structure
1338 :type 'boolean)
1340 (defcustom org-yank-adjusted-subtrees nil
1341 "Non-nil means when yanking subtrees, adjust the level.
1342 With this setting, `org-paste-subtree' is used to insert the subtree, see
1343 this function for details."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1347 (defcustom org-M-RET-may-split-line '((default . t))
1348 "Non-nil means M-RET will split the line at the cursor position.
1349 When nil, it will go to the end of the line before making a
1350 new line.
1351 You may also set this option in a different way for different
1352 contexts. Valid contexts are:
1354 headline when creating a new headline
1355 item when creating a new item
1356 table in a table field
1357 default the value to be used for all contexts not explicitly
1358 customized"
1359 :group 'org-structure
1360 :group 'org-table
1361 :type '(choice
1362 (const :tag "Always" t)
1363 (const :tag "Never" nil)
1364 (repeat :greedy t :tag "Individual contexts"
1365 (cons
1366 (choice :tag "Context"
1367 (const headline)
1368 (const item)
1369 (const table)
1370 (const default))
1371 (boolean)))))
1374 (defcustom org-insert-heading-respect-content nil
1375 "Non-nil means insert new headings after the current subtree.
1376 When nil, the new heading is created directly after the current line.
1377 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1378 this variable on for the duration of the command."
1379 :group 'org-structure
1380 :type 'boolean)
1382 (defcustom org-blank-before-new-entry '((heading . auto)
1383 (plain-list-item . auto))
1384 "Should `org-insert-heading' leave a blank line before new heading/item?
1385 The value is an alist, with `heading' and `plain-list-item' as CAR,
1386 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1387 which case Org will look at the surrounding headings/items and try to
1388 make an intelligent decision whether to insert a blank line or not.
1390 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1391 the setting here is ignored and no empty line is inserted to avoid breaking
1392 the list structure."
1393 :group 'org-edit-structure
1394 :type '(list
1395 (cons (const heading)
1396 (choice (const :tag "Never" nil)
1397 (const :tag "Always" t)
1398 (const :tag "Auto" auto)))
1399 (cons (const plain-list-item)
1400 (choice (const :tag "Never" nil)
1401 (const :tag "Always" t)
1402 (const :tag "Auto" auto)))))
1404 (defcustom org-insert-heading-hook nil
1405 "Hook being run after inserting a new heading."
1406 :group 'org-edit-structure
1407 :type 'hook)
1409 (defcustom org-enable-fixed-width-editor t
1410 "Non-nil means lines starting with \":\" are treated as fixed-width.
1411 This currently only means they are never auto-wrapped.
1412 When nil, such lines will be treated like ordinary lines.
1413 See also the QUOTE keyword."
1414 :group 'org-edit-structure
1415 :type 'boolean)
1417 (defcustom org-goto-auto-isearch t
1418 "Non-nil means typing characters in `org-goto' starts incremental search.
1419 When nil, you can use these keybindings to navigate the buffer:
1421 q Quit the org-goto interface
1422 n Go to the next visible heading
1423 p Go to the previous visible heading
1424 f Go one heading forward on same level
1425 b Go one heading backward on same level
1426 u Go one heading up"
1427 :group 'org-edit-structure
1428 :type 'boolean)
1430 (defgroup org-sparse-trees nil
1431 "Options concerning sparse trees in Org-mode."
1432 :tag "Org Sparse Trees"
1433 :group 'org-structure)
1435 (defcustom org-highlight-sparse-tree-matches t
1436 "Non-nil means highlight all matches that define a sparse tree.
1437 The highlights will automatically disappear the next time the buffer is
1438 changed by an edit command."
1439 :group 'org-sparse-trees
1440 :type 'boolean)
1442 (defcustom org-remove-highlights-with-change t
1443 "Non-nil means any change to the buffer will remove temporary highlights.
1444 Such highlights are created by `org-occur' and `org-clock-display'.
1445 When nil, `C-c C-c needs to be used to get rid of the highlights.
1446 The highlights created by `org-preview-latex-fragment' always need
1447 `C-c C-c' to be removed."
1448 :group 'org-sparse-trees
1449 :group 'org-time
1450 :type 'boolean)
1453 (defcustom org-occur-hook '(org-first-headline-recenter)
1454 "Hook that is run after `org-occur' has constructed a sparse tree.
1455 This can be used to recenter the window to show as much of the structure
1456 as possible."
1457 :group 'org-sparse-trees
1458 :type 'hook)
1460 (defgroup org-imenu-and-speedbar nil
1461 "Options concerning imenu and speedbar in Org-mode."
1462 :tag "Org Imenu and Speedbar"
1463 :group 'org-structure)
1465 (defcustom org-imenu-depth 2
1466 "The maximum level for Imenu access to Org-mode headlines.
1467 This also applied for speedbar access."
1468 :group 'org-imenu-and-speedbar
1469 :type 'integer)
1471 (defgroup org-table nil
1472 "Options concerning tables in Org-mode."
1473 :tag "Org Table"
1474 :group 'org)
1476 (defcustom org-enable-table-editor 'optimized
1477 "Non-nil means lines starting with \"|\" are handled by the table editor.
1478 When nil, such lines will be treated like ordinary lines.
1480 When equal to the symbol `optimized', the table editor will be optimized to
1481 do the following:
1482 - Automatic overwrite mode in front of whitespace in table fields.
1483 This makes the structure of the table stay in tact as long as the edited
1484 field does not exceed the column width.
1485 - Minimize the number of realigns. Normally, the table is aligned each time
1486 TAB or RET are pressed to move to another field. With optimization this
1487 happens only if changes to a field might have changed the column width.
1488 Optimization requires replacing the functions `self-insert-command',
1489 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1490 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1491 very good at guessing when a re-align will be necessary, but you can always
1492 force one with \\[org-ctrl-c-ctrl-c].
1494 If you would like to use the optimized version in Org-mode, but the
1495 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1497 This variable can be used to turn on and off the table editor during a session,
1498 but in order to toggle optimization, a restart is required.
1500 See also the variable `org-table-auto-blank-field'."
1501 :group 'org-table
1502 :type '(choice
1503 (const :tag "off" nil)
1504 (const :tag "on" t)
1505 (const :tag "on, optimized" optimized)))
1507 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1508 (version<= emacs-version "24.1"))
1509 "Non-nil means cluster self-insert commands for undo when possible.
1510 If this is set, then, like in the Emacs command loop, 20 consecutive
1511 characters will be undone together.
1512 This is configurable, because there is some impact on typing performance."
1513 :group 'org-table
1514 :type 'boolean)
1516 (defcustom org-table-tab-recognizes-table.el t
1517 "Non-nil means TAB will automatically notice a table.el table.
1518 When it sees such a table, it moves point into it and - if necessary -
1519 calls `table-recognize-table'."
1520 :group 'org-table-editing
1521 :type 'boolean)
1523 (defgroup org-link nil
1524 "Options concerning links in Org-mode."
1525 :tag "Org Link"
1526 :group 'org)
1528 (defvar org-link-abbrev-alist-local nil
1529 "Buffer-local version of `org-link-abbrev-alist', which see.
1530 The value of this is taken from the #+LINK lines.")
1531 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1533 (defcustom org-link-abbrev-alist nil
1534 "Alist of link abbreviations.
1535 The car of each element is a string, to be replaced at the start of a link.
1536 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1537 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1539 [[linkkey:tag][description]]
1541 The 'linkkey' must be a word word, starting with a letter, followed
1542 by letters, numbers, '-' or '_'.
1544 If REPLACE is a string, the tag will simply be appended to create the link.
1545 If the string contains \"%s\", the tag will be inserted there. If the string
1546 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1547 at that point (see the function `url-hexify-string'). If the string contains
1548 the specifier \"%(my-function)\", then the custom function `my-function' will
1549 be invoked: this function takes the tag as its only argument and must return
1550 a string.
1552 REPLACE may also be a function that will be called with the tag as the
1553 only argument to create the link, which should be returned as a string.
1555 See the manual for examples."
1556 :group 'org-link
1557 :type '(repeat
1558 (cons
1559 (string :tag "Protocol")
1560 (choice
1561 (string :tag "Format")
1562 (function)))))
1564 (defcustom org-descriptive-links t
1565 "Non-nil means Org will display descriptive links.
1566 E.g. [[http://orgmode.org][Org website]] will be displayed as
1567 \"Org Website\", hiding the link itself and just displaying its
1568 description. When set to `nil', Org will display the full links
1569 literally.
1571 You can interactively set the value of this variable by calling
1572 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1573 :group 'org-link
1574 :type 'boolean)
1576 (defcustom org-link-file-path-type 'adaptive
1577 "How the path name in file links should be stored.
1578 Valid values are:
1580 relative Relative to the current directory, i.e. the directory of the file
1581 into which the link is being inserted.
1582 absolute Absolute path, if possible with ~ for home directory.
1583 noabbrev Absolute path, no abbreviation of home directory.
1584 adaptive Use relative path for files in the current directory and sub-
1585 directories of it. For other files, use an absolute path."
1586 :group 'org-link
1587 :type '(choice
1588 (const relative)
1589 (const absolute)
1590 (const noabbrev)
1591 (const adaptive)))
1593 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1594 "Types of links that should be activated in Org-mode files.
1595 This is a list of symbols, each leading to the activation of a certain link
1596 type. In principle, it does not hurt to turn on most link types - there may
1597 be a small gain when turning off unused link types. The types are:
1599 bracket The recommended [[link][description]] or [[link]] links with hiding.
1600 angle Links in angular brackets that may contain whitespace like
1601 <bbdb:Carsten Dominik>.
1602 plain Plain links in normal text, no whitespace, like http://google.com.
1603 radio Text that is matched by a radio target, see manual for details.
1604 tag Tag settings in a headline (link to tag search).
1605 date Time stamps (link to calendar).
1606 footnote Footnote labels.
1608 Changing this variable requires a restart of Emacs to become effective."
1609 :group 'org-link
1610 :type '(set :greedy t
1611 (const :tag "Double bracket links" bracket)
1612 (const :tag "Angular bracket links" angle)
1613 (const :tag "Plain text links" plain)
1614 (const :tag "Radio target matches" radio)
1615 (const :tag "Tags" tag)
1616 (const :tag "Timestamps" date)
1617 (const :tag "Footnotes" footnote)))
1619 (defcustom org-make-link-description-function nil
1620 "Function to use for generating link descriptions from links.
1621 When nil, the link location will be used. This function must take
1622 two parameters: the first one is the link, the second one is the
1623 description generated by `org-insert-link'. The function should
1624 return the description to use."
1625 :group 'org-link
1626 :type '(choice (const nil) (function)))
1628 (defgroup org-link-store nil
1629 "Options concerning storing links in Org-mode."
1630 :tag "Org Store Link"
1631 :group 'org-link)
1633 (defcustom org-url-hexify-p t
1634 "When non-nil, hexify URL when creating a link."
1635 :type 'boolean
1636 :version "24.3"
1637 :group 'org-link-store)
1639 (defcustom org-email-link-description-format "Email %c: %.30s"
1640 "Format of the description part of a link to an email or usenet message.
1641 The following %-escapes will be replaced by corresponding information:
1643 %F full \"From\" field
1644 %f name, taken from \"From\" field, address if no name
1645 %T full \"To\" field
1646 %t first name in \"To\" field, address if no name
1647 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1648 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1649 %s subject
1650 %d date
1651 %m message-id.
1653 You may use normal field width specification between the % and the letter.
1654 This is for example useful to limit the length of the subject.
1656 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1657 :group 'org-link-store
1658 :type 'string)
1660 (defcustom org-from-is-user-regexp
1661 (let (r1 r2)
1662 (when (and user-mail-address (not (string= user-mail-address "")))
1663 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1664 (when (and user-full-name (not (string= user-full-name "")))
1665 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1666 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1667 "Regexp matched against the \"From:\" header of an email or usenet message.
1668 It should match if the message is from the user him/herself."
1669 :group 'org-link-store
1670 :type 'regexp)
1672 (defcustom org-context-in-file-links t
1673 "Non-nil means file links from `org-store-link' contain context.
1674 A search string will be added to the file name with :: as separator and
1675 used to find the context when the link is activated by the command
1676 `org-open-at-point'. When this option is t, the entire active region
1677 will be placed in the search string of the file link. If set to a
1678 positive integer, only the first n lines of context will be stored.
1680 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1681 negates this setting for the duration of the command."
1682 :group 'org-link-store
1683 :type '(choice boolean integer))
1685 (defcustom org-keep-stored-link-after-insertion nil
1686 "Non-nil means keep link in list for entire session.
1688 The command `org-store-link' adds a link pointing to the current
1689 location to an internal list. These links accumulate during a session.
1690 The command `org-insert-link' can be used to insert links into any
1691 Org-mode file (offering completion for all stored links). When this
1692 option is nil, every link which has been inserted once using \\[org-insert-link]
1693 will be removed from the list, to make completing the unused links
1694 more efficient."
1695 :group 'org-link-store
1696 :type 'boolean)
1698 (defgroup org-link-follow nil
1699 "Options concerning following links in Org-mode."
1700 :tag "Org Follow Link"
1701 :group 'org-link)
1703 (defcustom org-link-translation-function nil
1704 "Function to translate links with different syntax to Org syntax.
1705 This can be used to translate links created for example by the Planner
1706 or emacs-wiki packages to Org syntax.
1707 The function must accept two parameters, a TYPE containing the link
1708 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1709 which is everything after the link protocol. It should return a cons
1710 with possibly modified values of type and path.
1711 Org contains a function for this, so if you set this variable to
1712 `org-translate-link-from-planner', you should be able follow many
1713 links created by planner."
1714 :group 'org-link-follow
1715 :type '(choice (const nil) (function)))
1717 (defcustom org-follow-link-hook nil
1718 "Hook that is run after a link has been followed."
1719 :group 'org-link-follow
1720 :type 'hook)
1722 (defcustom org-tab-follows-link nil
1723 "Non-nil means on links TAB will follow the link.
1724 Needs to be set before org.el is loaded.
1725 This really should not be used, it does not make sense, and the
1726 implementation is bad."
1727 :group 'org-link-follow
1728 :type 'boolean)
1730 (defcustom org-return-follows-link nil
1731 "Non-nil means on links RET will follow the link.
1732 In tables, the special behavior of RET has precedence."
1733 :group 'org-link-follow
1734 :type 'boolean)
1736 (defcustom org-mouse-1-follows-link
1737 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1738 "Non-nil means mouse-1 on a link will follow the link.
1739 A longer mouse click will still set point. Does not work on XEmacs.
1740 Needs to be set before org.el is loaded."
1741 :group 'org-link-follow
1742 :version "24.4"
1743 :package-version '(Org . "8.3")
1744 :type '(choice
1745 (const :tag "A double click follows the link" double)
1746 (const :tag "Unconditionally follow the link with mouse-1" t)
1747 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1749 (defcustom org-mark-ring-length 4
1750 "Number of different positions to be recorded in the ring.
1751 Changing this requires a restart of Emacs to work correctly."
1752 :group 'org-link-follow
1753 :type 'integer)
1755 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1756 "Non-nil means internal links in Org files must exactly match a headline.
1757 When nil, the link search tries to match a phrase with all words
1758 in the search text."
1759 :group 'org-link-follow
1760 :version "24.1"
1761 :type '(choice
1762 (const :tag "Use fuzzy text search" nil)
1763 (const :tag "Match only exact headline" t)
1764 (const :tag "Match exact headline or query to create it"
1765 query-to-create)))
1767 (defcustom org-link-frame-setup
1768 '((vm . vm-visit-folder-other-frame)
1769 (vm-imap . vm-visit-imap-folder-other-frame)
1770 (gnus . org-gnus-no-new-news)
1771 (file . find-file-other-window)
1772 (wl . wl-other-frame))
1773 "Setup the frame configuration for following links.
1774 When following a link with Emacs, it may often be useful to display
1775 this link in another window or frame. This variable can be used to
1776 set this up for the different types of links.
1777 For VM, use any of
1778 `vm-visit-folder'
1779 `vm-visit-folder-other-window'
1780 `vm-visit-folder-other-frame'
1781 For Gnus, use any of
1782 `gnus'
1783 `gnus-other-frame'
1784 `org-gnus-no-new-news'
1785 For FILE, use any of
1786 `find-file'
1787 `find-file-other-window'
1788 `find-file-other-frame'
1789 For Wanderlust use any of
1790 `wl'
1791 `wl-other-frame'
1792 For the calendar, use the variable `calendar-setup'.
1793 For BBDB, it is currently only possible to display the matches in
1794 another window."
1795 :group 'org-link-follow
1796 :type '(list
1797 (cons (const vm)
1798 (choice
1799 (const vm-visit-folder)
1800 (const vm-visit-folder-other-window)
1801 (const vm-visit-folder-other-frame)))
1802 (cons (const vm-imap)
1803 (choice
1804 (const vm-visit-imap-folder)
1805 (const vm-visit-imap-folder-other-window)
1806 (const vm-visit-imap-folder-other-frame)))
1807 (cons (const gnus)
1808 (choice
1809 (const gnus)
1810 (const gnus-other-frame)
1811 (const org-gnus-no-new-news)))
1812 (cons (const file)
1813 (choice
1814 (const find-file)
1815 (const find-file-other-window)
1816 (const find-file-other-frame)))
1817 (cons (const wl)
1818 (choice
1819 (const wl)
1820 (const wl-other-frame)))))
1822 (defcustom org-display-internal-link-with-indirect-buffer nil
1823 "Non-nil means use indirect buffer to display infile links.
1824 Activating internal links (from one location in a file to another location
1825 in the same file) normally just jumps to the location. When the link is
1826 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1827 is displayed in
1828 another window. When this option is set, the other window actually displays
1829 an indirect buffer clone of the current buffer, to avoid any visibility
1830 changes to the current buffer."
1831 :group 'org-link-follow
1832 :type 'boolean)
1834 (defcustom org-open-non-existing-files nil
1835 "Non-nil means `org-open-file' will open non-existing files.
1836 When nil, an error will be generated.
1837 This variable applies only to external applications because they
1838 might choke on non-existing files. If the link is to a file that
1839 will be opened in Emacs, the variable is ignored."
1840 :group 'org-link-follow
1841 :type 'boolean)
1843 (defcustom org-open-directory-means-index-dot-org nil
1844 "Non-nil means a link to a directory really means to index.org.
1845 When nil, following a directory link will run dired or open a finder/explorer
1846 window on that directory."
1847 :group 'org-link-follow
1848 :type 'boolean)
1850 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1851 "Function and arguments to call for following mailto links.
1852 This is a list with the first element being a Lisp function, and the
1853 remaining elements being arguments to the function. In string arguments,
1854 %a will be replaced by the address, and %s will be replaced by the subject
1855 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1856 :group 'org-link-follow
1857 :type '(choice
1858 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1859 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1860 (const :tag "message-mail" (message-mail "%a" "%s"))
1861 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1863 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1864 "Non-nil means ask for confirmation before executing shell links.
1865 Shell links can be dangerous: just think about a link
1867 [[shell:rm -rf ~/*][Google Search]]
1869 This link would show up in your Org-mode document as \"Google Search\",
1870 but really it would remove your entire home directory.
1871 Therefore we advise against setting this variable to nil.
1872 Just change it to `y-or-n-p' if you want to confirm with a
1873 single keystroke rather than having to type \"yes\"."
1874 :group 'org-link-follow
1875 :type '(choice
1876 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1877 (const :tag "with y-or-n (faster)" y-or-n-p)
1878 (const :tag "no confirmation (dangerous)" nil)))
1879 (put 'org-confirm-shell-link-function
1880 'safe-local-variable
1881 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1883 (defcustom org-confirm-shell-link-not-regexp ""
1884 "A regexp to skip confirmation for shell links."
1885 :group 'org-link-follow
1886 :version "24.1"
1887 :type 'regexp)
1889 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1890 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1891 Elisp links can be dangerous: just think about a link
1893 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1895 This link would show up in your Org-mode document as \"Google Search\",
1896 but really it would remove your entire home directory.
1897 Therefore we advise against setting this variable to nil.
1898 Just change it to `y-or-n-p' if you want to confirm with a
1899 single keystroke rather than having to type \"yes\"."
1900 :group 'org-link-follow
1901 :type '(choice
1902 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1903 (const :tag "with y-or-n (faster)" y-or-n-p)
1904 (const :tag "no confirmation (dangerous)" nil)))
1905 (put 'org-confirm-shell-link-function
1906 'safe-local-variable
1907 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1909 (defcustom org-confirm-elisp-link-not-regexp ""
1910 "A regexp to skip confirmation for Elisp links."
1911 :group 'org-link-follow
1912 :version "24.1"
1913 :type 'regexp)
1915 (defconst org-file-apps-defaults-gnu
1916 '((remote . emacs)
1917 (system . mailcap)
1918 (t . mailcap))
1919 "Default file applications on a UNIX or GNU/Linux system.
1920 See `org-file-apps'.")
1922 (defconst org-file-apps-defaults-macosx
1923 '((remote . emacs)
1924 (t . "open %s")
1925 (system . "open %s")
1926 ("ps.gz" . "gv %s")
1927 ("eps.gz" . "gv %s")
1928 ("dvi" . "xdvi %s")
1929 ("fig" . "xfig %s"))
1930 "Default file applications on a MacOS X system.
1931 The system \"open\" is known as a default, but we use X11 applications
1932 for some files for which the OS does not have a good default.
1933 See `org-file-apps'.")
1935 (defconst org-file-apps-defaults-windowsnt
1936 (list
1937 '(remote . emacs)
1938 (cons t
1939 (list (if (featurep 'xemacs)
1940 'mswindows-shell-execute
1941 'w32-shell-execute)
1942 "open" 'file))
1943 (cons 'system
1944 (list (if (featurep 'xemacs)
1945 'mswindows-shell-execute
1946 'w32-shell-execute)
1947 "open" 'file)))
1948 "Default file applications on a Windows NT system.
1949 The system \"open\" is used for most files.
1950 See `org-file-apps'.")
1952 (defcustom org-file-apps
1953 '((auto-mode . emacs)
1954 ("\\.mm\\'" . default)
1955 ("\\.x?html?\\'" . default)
1956 ("\\.pdf\\'" . default))
1957 "External applications for opening `file:path' items in a document.
1958 Org-mode uses system defaults for different file types, but
1959 you can use this variable to set the application for a given file
1960 extension. The entries in this list are cons cells where the car identifies
1961 files and the cdr the corresponding command. Possible values for the
1962 file identifier are
1963 \"string\" A string as a file identifier can be interpreted in different
1964 ways, depending on its contents:
1966 - Alphanumeric characters only:
1967 Match links with this file extension.
1968 Example: (\"pdf\" . \"evince %s\")
1969 to open PDFs with evince.
1971 - Regular expression: Match links where the
1972 filename matches the regexp. If you want to
1973 use groups here, use shy groups.
1975 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1976 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1977 to open *.html and *.xhtml with firefox.
1979 - Regular expression which contains (non-shy) groups:
1980 Match links where the whole link, including \"::\", and
1981 anything after that, matches the regexp.
1982 In a custom command string, %1, %2, etc. are replaced with
1983 the parts of the link that were matched by the groups.
1984 For backwards compatibility, if a command string is given
1985 that does not use any of the group matches, this case is
1986 handled identically to the second one (i.e. match against
1987 file name only).
1988 In a custom lisp form, you can access the group matches with
1989 (match-string n link).
1991 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1992 to open [[file:document.pdf::5]] with evince at page 5.
1994 `directory' Matches a directory
1995 `remote' Matches a remote file, accessible through tramp or efs.
1996 Remote files most likely should be visited through Emacs
1997 because external applications cannot handle such paths.
1998 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1999 so all files Emacs knows how to handle. Using this with
2000 command `emacs' will open most files in Emacs. Beware that this
2001 will also open html files inside Emacs, unless you add
2002 (\"html\" . default) to the list as well.
2003 t Default for files not matched by any of the other options.
2004 `system' The system command to open files, like `open' on Windows
2005 and Mac OS X, and mailcap under GNU/Linux. This is the command
2006 that will be selected if you call `C-c C-o' with a double
2007 \\[universal-argument] \\[universal-argument] prefix.
2009 Possible values for the command are:
2010 `emacs' The file will be visited by the current Emacs process.
2011 `default' Use the default application for this file type, which is the
2012 association for t in the list, most likely in the system-specific
2013 part.
2014 This can be used to overrule an unwanted setting in the
2015 system-specific variable.
2016 `system' Use the system command for opening files, like \"open\".
2017 This command is specified by the entry whose car is `system'.
2018 Most likely, the system-specific version of this variable
2019 does define this command, but you can overrule/replace it
2020 here.
2021 string A command to be executed by a shell; %s will be replaced
2022 by the path to the file.
2023 sexp A Lisp form which will be evaluated. The file path will
2024 be available in the Lisp variable `file'.
2025 For more examples, see the system specific constants
2026 `org-file-apps-defaults-macosx'
2027 `org-file-apps-defaults-windowsnt'
2028 `org-file-apps-defaults-gnu'."
2029 :group 'org-link-follow
2030 :type '(repeat
2031 (cons (choice :value ""
2032 (string :tag "Extension")
2033 (const :tag "System command to open files" system)
2034 (const :tag "Default for unrecognized files" t)
2035 (const :tag "Remote file" remote)
2036 (const :tag "Links to a directory" directory)
2037 (const :tag "Any files that have Emacs modes"
2038 auto-mode))
2039 (choice :value ""
2040 (const :tag "Visit with Emacs" emacs)
2041 (const :tag "Use default" default)
2042 (const :tag "Use the system command" system)
2043 (string :tag "Command")
2044 (sexp :tag "Lisp form")))))
2046 (defcustom org-doi-server-url "http://dx.doi.org/"
2047 "The URL of the DOI server."
2048 :type 'string
2049 :version "24.3"
2050 :group 'org-link-follow)
2052 (defgroup org-refile nil
2053 "Options concerning refiling entries in Org-mode."
2054 :tag "Org Refile"
2055 :group 'org)
2057 (defcustom org-directory "~/org"
2058 "Directory with org files.
2059 This is just a default location to look for Org files. There is no need
2060 at all to put your files into this directory. It is only used in the
2061 following situations:
2063 1. When a capture template specifies a target file that is not an
2064 absolute path. The path will then be interpreted relative to
2065 `org-directory'
2066 2. When a capture note is filed away in an interactive way (when exiting the
2067 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2068 with `org-directory' as the default path."
2069 :group 'org-refile
2070 :group 'org-capture
2071 :type 'directory)
2073 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2074 "Default target for storing notes.
2075 Used as a fall back file for org-capture.el, for templates that
2076 do not specify a target file."
2077 :group 'org-refile
2078 :group 'org-capture
2079 :type '(choice
2080 (const :tag "Default from remember-data-file" nil)
2081 file))
2083 (defcustom org-goto-interface 'outline
2084 "The default interface to be used for `org-goto'.
2085 Allowed values are:
2086 outline The interface shows an outline of the relevant file
2087 and the correct heading is found by moving through
2088 the outline or by searching with incremental search.
2089 outline-path-completion Headlines in the current buffer are offered via
2090 completion. This is the interface also used by
2091 the refile command."
2092 :group 'org-refile
2093 :type '(choice
2094 (const :tag "Outline" outline)
2095 (const :tag "Outline-path-completion" outline-path-completion)))
2097 (defcustom org-goto-max-level 5
2098 "Maximum target level when running `org-goto' with refile interface."
2099 :group 'org-refile
2100 :type 'integer)
2102 (defcustom org-reverse-note-order nil
2103 "Non-nil means store new notes at the beginning of a file or entry.
2104 When nil, new notes will be filed to the end of a file or entry.
2105 This can also be a list with cons cells of regular expressions that
2106 are matched against file names, and values."
2107 :group 'org-capture
2108 :group 'org-refile
2109 :type '(choice
2110 (const :tag "Reverse always" t)
2111 (const :tag "Reverse never" nil)
2112 (repeat :tag "By file name regexp"
2113 (cons regexp boolean))))
2115 (defcustom org-log-refile nil
2116 "Information to record when a task is refiled.
2118 Possible values are:
2120 nil Don't add anything
2121 time Add a time stamp to the task
2122 note Prompt for a note and add it with template `org-log-note-headings'
2124 This option can also be set with on a per-file-basis with
2126 #+STARTUP: nologrefile
2127 #+STARTUP: logrefile
2128 #+STARTUP: lognoterefile
2130 You can have local logging settings for a subtree by setting the LOGGING
2131 property to one or more of these keywords.
2133 When bulk-refiling from the agenda, the value `note' is forbidden and
2134 will temporarily be changed to `time'."
2135 :group 'org-refile
2136 :group 'org-progress
2137 :version "24.1"
2138 :type '(choice
2139 (const :tag "No logging" nil)
2140 (const :tag "Record timestamp" time)
2141 (const :tag "Record timestamp with note." note)))
2143 (defcustom org-refile-targets nil
2144 "Targets for refiling entries with \\[org-refile].
2145 This is a list of cons cells. Each cell contains:
2146 - a specification of the files to be considered, either a list of files,
2147 or a symbol whose function or variable value will be used to retrieve
2148 a file name or a list of file names. If you use `org-agenda-files' for
2149 that, all agenda files will be scanned for targets. Nil means consider
2150 headings in the current buffer.
2151 - A specification of how to find candidate refile targets. This may be
2152 any of:
2153 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2154 This tag has to be present in all target headlines, inheritance will
2155 not be considered.
2156 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2157 todo keyword.
2158 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2159 headlines that are refiling targets.
2160 - a cons cell (:level . N). Any headline of level N is considered a target.
2161 Note that, when `org-odd-levels-only' is set, level corresponds to
2162 order in hierarchy, not to the number of stars.
2163 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2164 Note that, when `org-odd-levels-only' is set, level corresponds to
2165 order in hierarchy, not to the number of stars.
2167 Each element of this list generates a set of possible targets.
2168 The union of these sets is presented (with completion) to
2169 the user by `org-refile'.
2171 You can set the variable `org-refile-target-verify-function' to a function
2172 to verify each headline found by the simple criteria above.
2174 When this variable is nil, all top-level headlines in the current buffer
2175 are used, equivalent to the value `((nil . (:level . 1))'."
2176 :group 'org-refile
2177 :type '(repeat
2178 (cons
2179 (choice :value org-agenda-files
2180 (const :tag "All agenda files" org-agenda-files)
2181 (const :tag "Current buffer" nil)
2182 (function) (variable) (file))
2183 (choice :tag "Identify target headline by"
2184 (cons :tag "Specific tag" (const :value :tag) (string))
2185 (cons :tag "TODO keyword" (const :value :todo) (string))
2186 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2187 (cons :tag "Level number" (const :value :level) (integer))
2188 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2190 (defcustom org-refile-target-verify-function nil
2191 "Function to verify if the headline at point should be a refile target.
2192 The function will be called without arguments, with point at the
2193 beginning of the headline. It should return t and leave point
2194 where it is if the headline is a valid target for refiling.
2196 If the target should not be selected, the function must return nil.
2197 In addition to this, it may move point to a place from where the search
2198 should be continued. For example, the function may decide that the entire
2199 subtree of the current entry should be excluded and move point to the end
2200 of the subtree."
2201 :group 'org-refile
2202 :type '(choice
2203 (const nil)
2204 (function)))
2206 (defcustom org-refile-use-cache nil
2207 "Non-nil means cache refile targets to speed up the process.
2208 The cache for a particular file will be updated automatically when
2209 the buffer has been killed, or when any of the marker used for flagging
2210 refile targets no longer points at a live buffer.
2211 If you have added new entries to a buffer that might themselves be targets,
2212 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2213 find that easier, `C-u C-u C-u C-c C-w'."
2214 :group 'org-refile
2215 :version "24.1"
2216 :type 'boolean)
2218 (defcustom org-refile-use-outline-path nil
2219 "Non-nil means provide refile targets as paths.
2220 So a level 3 headline will be available as level1/level2/level3.
2222 When the value is `file', also include the file name (without directory)
2223 into the path. In this case, you can also stop the completion after
2224 the file name, to get entries inserted as top level in the file.
2226 When `full-file-path', include the full file path."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Not" nil)
2230 (const :tag "Yes" t)
2231 (const :tag "Start with file name" file)
2232 (const :tag "Start with full file path" full-file-path)))
2234 (defcustom org-outline-path-complete-in-steps t
2235 "Non-nil means complete the outline path in hierarchical steps.
2236 When Org-mode uses the refile interface to select an outline path
2237 \(see variable `org-refile-use-outline-path'), the completion of
2238 the path can be done is a single go, or if can be done in steps down
2239 the headline hierarchy. Going in steps is probably the best if you
2240 do not use a special completion package like `ido' or `icicles'.
2241 However, when using these packages, going in one step can be very
2242 fast, while still showing the whole path to the entry."
2243 :group 'org-refile
2244 :type 'boolean)
2246 (defcustom org-refile-allow-creating-parent-nodes nil
2247 "Non-nil means allow to create new nodes as refile targets.
2248 New nodes are then created by adding \"/new node name\" to the completion
2249 of an existing node. When the value of this variable is `confirm',
2250 new node creation must be confirmed by the user (recommended).
2251 When nil, the completion must match an existing entry.
2253 Note that, if the new heading is not seen by the criteria
2254 listed in `org-refile-targets', multiple instances of the same
2255 heading would be created by trying again to file under the new
2256 heading."
2257 :group 'org-refile
2258 :type '(choice
2259 (const :tag "Never" nil)
2260 (const :tag "Always" t)
2261 (const :tag "Prompt for confirmation" confirm)))
2263 (defcustom org-refile-active-region-within-subtree nil
2264 "Non-nil means also refile active region within a subtree.
2266 By default `org-refile' doesn't allow refiling regions if they
2267 don't contain a set of subtrees, but it might be convenient to
2268 do so sometimes: in that case, the first line of the region is
2269 converted to a headline before refiling."
2270 :group 'org-refile
2271 :version "24.1"
2272 :type 'boolean)
2274 (defgroup org-todo nil
2275 "Options concerning TODO items in Org-mode."
2276 :tag "Org TODO"
2277 :group 'org)
2279 (defgroup org-progress nil
2280 "Options concerning Progress logging in Org-mode."
2281 :tag "Org Progress"
2282 :group 'org-time)
2284 (defvar org-todo-interpretation-widgets
2285 '((:tag "Sequence (cycling hits every state)" sequence)
2286 (:tag "Type (cycling directly to DONE)" type))
2287 "The available interpretation symbols for customizing `org-todo-keywords'.
2288 Interested libraries should add to this list.")
2290 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2291 "List of TODO entry keyword sequences and their interpretation.
2292 \\<org-mode-map>This is a list of sequences.
2294 Each sequence starts with a symbol, either `sequence' or `type',
2295 indicating if the keywords should be interpreted as a sequence of
2296 action steps, or as different types of TODO items. The first
2297 keywords are states requiring action - these states will select a headline
2298 for inclusion into the global TODO list Org-mode produces. If one of
2299 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2300 signify that no further action is necessary. If \"|\" is not found,
2301 the last keyword is treated as the only DONE state of the sequence.
2303 The command \\[org-todo] cycles an entry through these states, and one
2304 additional state where no keyword is present. For details about this
2305 cycling, see the manual.
2307 TODO keywords and interpretation can also be set on a per-file basis with
2308 the special #+SEQ_TODO and #+TYP_TODO lines.
2310 Each keyword can optionally specify a character for fast state selection
2311 \(in combination with the variable `org-use-fast-todo-selection')
2312 and specifiers for state change logging, using the same syntax that
2313 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2314 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2315 indicates to record a time stamp each time this state is selected.
2317 Each keyword may also specify if a timestamp or a note should be
2318 recorded when entering or leaving the state, by adding additional
2319 characters in the parenthesis after the keyword. This looks like this:
2320 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2321 record only the time of the state change. With X and Y being either
2322 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2323 Y when leaving the state if and only if the *target* state does not
2324 define X. You may omit any of the fast-selection key or X or /Y,
2325 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2327 For backward compatibility, this variable may also be just a list
2328 of keywords. In this case the interpretation (sequence or type) will be
2329 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2330 :group 'org-todo
2331 :group 'org-keywords
2332 :type '(choice
2333 (repeat :tag "Old syntax, just keywords"
2334 (string :tag "Keyword"))
2335 (repeat :tag "New syntax"
2336 (cons
2337 (choice
2338 :tag "Interpretation"
2339 ;;Quick and dirty way to see
2340 ;;`org-todo-interpretations'. This takes the
2341 ;;place of item arguments
2342 :convert-widget
2343 (lambda (widget)
2344 (widget-put widget
2345 :args (mapcar
2346 #'(lambda (x)
2347 (widget-convert
2348 (cons 'const x)))
2349 org-todo-interpretation-widgets))
2350 widget))
2351 (repeat
2352 (string :tag "Keyword"))))))
2354 (defvar org-todo-keywords-1 nil
2355 "All TODO and DONE keywords active in a buffer.")
2356 (make-variable-buffer-local 'org-todo-keywords-1)
2357 (defvar org-todo-keywords-for-agenda nil)
2358 (defvar org-done-keywords-for-agenda nil)
2359 (defvar org-drawers-for-agenda nil)
2360 (defvar org-todo-keyword-alist-for-agenda nil)
2361 (defvar org-tag-alist-for-agenda nil
2362 "Alist of all tags from all agenda files.")
2363 (defvar org-tag-groups-alist-for-agenda nil
2364 "Alist of all groups tags from all current agenda files.")
2365 (defvar org-tag-groups-alist nil)
2366 (make-variable-buffer-local 'org-tag-groups-alist)
2367 (defvar org-agenda-contributing-files nil)
2368 (defvar org-not-done-keywords nil)
2369 (make-variable-buffer-local 'org-not-done-keywords)
2370 (defvar org-done-keywords nil)
2371 (make-variable-buffer-local 'org-done-keywords)
2372 (defvar org-todo-heads nil)
2373 (make-variable-buffer-local 'org-todo-heads)
2374 (defvar org-todo-sets nil)
2375 (make-variable-buffer-local 'org-todo-sets)
2376 (defvar org-todo-log-states nil)
2377 (make-variable-buffer-local 'org-todo-log-states)
2378 (defvar org-todo-kwd-alist nil)
2379 (make-variable-buffer-local 'org-todo-kwd-alist)
2380 (defvar org-todo-key-alist nil)
2381 (make-variable-buffer-local 'org-todo-key-alist)
2382 (defvar org-todo-key-trigger nil)
2383 (make-variable-buffer-local 'org-todo-key-trigger)
2385 (defcustom org-todo-interpretation 'sequence
2386 "Controls how TODO keywords are interpreted.
2387 This variable is in principle obsolete and is only used for
2388 backward compatibility, if the interpretation of todo keywords is
2389 not given already in `org-todo-keywords'. See that variable for
2390 more information."
2391 :group 'org-todo
2392 :group 'org-keywords
2393 :type '(choice (const sequence)
2394 (const type)))
2396 (defcustom org-use-fast-todo-selection t
2397 "Non-nil means use the fast todo selection scheme with C-c C-t.
2398 This variable describes if and under what circumstances the cycling
2399 mechanism for TODO keywords will be replaced by a single-key, direct
2400 selection scheme.
2402 When nil, fast selection is never used.
2404 When the symbol `prefix', it will be used when `org-todo' is called
2405 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2406 `C-u t' in an agenda buffer.
2408 When t, fast selection is used by default. In this case, the prefix
2409 argument forces cycling instead.
2411 In all cases, the special interface is only used if access keys have
2412 actually been assigned by the user, i.e. if keywords in the configuration
2413 are followed by a letter in parenthesis, like TODO(t)."
2414 :group 'org-todo
2415 :type '(choice
2416 (const :tag "Never" nil)
2417 (const :tag "By default" t)
2418 (const :tag "Only with C-u C-c C-t" prefix)))
2420 (defcustom org-provide-todo-statistics t
2421 "Non-nil means update todo statistics after insert and toggle.
2422 ALL-HEADLINES means update todo statistics by including headlines
2423 with no TODO keyword as well, counting them as not done.
2424 A list of TODO keywords means the same, but skip keywords that are
2425 not in this list.
2427 When this is set, todo statistics is updated in the parent of the
2428 current entry each time a todo state is changed."
2429 :group 'org-todo
2430 :type '(choice
2431 (const :tag "Yes, only for TODO entries" t)
2432 (const :tag "Yes, including all entries" all-headlines)
2433 (repeat :tag "Yes, for TODOs in this list"
2434 (string :tag "TODO keyword"))
2435 (other :tag "No TODO statistics" nil)))
2437 (defcustom org-hierarchical-todo-statistics t
2438 "Non-nil means TODO statistics covers just direct children.
2439 When nil, all entries in the subtree are considered.
2440 This has only an effect if `org-provide-todo-statistics' is set.
2441 To set this to nil for only a single subtree, use a COOKIE_DATA
2442 property and include the word \"recursive\" into the value."
2443 :group 'org-todo
2444 :type 'boolean)
2446 (defcustom org-after-todo-state-change-hook nil
2447 "Hook which is run after the state of a TODO item was changed.
2448 The new state (a string with a TODO keyword, or nil) is available in the
2449 Lisp variable `org-state'."
2450 :group 'org-todo
2451 :type 'hook)
2453 (defvar org-blocker-hook nil
2454 "Hook for functions that are allowed to block a state change.
2456 Functions in this hook should not modify the buffer.
2457 Each function gets as its single argument a property list,
2458 see `org-trigger-hook' for more information about this list.
2460 If any of the functions in this hook returns nil, the state change
2461 is blocked.")
2463 (defvar org-trigger-hook nil
2464 "Hook for functions that are triggered by a state change.
2466 Each function gets as its single argument a property list with at
2467 least the following elements:
2469 (:type type-of-change :position pos-at-entry-start
2470 :from old-state :to new-state)
2472 Depending on the type, more properties may be present.
2474 This mechanism is currently implemented for:
2476 TODO state changes
2477 ------------------
2478 :type todo-state-change
2479 :from previous state (keyword as a string), or nil, or a symbol
2480 'todo' or 'done', to indicate the general type of state.
2481 :to new state, like in :from")
2483 (defcustom org-enforce-todo-dependencies nil
2484 "Non-nil means undone TODO entries will block switching the parent to DONE.
2485 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2486 be blocked if any prior sibling is not yet done.
2487 Finally, if the parent is blocked because of ordered siblings of its own,
2488 the child will also be blocked."
2489 :set (lambda (var val)
2490 (set var val)
2491 (if val
2492 (add-hook 'org-blocker-hook
2493 'org-block-todo-from-children-or-siblings-or-parent)
2494 (remove-hook 'org-blocker-hook
2495 'org-block-todo-from-children-or-siblings-or-parent)))
2496 :group 'org-todo
2497 :type 'boolean)
2499 (defcustom org-enforce-todo-checkbox-dependencies nil
2500 "Non-nil means unchecked boxes will block switching the parent to DONE.
2501 When this is nil, checkboxes have no influence on switching TODO states.
2502 When non-nil, you first need to check off all check boxes before the TODO
2503 entry can be switched to DONE.
2504 This variable needs to be set before org.el is loaded, and you need to
2505 restart Emacs after a change to make the change effective. The only way
2506 to change is while Emacs is running is through the customize interface."
2507 :set (lambda (var val)
2508 (set var val)
2509 (if val
2510 (add-hook 'org-blocker-hook
2511 'org-block-todo-from-checkboxes)
2512 (remove-hook 'org-blocker-hook
2513 'org-block-todo-from-checkboxes)))
2514 :group 'org-todo
2515 :type 'boolean)
2517 (defcustom org-treat-insert-todo-heading-as-state-change nil
2518 "Non-nil means inserting a TODO heading is treated as state change.
2519 So when the command \\[org-insert-todo-heading] is used, state change
2520 logging will apply if appropriate. When nil, the new TODO item will
2521 be inserted directly, and no logging will take place."
2522 :group 'org-todo
2523 :type 'boolean)
2525 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2526 "Non-nil means switching TODO states with S-cursor counts as state change.
2527 This is the default behavior. However, setting this to nil allows a
2528 convenient way to select a TODO state and bypass any logging associated
2529 with that."
2530 :group 'org-todo
2531 :type 'boolean)
2533 (defcustom org-todo-state-tags-triggers nil
2534 "Tag changes that should be triggered by TODO state changes.
2535 This is a list. Each entry is
2537 (state-change (tag . flag) .......)
2539 State-change can be a string with a state, and empty string to indicate the
2540 state that has no TODO keyword, or it can be one of the symbols `todo'
2541 or `done', meaning any not-done or done state, respectively."
2542 :group 'org-todo
2543 :group 'org-tags
2544 :type '(repeat
2545 (cons (choice :tag "When changing to"
2546 (const :tag "Not-done state" todo)
2547 (const :tag "Done state" done)
2548 (string :tag "State"))
2549 (repeat
2550 (cons :tag "Tag action"
2551 (string :tag "Tag")
2552 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2554 (defcustom org-log-done nil
2555 "Information to record when a task moves to the DONE state.
2557 Possible values are:
2559 nil Don't add anything, just change the keyword
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologdone
2566 #+STARTUP: logdone
2567 #+STARTUP: lognotedone
2569 You can have local logging settings for a subtree by setting the LOGGING
2570 property to one or more of these keywords."
2571 :group 'org-todo
2572 :group 'org-progress
2573 :type '(choice
2574 (const :tag "No logging" nil)
2575 (const :tag "Record CLOSED timestamp" time)
2576 (const :tag "Record CLOSED timestamp with note." note)))
2578 ;; Normalize old uses of org-log-done.
2579 (cond
2580 ((eq org-log-done t) (setq org-log-done 'time))
2581 ((and (listp org-log-done) (memq 'done org-log-done))
2582 (setq org-log-done 'note)))
2584 (defcustom org-log-reschedule nil
2585 "Information to record when the scheduling date of a tasks is modified.
2587 Possible values are:
2589 nil Don't add anything, just change the date
2590 time Add a time stamp to the task
2591 note Prompt for a note and add it with template `org-log-note-headings'
2593 This option can also be set with on a per-file-basis with
2595 #+STARTUP: nologreschedule
2596 #+STARTUP: logreschedule
2597 #+STARTUP: lognotereschedule"
2598 :group 'org-todo
2599 :group 'org-progress
2600 :type '(choice
2601 (const :tag "No logging" nil)
2602 (const :tag "Record timestamp" time)
2603 (const :tag "Record timestamp with note." note)))
2605 (defcustom org-log-redeadline nil
2606 "Information to record when the deadline date of a tasks is modified.
2608 Possible values are:
2610 nil Don't add anything, just change the date
2611 time Add a time stamp to the task
2612 note Prompt for a note and add it with template `org-log-note-headings'
2614 This option can also be set with on a per-file-basis with
2616 #+STARTUP: nologredeadline
2617 #+STARTUP: logredeadline
2618 #+STARTUP: lognoteredeadline
2620 You can have local logging settings for a subtree by setting the LOGGING
2621 property to one or more of these keywords."
2622 :group 'org-todo
2623 :group 'org-progress
2624 :type '(choice
2625 (const :tag "No logging" nil)
2626 (const :tag "Record timestamp" time)
2627 (const :tag "Record timestamp with note." note)))
2629 (defcustom org-log-note-clock-out nil
2630 "Non-nil means record a note when clocking out of an item.
2631 This can also be configured on a per-file basis by adding one of
2632 the following lines anywhere in the buffer:
2634 #+STARTUP: lognoteclock-out
2635 #+STARTUP: nolognoteclock-out"
2636 :group 'org-todo
2637 :group 'org-progress
2638 :type 'boolean)
2640 (defcustom org-log-done-with-time t
2641 "Non-nil means the CLOSED time stamp will contain date and time.
2642 When nil, only the date will be recorded."
2643 :group 'org-progress
2644 :type 'boolean)
2646 (defcustom org-log-note-headings
2647 '((done . "CLOSING NOTE %t")
2648 (state . "State %-12s from %-12S %t")
2649 (note . "Note taken on %t")
2650 (reschedule . "Rescheduled from %S on %t")
2651 (delschedule . "Not scheduled, was %S on %t")
2652 (redeadline . "New deadline from %S on %t")
2653 (deldeadline . "Removed deadline, was %S on %t")
2654 (refile . "Refiled on %t")
2655 (clock-out . ""))
2656 "Headings for notes added to entries.
2657 The value is an alist, with the car being a symbol indicating the note
2658 context, and the cdr is the heading to be used. The heading may also be the
2659 empty string.
2660 %t in the heading will be replaced by a time stamp.
2661 %T will be an active time stamp instead the default inactive one
2662 %d will be replaced by a short-format time stamp.
2663 %D will be replaced by an active short-format time stamp.
2664 %s will be replaced by the new TODO state, in double quotes.
2665 %S will be replaced by the old TODO state, in double quotes.
2666 %u will be replaced by the user name.
2667 %U will be replaced by the full user name.
2669 In fact, it is not a good idea to change the `state' entry, because
2670 agenda log mode depends on the format of these entries."
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type '(list :greedy t
2674 (cons (const :tag "Heading when closing an item" done) string)
2675 (cons (const :tag
2676 "Heading when changing todo state (todo sequence only)"
2677 state) string)
2678 (cons (const :tag "Heading when just taking a note" note) string)
2679 (cons (const :tag "Heading when rescheduling" reschedule) string)
2680 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2681 (cons (const :tag "Heading when changing deadline" redeadline) string)
2682 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2683 (cons (const :tag "Heading when refiling" refile) string)
2684 (cons (const :tag "Heading when clocking out" clock-out) string)))
2686 (unless (assq 'note org-log-note-headings)
2687 (push '(note . "%t") org-log-note-headings))
2689 (defcustom org-log-into-drawer nil
2690 "Non-nil means insert state change notes and time stamps into a drawer.
2691 When nil, state changes notes will be inserted after the headline and
2692 any scheduling and clock lines, but not inside a drawer.
2694 The value of this variable should be the name of the drawer to use.
2695 LOGBOOK is proposed as the default drawer for this purpose, you can
2696 also set this to a string to define the drawer of your choice.
2698 A value of t is also allowed, representing \"LOGBOOK\".
2700 A value of t or nil can also be set with on a per-file-basis with
2702 #+STARTUP: logdrawer
2703 #+STARTUP: nologdrawer
2705 If this variable is set, `org-log-state-notes-insert-after-drawers'
2706 will be ignored.
2708 You can set the property LOG_INTO_DRAWER to overrule this setting for
2709 a subtree."
2710 :group 'org-todo
2711 :group 'org-progress
2712 :type '(choice
2713 (const :tag "Not into a drawer" nil)
2714 (const :tag "LOGBOOK" t)
2715 (string :tag "Other")))
2717 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2719 (defun org-log-into-drawer ()
2720 "Return the value of `org-log-into-drawer', but let properties overrule.
2721 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2722 used instead of the default value."
2723 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2724 (cond
2725 ((not p) org-log-into-drawer)
2726 ((equal p "nil") nil)
2727 ((equal p "t") "LOGBOOK")
2728 (t p))))
2730 (defcustom org-log-state-notes-insert-after-drawers nil
2731 "Non-nil means insert state change notes after any drawers in entry.
2732 Only the drawers that *immediately* follow the headline and the
2733 deadline/scheduled line are skipped.
2734 When nil, insert notes right after the heading and perhaps the line
2735 with deadline/scheduling if present.
2737 This variable will have no effect if `org-log-into-drawer' is
2738 set."
2739 :group 'org-todo
2740 :group 'org-progress
2741 :type 'boolean)
2743 (defcustom org-log-states-order-reversed t
2744 "Non-nil means the latest state note will be directly after heading.
2745 When nil, the state change notes will be ordered according to time.
2747 This option can also be set with on a per-file-basis with
2749 #+STARTUP: logstatesreversed
2750 #+STARTUP: nologstatesreversed"
2751 :group 'org-todo
2752 :group 'org-progress
2753 :type 'boolean)
2755 (defcustom org-todo-repeat-to-state nil
2756 "The TODO state to which a repeater should return the repeating task.
2757 By default this is the first task in a TODO sequence, or the previous state
2758 in a TODO_TYP set. But you can specify another task here.
2759 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2760 :group 'org-todo
2761 :version "24.1"
2762 :type '(choice (const :tag "Head of sequence" nil)
2763 (string :tag "Specific state")))
2765 (defcustom org-log-repeat 'time
2766 "Non-nil means record moving through the DONE state when triggering repeat.
2767 An auto-repeating task is immediately switched back to TODO when
2768 marked DONE. If you are not logging state changes (by adding \"@\"
2769 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2770 record a closing note, there will be no record of the task moving
2771 through DONE. This variable forces taking a note anyway.
2773 nil Don't force a record
2774 time Record a time stamp
2775 note Prompt for a note and add it with template `org-log-note-headings'
2777 This option can also be set with on a per-file-basis with
2779 #+STARTUP: nologrepeat
2780 #+STARTUP: logrepeat
2781 #+STARTUP: lognoterepeat
2783 You can have local logging settings for a subtree by setting the LOGGING
2784 property to one or more of these keywords."
2785 :group 'org-todo
2786 :group 'org-progress
2787 :type '(choice
2788 (const :tag "Don't force a record" nil)
2789 (const :tag "Force recording the DONE state" time)
2790 (const :tag "Force recording a note with the DONE state" note)))
2793 (defgroup org-priorities nil
2794 "Priorities in Org-mode."
2795 :tag "Org Priorities"
2796 :group 'org-todo)
2798 (defcustom org-enable-priority-commands t
2799 "Non-nil means priority commands are active.
2800 When nil, these commands will be disabled, so that you never accidentally
2801 set a priority."
2802 :group 'org-priorities
2803 :type 'boolean)
2805 (defcustom org-highest-priority ?A
2806 "The highest priority of TODO items. A character like ?A, ?B etc.
2807 Must have a smaller ASCII number than `org-lowest-priority'."
2808 :group 'org-priorities
2809 :type 'character)
2811 (defcustom org-lowest-priority ?C
2812 "The lowest priority of TODO items. A character like ?A, ?B etc.
2813 Must have a larger ASCII number than `org-highest-priority'."
2814 :group 'org-priorities
2815 :type 'character)
2817 (defcustom org-default-priority ?B
2818 "The default priority of TODO items.
2819 This is the priority an item gets if no explicit priority is given.
2820 When starting to cycle on an empty priority the first step in the cycle
2821 depends on `org-priority-start-cycle-with-default'. The resulting first
2822 step priority must not exceed the range from `org-highest-priority' to
2823 `org-lowest-priority' which means that `org-default-priority' has to be
2824 in this range exclusive or inclusive the range boundaries. Else the
2825 first step refuses to set the default and the second will fall back
2826 to (depending on the command used) the highest or lowest priority."
2827 :group 'org-priorities
2828 :type 'character)
2830 (defcustom org-priority-start-cycle-with-default t
2831 "Non-nil means start with default priority when starting to cycle.
2832 When this is nil, the first step in the cycle will be (depending on the
2833 command used) one higher or lower than the default priority.
2834 See also `org-default-priority'."
2835 :group 'org-priorities
2836 :type 'boolean)
2838 (defcustom org-get-priority-function nil
2839 "Function to extract the priority from a string.
2840 The string is normally the headline. If this is nil Org computes the
2841 priority from the priority cookie like [#A] in the headline. It returns
2842 an integer, increasing by 1000 for each priority level.
2843 The user can set a different function here, which should take a string
2844 as an argument and return the numeric priority."
2845 :group 'org-priorities
2846 :version "24.1"
2847 :type '(choice
2848 (const nil)
2849 (function)))
2851 (defgroup org-time nil
2852 "Options concerning time stamps and deadlines in Org-mode."
2853 :tag "Org Time"
2854 :group 'org)
2856 (defcustom org-insert-labeled-timestamps-at-point nil
2857 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2858 When nil, these labeled time stamps are forces into the second line of an
2859 entry, just after the headline. When scheduling from the global TODO list,
2860 the time stamp will always be forced into the second line."
2861 :group 'org-time
2862 :type 'boolean)
2864 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2865 "Formats for `format-time-string' which are used for time stamps.
2866 It is not recommended to change this constant.")
2868 (defcustom org-time-stamp-rounding-minutes '(0 5)
2869 "Number of minutes to round time stamps to.
2870 These are two values, the first applies when first creating a time stamp.
2871 The second applies when changing it with the commands `S-up' and `S-down'.
2872 When changing the time stamp, this means that it will change in steps
2873 of N minutes, as given by the second value.
2875 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2876 numbers should be factors of 60, so for example 5, 10, 15.
2878 When this is larger than 1, you can still force an exact time stamp by using
2879 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2880 and by using a prefix arg to `S-up/down' to specify the exact number
2881 of minutes to shift."
2882 :group 'org-time
2883 :get #'(lambda (var) ; Make sure both elements are there
2884 (if (integerp (default-value var))
2885 (list (default-value var) 5)
2886 (default-value var)))
2887 :type '(list
2888 (integer :tag "when inserting times")
2889 (integer :tag "when modifying times")))
2891 ;; Normalize old customizations of this variable.
2892 (when (integerp org-time-stamp-rounding-minutes)
2893 (setq org-time-stamp-rounding-minutes
2894 (list org-time-stamp-rounding-minutes
2895 org-time-stamp-rounding-minutes)))
2897 (defcustom org-display-custom-times nil
2898 "Non-nil means overlay custom formats over all time stamps.
2899 The formats are defined through the variable `org-time-stamp-custom-formats'.
2900 To turn this on on a per-file basis, insert anywhere in the file:
2901 #+STARTUP: customtime"
2902 :group 'org-time
2903 :set 'set-default
2904 :type 'sexp)
2905 (make-variable-buffer-local 'org-display-custom-times)
2907 (defcustom org-time-stamp-custom-formats
2908 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2909 "Custom formats for time stamps. See `format-time-string' for the syntax.
2910 These are overlaid over the default ISO format if the variable
2911 `org-display-custom-times' is set. Time like %H:%M should be at the
2912 end of the second format. The custom formats are also honored by export
2913 commands, if custom time display is turned on at the time of export."
2914 :group 'org-time
2915 :type 'sexp)
2917 (defun org-time-stamp-format (&optional long inactive)
2918 "Get the right format for a time string."
2919 (let ((f (if long (cdr org-time-stamp-formats)
2920 (car org-time-stamp-formats))))
2921 (if inactive
2922 (concat "[" (substring f 1 -1) "]")
2923 f)))
2925 (defcustom org-time-clocksum-format
2926 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2927 "The format string used when creating CLOCKSUM lines.
2928 This is also used when Org mode generates a time duration.
2930 The value can be a single format string containing two
2931 %-sequences, which will be filled with the number of hours and
2932 minutes in that order.
2934 Alternatively, the value can be a plist associating any of the
2935 keys :years, :months, :weeks, :days, :hours or :minutes with
2936 format strings. The time duration is formatted using only the
2937 time components that are needed and concatenating the results.
2938 If a time unit in absent, it falls back to the next smallest
2939 unit.
2941 The keys :require-years, :require-months, :require-days,
2942 :require-weeks, :require-hours, :require-minutes are also
2943 meaningful. A non-nil value for these keys indicates that the
2944 corresponding time component should always be included, even if
2945 its value is 0.
2948 For example,
2950 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2951 :require-minutes t)
2953 means durations longer than a day will be expressed in days,
2954 hours and minutes, and durations less than a day will always be
2955 expressed in hours and minutes (even for durations less than an
2956 hour).
2958 The value
2960 \(:days \"%dd\" :minutes \"%dm\")
2962 means durations longer than a day will be expressed in days and
2963 minutes, and durations less than a day will be expressed entirely
2964 in minutes (even for durations longer than an hour)."
2965 :group 'org-time
2966 :group 'org-clock
2967 :version "24.4"
2968 :package-version '(Org . "8.0")
2969 :type '(choice (string :tag "Format string")
2970 (set :tag "Plist"
2971 (group :inline t (const :tag "Years" :years)
2972 (string :tag "Format string"))
2973 (group :inline t
2974 (const :tag "Always show years" :require-years)
2975 (const t))
2976 (group :inline t (const :tag "Months" :months)
2977 (string :tag "Format string"))
2978 (group :inline t
2979 (const :tag "Always show months" :require-months)
2980 (const t))
2981 (group :inline t (const :tag "Weeks" :weeks)
2982 (string :tag "Format string"))
2983 (group :inline t
2984 (const :tag "Always show weeks" :require-weeks)
2985 (const t))
2986 (group :inline t (const :tag "Days" :days)
2987 (string :tag "Format string"))
2988 (group :inline t
2989 (const :tag "Always show days" :require-days)
2990 (const t))
2991 (group :inline t (const :tag "Hours" :hours)
2992 (string :tag "Format string"))
2993 (group :inline t
2994 (const :tag "Always show hours" :require-hours)
2995 (const t))
2996 (group :inline t (const :tag "Minutes" :minutes)
2997 (string :tag "Format string"))
2998 (group :inline t
2999 (const :tag "Always show minutes" :require-minutes)
3000 (const t)))))
3002 (defcustom org-time-clocksum-use-fractional nil
3003 "When non-nil, \\[org-clock-display] uses fractional times.
3004 See `org-time-clocksum-format' for more on time clock formats."
3005 :group 'org-time
3006 :group 'org-clock
3007 :version "24.3"
3008 :type 'boolean)
3010 (defcustom org-time-clocksum-use-effort-durations nil
3011 "When non-nil, \\[org-clock-display] uses effort durations.
3012 E.g. by default, one day is considered to be a 8 hours effort,
3013 so a task that has been clocked for 16 hours will be displayed
3014 as during 2 days in the clock display or in the clocktable.
3016 See `org-effort-durations' on how to set effort durations
3017 and `org-time-clocksum-format' for more on time clock formats."
3018 :group 'org-time
3019 :group 'org-clock
3020 :version "24.4"
3021 :package-version '(Org . "8.0")
3022 :type 'boolean)
3024 (defcustom org-time-clocksum-fractional-format "%.2f"
3025 "The format string used when creating CLOCKSUM lines,
3026 or when Org mode generates a time duration, if
3027 `org-time-clocksum-use-fractional' is enabled.
3029 The value can be a single format string containing one
3030 %-sequence, which will be filled with the number of hours as
3031 a float.
3033 Alternatively, the value can be a plist associating any of the
3034 keys :years, :months, :weeks, :days, :hours or :minutes with
3035 a format string. The time duration is formatted using the
3036 largest time unit which gives a non-zero integer part. If all
3037 specified formats have zero integer part, the smallest time unit
3038 is used."
3039 :group 'org-time
3040 :type '(choice (string :tag "Format string")
3041 (set (group :inline t (const :tag "Years" :years)
3042 (string :tag "Format string"))
3043 (group :inline t (const :tag "Months" :months)
3044 (string :tag "Format string"))
3045 (group :inline t (const :tag "Weeks" :weeks)
3046 (string :tag "Format string"))
3047 (group :inline t (const :tag "Days" :days)
3048 (string :tag "Format string"))
3049 (group :inline t (const :tag "Hours" :hours)
3050 (string :tag "Format string"))
3051 (group :inline t (const :tag "Minutes" :minutes)
3052 (string :tag "Format string")))))
3054 (defcustom org-deadline-warning-days 14
3055 "Number of days before expiration during which a deadline becomes active.
3056 This variable governs the display in sparse trees and in the agenda.
3057 When 0 or negative, it means use this number (the absolute value of it)
3058 even if a deadline has a different individual lead time specified.
3060 Custom commands can set this variable in the options section."
3061 :group 'org-time
3062 :group 'org-agenda-daily/weekly
3063 :type 'integer)
3065 (defcustom org-scheduled-delay-days 0
3066 "Number of days before a scheduled item becomes active.
3067 This variable governs the display in sparse trees and in the agenda.
3068 The default value (i.e. 0) means: don't delay scheduled item.
3069 When negative, it means use this number (the absolute value of it)
3070 even if a scheduled item has a different individual delay time
3071 specified.
3073 Custom commands can set this variable in the options section."
3074 :group 'org-time
3075 :group 'org-agenda-daily/weekly
3076 :version "24.4"
3077 :package-version '(Org . "8.0")
3078 :type 'integer)
3080 (defcustom org-read-date-prefer-future t
3081 "Non-nil means assume future for incomplete date input from user.
3082 This affects the following situations:
3083 1. The user gives a month but not a year.
3084 For example, if it is April and you enter \"feb 2\", this will be read
3085 as Feb 2, *next* year. \"May 5\", however, will be this year.
3086 2. The user gives a day, but no month.
3087 For example, if today is the 15th, and you enter \"3\", Org-mode will
3088 read this as the third of *next* month. However, if you enter \"17\",
3089 it will be considered as *this* month.
3091 If you set this variable to the symbol `time', then also the following
3092 will work:
3094 3. If the user gives a time.
3095 If the time is before now, it will be interpreted as tomorrow.
3097 Currently none of this works for ISO week specifications.
3099 When this option is nil, the current day, month and year will always be
3100 used as defaults.
3102 See also `org-agenda-jump-prefer-future'."
3103 :group 'org-time
3104 :type '(choice
3105 (const :tag "Never" nil)
3106 (const :tag "Check month and day" t)
3107 (const :tag "Check month, day, and time" time)))
3109 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3110 "Should the agenda jump command prefer the future for incomplete dates?
3111 The default is to do the same as configured in `org-read-date-prefer-future'.
3112 But you can also set a deviating value here.
3113 This may t or nil, or the symbol `org-read-date-prefer-future'."
3114 :group 'org-agenda
3115 :group 'org-time
3116 :version "24.1"
3117 :type '(choice
3118 (const :tag "Use org-read-date-prefer-future"
3119 org-read-date-prefer-future)
3120 (const :tag "Never" nil)
3121 (const :tag "Always" t)))
3123 (defcustom org-read-date-force-compatible-dates t
3124 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3126 Depending on the system Emacs is running on, certain dates cannot
3127 be represented with the type used internally to represent time.
3128 Dates between 1970-1-1 and 2038-1-1 can always be represented
3129 correctly. Some systems allow for earlier dates, some for later,
3130 some for both. One way to find out it to insert any date into an
3131 Org buffer, putting the cursor on the year and hitting S-up and
3132 S-down to test the range.
3134 When this variable is set to t, the date/time prompt will not let
3135 you specify dates outside the 1970-2037 range, so it is certain that
3136 these dates will work in whatever version of Emacs you are
3137 running, and also that you can move a file from one Emacs implementation
3138 to another. WHenever Org is forcing the year for you, it will display
3139 a message and beep.
3141 When this variable is nil, Org will check if the date is
3142 representable in the specific Emacs implementation you are using.
3143 If not, it will force a year, usually the current year, and beep
3144 to remind you. Currently this setting is not recommended because
3145 the likelihood that you will open your Org files in an Emacs that
3146 has limited date range is not negligible.
3148 A workaround for this problem is to use diary sexp dates for time
3149 stamps outside of this range."
3150 :group 'org-time
3151 :version "24.1"
3152 :type 'boolean)
3154 (defcustom org-read-date-display-live t
3155 "Non-nil means display current interpretation of date prompt live.
3156 This display will be in an overlay, in the minibuffer."
3157 :group 'org-time
3158 :type 'boolean)
3160 (defcustom org-read-date-popup-calendar t
3161 "Non-nil means pop up a calendar when prompting for a date.
3162 In the calendar, the date can be selected with mouse-1. However, the
3163 minibuffer will also be active, and you can simply enter the date as well.
3164 When nil, only the minibuffer will be available."
3165 :group 'org-time
3166 :type 'boolean)
3167 (org-defvaralias 'org-popup-calendar-for-date-prompt
3168 'org-read-date-popup-calendar)
3170 (make-obsolete-variable
3171 'org-read-date-minibuffer-setup-hook
3172 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3173 (defcustom org-read-date-minibuffer-setup-hook nil
3174 "Hook to be used to set up keys for the date/time interface.
3175 Add key definitions to `minibuffer-local-map', which will be a
3176 temporary copy.
3178 WARNING: This option is obsolete, you should use
3179 `org-read-date-minibuffer-local-map' to set up keys."
3180 :group 'org-time
3181 :type 'hook)
3183 (defcustom org-extend-today-until 0
3184 "The hour when your day really ends. Must be an integer.
3185 This has influence for the following applications:
3186 - When switching the agenda to \"today\". It it is still earlier than
3187 the time given here, the day recognized as TODAY is actually yesterday.
3188 - When a date is read from the user and it is still before the time given
3189 here, the current date and time will be assumed to be yesterday, 23:59.
3190 Also, timestamps inserted in capture templates follow this rule.
3192 IMPORTANT: This is a feature whose implementation is and likely will
3193 remain incomplete. Really, it is only here because past midnight seems to
3194 be the favorite working time of John Wiegley :-)"
3195 :group 'org-time
3196 :type 'integer)
3198 (defcustom org-use-effective-time nil
3199 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3200 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3201 \"effective time\" of any timestamps between midnight and 8am will be
3202 23:59 of the previous day."
3203 :group 'org-time
3204 :version "24.1"
3205 :type 'boolean)
3207 (defcustom org-use-last-clock-out-time-as-effective-time nil
3208 "When non-nil, use the last clock out time for `org-todo'.
3209 Note that this option has precedence over the combined use of
3210 `org-use-effective-time' and `org-extend-today-until'."
3211 :group 'org-time
3212 :version "24.4"
3213 :package-version '(Org . "8.0")
3214 :type 'boolean)
3216 (defcustom org-edit-timestamp-down-means-later nil
3217 "Non-nil means S-down will increase the time in a time stamp.
3218 When nil, S-up will increase."
3219 :group 'org-time
3220 :type 'boolean)
3222 (defcustom org-calendar-follow-timestamp-change t
3223 "Non-nil means make the calendar window follow timestamp changes.
3224 When a timestamp is modified and the calendar window is visible, it will be
3225 moved to the new date."
3226 :group 'org-time
3227 :type 'boolean)
3229 (defgroup org-tags nil
3230 "Options concerning tags in Org-mode."
3231 :tag "Org Tags"
3232 :group 'org)
3234 (defcustom org-tag-alist nil
3235 "List of tags allowed in Org-mode files.
3236 When this list is nil, Org-mode will base TAG input on what is already in the
3237 buffer.
3238 The value of this variable is an alist, the car of each entry must be a
3239 keyword as a string, the cdr may be a character that is used to select
3240 that tag through the fast-tag-selection interface.
3241 See the manual for details."
3242 :group 'org-tags
3243 :type '(repeat
3244 (choice
3245 (cons (string :tag "Tag name")
3246 (character :tag "Access char"))
3247 (list :tag "Start radio group"
3248 (const :startgroup)
3249 (option (string :tag "Group description")))
3250 (list :tag "Group tags delimiter"
3251 (const :grouptags))
3252 (list :tag "End radio group"
3253 (const :endgroup)
3254 (option (string :tag "Group description")))
3255 (const :tag "New line" (:newline)))))
3257 (defcustom org-tag-persistent-alist nil
3258 "List of tags that will always appear in all Org-mode files.
3259 This is in addition to any in buffer settings or customizations
3260 of `org-tag-alist'.
3261 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3262 The value of this variable is an alist, the car of each entry must be a
3263 keyword as a string, the cdr may be a character that is used to select
3264 that tag through the fast-tag-selection interface.
3265 See the manual for details.
3266 To disable these tags on a per-file basis, insert anywhere in the file:
3267 #+STARTUP: noptag"
3268 :group 'org-tags
3269 :type '(repeat
3270 (choice
3271 (cons (string :tag "Tag name")
3272 (character :tag "Access char"))
3273 (const :tag "Start radio group" (:startgroup))
3274 (const :tag "Group tags delimiter" (:grouptags))
3275 (const :tag "End radio group" (:endgroup))
3276 (const :tag "New line" (:newline)))))
3278 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3279 "If non-nil, always offer completion for all tags of all agenda files.
3280 Instead of customizing this variable directly, you might want to
3281 set it locally for capture buffers, because there no list of
3282 tags in that file can be created dynamically (there are none).
3284 (add-hook 'org-capture-mode-hook
3285 (lambda ()
3286 (set (make-local-variable
3287 'org-complete-tags-always-offer-all-agenda-tags)
3288 t)))"
3289 :group 'org-tags
3290 :version "24.1"
3291 :type 'boolean)
3293 (defvar org-file-tags nil
3294 "List of tags that can be inherited by all entries in the file.
3295 The tags will be inherited if the variable `org-use-tag-inheritance'
3296 says they should be.
3297 This variable is populated from #+FILETAGS lines.")
3299 (defcustom org-use-fast-tag-selection 'auto
3300 "Non-nil means use fast tag selection scheme.
3301 This is a special interface to select and deselect tags with single keys.
3302 When nil, fast selection is never used.
3303 When the symbol `auto', fast selection is used if and only if selection
3304 characters for tags have been configured, either through the variable
3305 `org-tag-alist' or through a #+TAGS line in the buffer.
3306 When t, fast selection is always used and selection keys are assigned
3307 automatically if necessary."
3308 :group 'org-tags
3309 :type '(choice
3310 (const :tag "Always" t)
3311 (const :tag "Never" nil)
3312 (const :tag "When selection characters are configured" auto)))
3314 (defcustom org-fast-tag-selection-single-key nil
3315 "Non-nil means fast tag selection exits after first change.
3316 When nil, you have to press RET to exit it.
3317 During fast tag selection, you can toggle this flag with `C-c'.
3318 This variable can also have the value `expert'. In this case, the window
3319 displaying the tags menu is not even shown, until you press C-c again."
3320 :group 'org-tags
3321 :type '(choice
3322 (const :tag "No" nil)
3323 (const :tag "Yes" t)
3324 (const :tag "Expert" expert)))
3326 (defvar org-fast-tag-selection-include-todo nil
3327 "Non-nil means fast tags selection interface will also offer TODO states.
3328 This is an undocumented feature, you should not rely on it.")
3330 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3331 "The column to which tags should be indented in a headline.
3332 If this number is positive, it specifies the column. If it is negative,
3333 it means that the tags should be flushright to that column. For example,
3334 -80 works well for a normal 80 character screen.
3335 When 0, place tags directly after headline text, with only one space in
3336 between."
3337 :group 'org-tags
3338 :type 'integer)
3340 (defcustom org-auto-align-tags t
3341 "Non-nil keeps tags aligned when modifying headlines.
3342 Some operations (i.e. demoting) change the length of a headline and
3343 therefore shift the tags around. With this option turned on, after
3344 each such operation the tags are again aligned to `org-tags-column'."
3345 :group 'org-tags
3346 :type 'boolean)
3348 (defcustom org-use-tag-inheritance t
3349 "Non-nil means tags in levels apply also for sublevels.
3350 When nil, only the tags directly given in a specific line apply there.
3351 This may also be a list of tags that should be inherited, or a regexp that
3352 matches tags that should be inherited. Additional control is possible
3353 with the variable `org-tags-exclude-from-inheritance' which gives an
3354 explicit list of tags to be excluded from inheritance, even if the value of
3355 `org-use-tag-inheritance' would select it for inheritance.
3357 If this option is t, a match early-on in a tree can lead to a large
3358 number of matches in the subtree when constructing the agenda or creating
3359 a sparse tree. If you only want to see the first match in a tree during
3360 a search, check out the variable `org-tags-match-list-sublevels'."
3361 :group 'org-tags
3362 :type '(choice
3363 (const :tag "Not" nil)
3364 (const :tag "Always" t)
3365 (repeat :tag "Specific tags" (string :tag "Tag"))
3366 (regexp :tag "Tags matched by regexp")))
3368 (defcustom org-tags-exclude-from-inheritance nil
3369 "List of tags that should never be inherited.
3370 This is a way to exclude a few tags from inheritance. For way to do
3371 the opposite, to actively allow inheritance for selected tags,
3372 see the variable `org-use-tag-inheritance'."
3373 :group 'org-tags
3374 :type '(repeat (string :tag "Tag")))
3376 (defun org-tag-inherit-p (tag)
3377 "Check if TAG is one that should be inherited."
3378 (cond
3379 ((member tag org-tags-exclude-from-inheritance) nil)
3380 ((eq org-use-tag-inheritance t) t)
3381 ((not org-use-tag-inheritance) nil)
3382 ((stringp org-use-tag-inheritance)
3383 (string-match org-use-tag-inheritance tag))
3384 ((listp org-use-tag-inheritance)
3385 (member tag org-use-tag-inheritance))
3386 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3388 (defcustom org-tags-match-list-sublevels t
3389 "Non-nil means list also sublevels of headlines matching a search.
3390 This variable applies to tags/property searches, and also to stuck
3391 projects because this search is based on a tags match as well.
3393 When set to the symbol `indented', sublevels are indented with
3394 leading dots.
3396 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3397 the sublevels of a headline matching a tag search often also match
3398 the same search. Listing all of them can create very long lists.
3399 Setting this variable to nil causes subtrees of a match to be skipped.
3401 This variable is semi-obsolete and probably should always be true. It
3402 is better to limit inheritance to certain tags using the variables
3403 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3404 :group 'org-tags
3405 :type '(choice
3406 (const :tag "No, don't list them" nil)
3407 (const :tag "Yes, do list them" t)
3408 (const :tag "List them, indented with leading dots" indented)))
3410 (defcustom org-tags-sort-function nil
3411 "When set, tags are sorted using this function as a comparator."
3412 :group 'org-tags
3413 :type '(choice
3414 (const :tag "No sorting" nil)
3415 (const :tag "Alphabetical" string<)
3416 (const :tag "Reverse alphabetical" string>)
3417 (function :tag "Custom function" nil)))
3419 (defvar org-tags-history nil
3420 "History of minibuffer reads for tags.")
3421 (defvar org-last-tags-completion-table nil
3422 "The last used completion table for tags.")
3423 (defvar org-after-tags-change-hook nil
3424 "Hook that is run after the tags in a line have changed.")
3426 (defgroup org-properties nil
3427 "Options concerning properties in Org-mode."
3428 :tag "Org Properties"
3429 :group 'org)
3431 (defcustom org-property-format "%-10s %s"
3432 "How property key/value pairs should be formatted by `indent-line'.
3433 When `indent-line' hits a property definition, it will format the line
3434 according to this format, mainly to make sure that the values are
3435 lined-up with respect to each other."
3436 :group 'org-properties
3437 :type 'string)
3439 (defcustom org-properties-postprocess-alist nil
3440 "Alist of properties and functions to adjust inserted values.
3441 Elements of this alist must be of the form
3443 ([string] [function])
3445 where [string] must be a property name and [function] must be a
3446 lambda expression: this lambda expression must take one argument,
3447 the value to adjust, and return the new value as a string.
3449 For example, this element will allow the property \"Remaining\"
3450 to be updated wrt the relation between the \"Effort\" property
3451 and the clock summary:
3453 ((\"Remaining\" (lambda(value)
3454 (let ((clocksum (org-clock-sum-current-item))
3455 (effort (org-duration-string-to-minutes
3456 (org-entry-get (point) \"Effort\"))))
3457 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3458 :group 'org-properties
3459 :version "24.1"
3460 :type '(alist :key-type (string :tag "Property")
3461 :value-type (function :tag "Function")))
3463 (defcustom org-use-property-inheritance nil
3464 "Non-nil means properties apply also for sublevels.
3466 This setting is chiefly used during property searches. Turning it on can
3467 cause significant overhead when doing a search, which is why it is not
3468 on by default.
3470 When nil, only the properties directly given in the current entry count.
3471 When t, every property is inherited. The value may also be a list of
3472 properties that should have inheritance, or a regular expression matching
3473 properties that should be inherited.
3475 However, note that some special properties use inheritance under special
3476 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3477 and the properties ending in \"_ALL\" when they are used as descriptor
3478 for valid values of a property.
3480 Note for programmers:
3481 When querying an entry with `org-entry-get', you can control if inheritance
3482 should be used. By default, `org-entry-get' looks only at the local
3483 properties. You can request inheritance by setting the inherit argument
3484 to t (to force inheritance) or to `selective' (to respect the setting
3485 in this variable)."
3486 :group 'org-properties
3487 :type '(choice
3488 (const :tag "Not" nil)
3489 (const :tag "Always" t)
3490 (repeat :tag "Specific properties" (string :tag "Property"))
3491 (regexp :tag "Properties matched by regexp")))
3493 (defun org-property-inherit-p (property)
3494 "Check if PROPERTY is one that should be inherited."
3495 (cond
3496 ((eq org-use-property-inheritance t) t)
3497 ((not org-use-property-inheritance) nil)
3498 ((stringp org-use-property-inheritance)
3499 (string-match org-use-property-inheritance property))
3500 ((listp org-use-property-inheritance)
3501 (member property org-use-property-inheritance))
3502 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3504 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3505 "The default column format, if no other format has been defined.
3506 This variable can be set on the per-file basis by inserting a line
3508 #+COLUMNS: %25ITEM ....."
3509 :group 'org-properties
3510 :type 'string)
3512 (defcustom org-columns-ellipses ".."
3513 "The ellipses to be used when a field in column view is truncated.
3514 When this is the empty string, as many characters as possible are shown,
3515 but then there will be no visual indication that the field has been truncated.
3516 When this is a string of length N, the last N characters of a truncated
3517 field are replaced by this string. If the column is narrower than the
3518 ellipses string, only part of the ellipses string will be shown."
3519 :group 'org-properties
3520 :type 'string)
3522 (defcustom org-columns-modify-value-for-display-function nil
3523 "Function that modifies values for display in column view.
3524 For example, it can be used to cut out a certain part from a time stamp.
3525 The function must take 2 arguments:
3527 column-title The title of the column (*not* the property name)
3528 value The value that should be modified.
3530 The function should return the value that should be displayed,
3531 or nil if the normal value should be used."
3532 :group 'org-properties
3533 :type '(choice (const nil) (function)))
3535 (defcustom org-effort-property "Effort"
3536 "The property that is being used to keep track of effort estimates.
3537 Effort estimates given in this property need to have the format H:MM."
3538 :group 'org-properties
3539 :group 'org-progress
3540 :type '(string :tag "Property"))
3542 (defconst org-global-properties-fixed
3543 '(("VISIBILITY_ALL" . "folded children content all")
3544 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3545 "List of property/value pairs that can be inherited by any entry.
3547 These are fixed values, for the preset properties. The user variable
3548 that can be used to add to this list is `org-global-properties'.
3550 The entries in this list are cons cells where the car is a property
3551 name and cdr is a string with the value. If the value represents
3552 multiple items like an \"_ALL\" property, separate the items by
3553 spaces.")
3555 (defcustom org-global-properties nil
3556 "List of property/value pairs that can be inherited by any entry.
3558 This list will be combined with the constant `org-global-properties-fixed'.
3560 The entries in this list are cons cells where the car is a property
3561 name and cdr is a string with the value.
3563 You can set buffer-local values for the same purpose in the variable
3564 `org-file-properties' this by adding lines like
3566 #+PROPERTY: NAME VALUE"
3567 :group 'org-properties
3568 :type '(repeat
3569 (cons (string :tag "Property")
3570 (string :tag "Value"))))
3572 (defvar org-file-properties nil
3573 "List of property/value pairs that can be inherited by any entry.
3574 Valid for the current buffer.
3575 This variable is populated from #+PROPERTY lines.")
3576 (make-variable-buffer-local 'org-file-properties)
3578 (defgroup org-agenda nil
3579 "Options concerning agenda views in Org-mode."
3580 :tag "Org Agenda"
3581 :group 'org)
3583 (defvar org-category nil
3584 "Variable used by org files to set a category for agenda display.
3585 Such files should use a file variable to set it, for example
3587 # -*- mode: org; org-category: \"ELisp\"
3589 or contain a special line
3591 #+CATEGORY: ELisp
3593 If the file does not specify a category, then file's base name
3594 is used instead.")
3595 (make-variable-buffer-local 'org-category)
3596 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3598 (defcustom org-agenda-files nil
3599 "The files to be used for agenda display.
3600 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3601 \\[org-remove-file]. You can also use customize to edit the list.
3603 If an entry is a directory, all files in that directory that are matched by
3604 `org-agenda-file-regexp' will be part of the file list.
3606 If the value of the variable is not a list but a single file name, then
3607 the list of agenda files is actually stored and maintained in that file, one
3608 agenda file per line. In this file paths can be given relative to
3609 `org-directory'. Tilde expansion and environment variable substitution
3610 are also made."
3611 :group 'org-agenda
3612 :type '(choice
3613 (repeat :tag "List of files and directories" file)
3614 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3616 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3617 "Regular expression to match files for `org-agenda-files'.
3618 If any element in the list in that variable contains a directory instead
3619 of a normal file, all files in that directory that are matched by this
3620 regular expression will be included."
3621 :group 'org-agenda
3622 :type 'regexp)
3624 (defcustom org-agenda-text-search-extra-files nil
3625 "List of extra files to be searched by text search commands.
3626 These files will be searched in addition to the agenda files by the
3627 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3628 Note that these files will only be searched for text search commands,
3629 not for the other agenda views like todo lists, tag searches or the weekly
3630 agenda. This variable is intended to list notes and possibly archive files
3631 that should also be searched by these two commands.
3632 In fact, if the first element in the list is the symbol `agenda-archives',
3633 then all archive files of all agenda files will be added to the search
3634 scope."
3635 :group 'org-agenda
3636 :type '(set :greedy t
3637 (const :tag "Agenda Archives" agenda-archives)
3638 (repeat :inline t (file))))
3640 (org-defvaralias 'org-agenda-multi-occur-extra-files
3641 'org-agenda-text-search-extra-files)
3643 (defcustom org-agenda-skip-unavailable-files nil
3644 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3645 A nil value means to remove them, after a query, from the list."
3646 :group 'org-agenda
3647 :type 'boolean)
3649 (defcustom org-calendar-to-agenda-key [?c]
3650 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3651 The command `org-calendar-goto-agenda' will be bound to this key. The
3652 default is the character `c' because then `c' can be used to switch back and
3653 forth between agenda and calendar."
3654 :group 'org-agenda
3655 :type 'sexp)
3657 (defcustom org-calendar-insert-diary-entry-key [?i]
3658 "The key to be installed in `calendar-mode-map' for adding diary entries.
3659 This option is irrelevant until `org-agenda-diary-file' has been configured
3660 to point to an Org-mode file. When that is the case, the command
3661 `org-agenda-diary-entry' will be bound to the key given here, by default
3662 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3663 if you want to continue doing this, you need to change this to a different
3664 key."
3665 :group 'org-agenda
3666 :type 'sexp)
3668 (defcustom org-agenda-diary-file 'diary-file
3669 "File to which to add new entries with the `i' key in agenda and calendar.
3670 When this is the symbol `diary-file', the functionality in the Emacs
3671 calendar will be used to add entries to the `diary-file'. But when this
3672 points to a file, `org-agenda-diary-entry' will be used instead."
3673 :group 'org-agenda
3674 :type '(choice
3675 (const :tag "The standard Emacs diary file" diary-file)
3676 (file :tag "Special Org file diary entries")))
3678 (eval-after-load "calendar"
3679 '(progn
3680 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3681 'org-calendar-goto-agenda)
3682 (add-hook 'calendar-mode-hook
3683 (lambda ()
3684 (unless (eq org-agenda-diary-file 'diary-file)
3685 (define-key calendar-mode-map
3686 org-calendar-insert-diary-entry-key
3687 'org-agenda-diary-entry))))))
3689 (defgroup org-latex nil
3690 "Options for embedding LaTeX code into Org-mode."
3691 :tag "Org LaTeX"
3692 :group 'org)
3694 (defcustom org-format-latex-options
3695 '(:foreground default :background default :scale 1.0
3696 :html-foreground "Black" :html-background "Transparent"
3697 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3698 "Options for creating images from LaTeX fragments.
3699 This is a property list with the following properties:
3700 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3701 `default' means use the foreground of the default face.
3702 `auto' means use the foreground from the text face.
3703 :background the background color, or \"Transparent\".
3704 `default' means use the background of the default face.
3705 `auto' means use the background from the text face.
3706 :scale a scaling factor for the size of the images, to get more pixels
3707 :html-foreground, :html-background, :html-scale
3708 the same numbers for HTML export.
3709 :matchers a list indicating which matchers should be used to
3710 find LaTeX fragments. Valid members of this list are:
3711 \"begin\" find environments
3712 \"$1\" find single characters surrounded by $.$
3713 \"$\" find math expressions surrounded by $...$
3714 \"$$\" find math expressions surrounded by $$....$$
3715 \"\\(\" find math expressions surrounded by \\(...\\)
3716 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3717 :group 'org-latex
3718 :type 'plist)
3720 (defcustom org-format-latex-signal-error t
3721 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3722 When nil, just push out a message."
3723 :group 'org-latex
3724 :version "24.1"
3725 :type 'boolean)
3727 (defcustom org-latex-to-mathml-jar-file nil
3728 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3729 Use this to specify additional executable file say a jar file.
3731 When using MathToWeb as the converter, specify the full-path to
3732 your mathtoweb.jar file."
3733 :group 'org-latex
3734 :version "24.1"
3735 :type '(choice
3736 (const :tag "None" nil)
3737 (file :tag "JAR file" :must-match t)))
3739 (defcustom org-latex-to-mathml-convert-command nil
3740 "Command to convert LaTeX fragments to MathML.
3741 Replace format-specifiers in the command as noted below and use
3742 `shell-command' to convert LaTeX to MathML.
3743 %j: Executable file in fully expanded form as specified by
3744 `org-latex-to-mathml-jar-file'.
3745 %I: Input LaTeX file in fully expanded form
3746 %o: Output MathML file
3747 This command is used by `org-create-math-formula'.
3749 When using MathToWeb as the converter, set this to
3750 \"java -jar %j -unicode -force -df %o %I\"."
3751 :group 'org-latex
3752 :version "24.1"
3753 :type '(choice
3754 (const :tag "None" nil)
3755 (string :tag "\nShell command")))
3757 (defcustom org-latex-create-formula-image-program 'dvipng
3758 "Program to convert LaTeX fragments with.
3760 dvipng Process the LaTeX fragments to dvi file, then convert
3761 dvi files to png files using dvipng.
3762 This will also include processing of non-math environments.
3763 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3764 to convert pdf files to png files"
3765 :group 'org-latex
3766 :version "24.1"
3767 :type '(choice
3768 (const :tag "dvipng" dvipng)
3769 (const :tag "imagemagick" imagemagick)))
3771 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3772 "Path to store latex preview images.
3773 A relative path here creates many directories relative to the
3774 processed org files paths. An absolute path puts all preview
3775 images at the same place."
3776 :group 'org-latex
3777 :version "24.3"
3778 :type 'string)
3780 (defun org-format-latex-mathml-available-p ()
3781 "Return t if `org-latex-to-mathml-convert-command' is usable."
3782 (save-match-data
3783 (when (and (boundp 'org-latex-to-mathml-convert-command)
3784 org-latex-to-mathml-convert-command)
3785 (let ((executable (car (split-string
3786 org-latex-to-mathml-convert-command))))
3787 (when (executable-find executable)
3788 (if (string-match
3789 "%j" org-latex-to-mathml-convert-command)
3790 (file-readable-p org-latex-to-mathml-jar-file)
3791 t))))))
3793 (defcustom org-format-latex-header "\\documentclass{article}
3794 \\usepackage[usenames]{color}
3795 \[PACKAGES]
3796 \[DEFAULT-PACKAGES]
3797 \\pagestyle{empty} % do not remove
3798 % The settings below are copied from fullpage.sty
3799 \\setlength{\\textwidth}{\\paperwidth}
3800 \\addtolength{\\textwidth}{-3cm}
3801 \\setlength{\\oddsidemargin}{1.5cm}
3802 \\addtolength{\\oddsidemargin}{-2.54cm}
3803 \\setlength{\\evensidemargin}{\\oddsidemargin}
3804 \\setlength{\\textheight}{\\paperheight}
3805 \\addtolength{\\textheight}{-\\headheight}
3806 \\addtolength{\\textheight}{-\\headsep}
3807 \\addtolength{\\textheight}{-\\footskip}
3808 \\addtolength{\\textheight}{-3cm}
3809 \\setlength{\\topmargin}{1.5cm}
3810 \\addtolength{\\topmargin}{-2.54cm}"
3811 "The document header used for processing LaTeX fragments.
3812 It is imperative that this header make sure that no page number
3813 appears on the page. The package defined in the variables
3814 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3815 will either replace the placeholder \"[PACKAGES]\" in this
3816 header, or they will be appended."
3817 :group 'org-latex
3818 :type 'string)
3820 (defun org-set-packages-alist (var val)
3821 "Set the packages alist and make sure it has 3 elements per entry."
3822 (set var (mapcar (lambda (x)
3823 (if (and (consp x) (= (length x) 2))
3824 (list (car x) (nth 1 x) t)
3826 val)))
3828 (defun org-get-packages-alist (var)
3829 "Get the packages alist and make sure it has 3 elements per entry."
3830 (mapcar (lambda (x)
3831 (if (and (consp x) (= (length x) 2))
3832 (list (car x) (nth 1 x) t)
3834 (default-value var)))
3836 (defcustom org-latex-default-packages-alist
3837 '(("AUTO" "inputenc" t)
3838 ("T1" "fontenc" t)
3839 ("" "fixltx2e" nil)
3840 ("" "graphicx" t)
3841 ("" "longtable" nil)
3842 ("" "float" nil)
3843 ("" "wrapfig" nil)
3844 ("" "rotating" nil)
3845 ("normalem" "ulem" t)
3846 ("" "amsmath" t)
3847 ("" "textcomp" t)
3848 ("" "marvosym" t)
3849 ("" "wasysym" t)
3850 ("" "amssymb" t)
3851 ("" "hyperref" nil)
3852 "\\tolerance=1000")
3853 "Alist of default packages to be inserted in the header.
3855 Change this only if one of the packages here causes an
3856 incompatibility with another package you are using.
3858 The packages in this list are needed by one part or another of
3859 Org mode to function properly:
3861 - inputenc, fontenc: for basic font and character selection
3862 - fixltx2e: Important patches of LaTeX itself
3863 - graphicx: for including images
3864 - longtable: For multipage tables
3865 - float, wrapfig: for figure placement
3866 - rotating: for sideways figures and tables
3867 - ulem: for underline and strike-through
3868 - amsmath: for subscript and superscript and math environments
3869 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3870 for interpreting the entities in `org-entities'. You can skip
3871 some of these packages if you don't use any of their symbols.
3872 - hyperref: for cross references
3874 Therefore you should not modify this variable unless you know
3875 what you are doing. The one reason to change it anyway is that
3876 you might be loading some other package that conflicts with one
3877 of the default packages. Each element is either a cell or
3878 a string.
3880 A cell is of the format:
3882 \( \"options\" \"package\" SNIPPET-FLAG).
3884 If SNIPPET-FLAG is non-nil, the package also needs to be included
3885 when compiling LaTeX snippets into images for inclusion into
3886 non-LaTeX output.
3888 A string will be inserted as-is in the header of the document."
3889 :group 'org-latex
3890 :group 'org-export-latex
3891 :set 'org-set-packages-alist
3892 :get 'org-get-packages-alist
3893 :version "24.1"
3894 :type '(repeat
3895 (choice
3896 (list :tag "options/package pair"
3897 (string :tag "options")
3898 (string :tag "package")
3899 (boolean :tag "Snippet"))
3900 (string :tag "A line of LaTeX"))))
3902 (defcustom org-latex-packages-alist nil
3903 "Alist of packages to be inserted in every LaTeX header.
3905 These will be inserted after `org-latex-default-packages-alist'.
3906 Each element is either a cell or a string.
3908 A cell is of the format:
3910 \(\"options\" \"package\" SNIPPET-FLAG)
3912 SNIPPET-FLAG, when non-nil, indicates that this package is also
3913 needed when turning LaTeX snippets into images for inclusion into
3914 non-LaTeX output.
3916 A string will be inserted as-is in the header of the document.
3918 Make sure that you only list packages here which:
3920 - you want in every file;
3921 - do not conflict with the setup in `org-format-latex-header';
3922 - do not conflict with the default packages in
3923 `org-latex-default-packages-alist'."
3924 :group 'org-latex
3925 :group 'org-export-latex
3926 :set 'org-set-packages-alist
3927 :get 'org-get-packages-alist
3928 :type '(repeat
3929 (choice
3930 (list :tag "options/package pair"
3931 (string :tag "options")
3932 (string :tag "package")
3933 (boolean :tag "Snippet"))
3934 (string :tag "A line of LaTeX"))))
3936 (defgroup org-appearance nil
3937 "Settings for Org-mode appearance."
3938 :tag "Org Appearance"
3939 :group 'org)
3941 (defcustom org-level-color-stars-only nil
3942 "Non-nil means fontify only the stars in each headline.
3943 When nil, the entire headline is fontified.
3944 Changing it requires restart of `font-lock-mode' to become effective
3945 also in regions already fontified."
3946 :group 'org-appearance
3947 :type 'boolean)
3949 (defcustom org-hide-leading-stars nil
3950 "Non-nil means hide the first N-1 stars in a headline.
3951 This works by using the face `org-hide' for these stars. This
3952 face is white for a light background, and black for a dark
3953 background. You may have to customize the face `org-hide' to
3954 make this work.
3955 Changing it requires restart of `font-lock-mode' to become effective
3956 also in regions already fontified.
3957 You may also set this on a per-file basis by adding one of the following
3958 lines to the buffer:
3960 #+STARTUP: hidestars
3961 #+STARTUP: showstars"
3962 :group 'org-appearance
3963 :type 'boolean)
3965 (defcustom org-hidden-keywords nil
3966 "List of symbols corresponding to keywords to be hidden the org buffer.
3967 For example, a value '(title) for this list will make the document's title
3968 appear in the buffer without the initial #+TITLE: keyword."
3969 :group 'org-appearance
3970 :version "24.1"
3971 :type '(set (const :tag "#+AUTHOR" author)
3972 (const :tag "#+DATE" date)
3973 (const :tag "#+EMAIL" email)
3974 (const :tag "#+TITLE" title)))
3976 (defcustom org-custom-properties nil
3977 "List of properties (as strings) with a special meaning.
3978 The default use of these custom properties is to let the user
3979 hide them with `org-toggle-custom-properties-visibility'."
3980 :group 'org-properties
3981 :group 'org-appearance
3982 :version "24.3"
3983 :type '(repeat (string :tag "Property Name")))
3985 (defcustom org-fontify-done-headline nil
3986 "Non-nil means change the face of a headline if it is marked DONE.
3987 Normally, only the TODO/DONE keyword indicates the state of a headline.
3988 When this is non-nil, the headline after the keyword is set to the
3989 `org-headline-done' as an additional indication."
3990 :group 'org-appearance
3991 :type 'boolean)
3993 (defcustom org-fontify-emphasized-text t
3994 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3995 Changing this variable requires a restart of Emacs to take effect."
3996 :group 'org-appearance
3997 :type 'boolean)
3999 (defcustom org-fontify-whole-heading-line nil
4000 "Non-nil means fontify the whole line for headings.
4001 This is useful when setting a background color for the
4002 org-level-* faces."
4003 :group 'org-appearance
4004 :type 'boolean)
4006 (defcustom org-highlight-latex-and-related nil
4007 "Non-nil means highlight LaTeX related syntax in the buffer.
4008 When non nil, the value should be a list containing any of the
4009 following symbols:
4010 `latex' Highlight LaTeX snippets and environments.
4011 `script' Highlight subscript and superscript.
4012 `entities' Highlight entities."
4013 :group 'org-appearance
4014 :version "24.4"
4015 :package-version '(Org . "8.0")
4016 :type '(choice
4017 (const :tag "No highlighting" nil)
4018 (set :greedy t :tag "Highlight"
4019 (const :tag "LaTeX snippets and environments" latex)
4020 (const :tag "Subscript and superscript" script)
4021 (const :tag "Entities" entities))))
4023 (defcustom org-hide-emphasis-markers nil
4024 "Non-nil mean font-lock should hide the emphasis marker characters."
4025 :group 'org-appearance
4026 :type 'boolean)
4028 (defcustom org-pretty-entities nil
4029 "Non-nil means show entities as UTF8 characters.
4030 When nil, the \\name form remains in the buffer."
4031 :group 'org-appearance
4032 :version "24.1"
4033 :type 'boolean)
4035 (defcustom org-pretty-entities-include-sub-superscripts t
4036 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4037 :group 'org-appearance
4038 :version "24.1"
4039 :type 'boolean)
4041 (defvar org-emph-re nil
4042 "Regular expression for matching emphasis.
4043 After a match, the match groups contain these elements:
4044 0 The match of the full regular expression, including the characters
4045 before and after the proper match
4046 1 The character before the proper match, or empty at beginning of line
4047 2 The proper match, including the leading and trailing markers
4048 3 The leading marker like * or /, indicating the type of highlighting
4049 4 The text between the emphasis markers, not including the markers
4050 5 The character after the match, empty at the end of a line")
4051 (defvar org-verbatim-re nil
4052 "Regular expression for matching verbatim text.")
4053 (defvar org-emphasis-regexp-components) ; defined just below
4054 (defvar org-emphasis-alist) ; defined just below
4055 (defun org-set-emph-re (var val)
4056 "Set variable and compute the emphasis regular expression."
4057 (set var val)
4058 (when (and (boundp 'org-emphasis-alist)
4059 (boundp 'org-emphasis-regexp-components)
4060 org-emphasis-alist org-emphasis-regexp-components)
4061 (let* ((e org-emphasis-regexp-components)
4062 (pre (car e))
4063 (post (nth 1 e))
4064 (border (nth 2 e))
4065 (body (nth 3 e))
4066 (nl (nth 4 e))
4067 (body1 (concat body "*?"))
4068 (markers (mapconcat 'car org-emphasis-alist ""))
4069 (vmarkers (mapconcat
4070 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4071 org-emphasis-alist "")))
4072 ;; make sure special characters appear at the right position in the class
4073 (if (string-match "\\^" markers)
4074 (setq markers (concat (replace-match "" t t markers) "^")))
4075 (if (string-match "-" markers)
4076 (setq markers (concat (replace-match "" t t markers) "-")))
4077 (if (string-match "\\^" vmarkers)
4078 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4079 (if (string-match "-" vmarkers)
4080 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4081 (if (> nl 0)
4082 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4083 (int-to-string nl) "\\}")))
4084 ;; Make the regexp
4085 (setq org-emph-re
4086 (concat "\\([" pre "]\\|^\\)"
4087 "\\("
4088 "\\([" markers "]\\)"
4089 "\\("
4090 "[^" border "]\\|"
4091 "[^" border "]"
4092 body1
4093 "[^" border "]"
4094 "\\)"
4095 "\\3\\)"
4096 "\\([" post "]\\|$\\)"))
4097 (setq org-verbatim-re
4098 (concat "\\([" pre "]\\|^\\)"
4099 "\\("
4100 "\\([" vmarkers "]\\)"
4101 "\\("
4102 "[^" border "]\\|"
4103 "[^" border "]"
4104 body1
4105 "[^" border "]"
4106 "\\)"
4107 "\\3\\)"
4108 "\\([" post "]\\|$\\)")))))
4110 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4111 ;; set this option proved cumbersome. See this message/thread:
4112 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4113 (defvar org-emphasis-regexp-components
4114 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4115 "Components used to build the regular expression for emphasis.
4116 This is a list with five entries. Terminology: In an emphasis string
4117 like \" *strong word* \", we call the initial space PREMATCH, the final
4118 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4119 and \"trong wor\" is the body. The different components in this variable
4120 specify what is allowed/forbidden in each part:
4122 pre Chars allowed as prematch. Beginning of line will be allowed too.
4123 post Chars allowed as postmatch. End of line will be allowed too.
4124 border The chars *forbidden* as border characters.
4125 body-regexp A regexp like \".\" to match a body character. Don't use
4126 non-shy groups here, and don't allow newline here.
4127 newline The maximum number of newlines allowed in an emphasis exp.
4129 You need to reload Org or to restart Emacs after customizing this.")
4131 (defcustom org-emphasis-alist
4132 `(("*" bold)
4133 ("/" italic)
4134 ("_" underline)
4135 ("=" org-verbatim verbatim)
4136 ("~" org-code verbatim)
4137 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4138 "Alist of characters and faces to emphasize text.
4139 Text starting and ending with a special character will be emphasized,
4140 for example *bold*, _underlined_ and /italic/. This variable sets the
4141 marker characters and the face to be used by font-lock for highlighting
4142 in Org-mode Emacs buffers.
4144 You need to reload Org or to restart Emacs after customizing this."
4145 :group 'org-appearance
4146 :set 'org-set-emph-re
4147 :version "24.4"
4148 :package-version '(Org . "8.0")
4149 :type '(repeat
4150 (list
4151 (string :tag "Marker character")
4152 (choice
4153 (face :tag "Font-lock-face")
4154 (plist :tag "Face property list"))
4155 (option (const verbatim)))))
4157 (defvar org-protecting-blocks
4158 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4159 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4160 This is needed for font-lock setup.")
4162 ;;; Miscellaneous options
4164 (defgroup org-completion nil
4165 "Completion in Org-mode."
4166 :tag "Org Completion"
4167 :group 'org)
4169 (defcustom org-completion-use-ido nil
4170 "Non-nil means use ido completion wherever possible.
4171 Note that `ido-mode' must be active for this variable to be relevant.
4172 If you decide to turn this variable on, you might well want to turn off
4173 `org-outline-path-complete-in-steps'.
4174 See also `org-completion-use-iswitchb'."
4175 :group 'org-completion
4176 :type 'boolean)
4178 (defcustom org-completion-use-iswitchb nil
4179 "Non-nil means use iswitchb completion wherever possible.
4180 Note that `iswitchb-mode' must be active for this variable to be relevant.
4181 If you decide to turn this variable on, you might well want to turn off
4182 `org-outline-path-complete-in-steps'.
4183 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4184 :group 'org-completion
4185 :type 'boolean)
4187 (defcustom org-completion-fallback-command 'hippie-expand
4188 "The expansion command called by \\[pcomplete] in normal context.
4189 Normal means, no org-mode-specific context."
4190 :group 'org-completion
4191 :type 'function)
4193 ;;; Functions and variables from their packages
4194 ;; Declared here to avoid compiler warnings
4196 ;; XEmacs only
4197 (defvar outline-mode-menu-heading)
4198 (defvar outline-mode-menu-show)
4199 (defvar outline-mode-menu-hide)
4200 (defvar zmacs-regions) ; XEmacs regions
4202 ;; Emacs only
4203 (defvar mark-active)
4205 ;; Various packages
4206 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4207 (declare-function calendar-forward-day "cal-move" (arg))
4208 (declare-function calendar-goto-date "cal-move" (date))
4209 (declare-function calendar-goto-today "cal-move" ())
4210 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4211 (defvar calc-embedded-close-formula)
4212 (defvar calc-embedded-open-formula)
4213 (declare-function cdlatex-tab "ext:cdlatex" ())
4214 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4215 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4216 (defvar font-lock-unfontify-region-function)
4217 (declare-function iswitchb-read-buffer "iswitchb"
4218 (prompt &optional default require-match start matches-set))
4219 (defvar iswitchb-temp-buflist)
4220 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4221 (defvar org-agenda-tags-todo-honor-ignore-options)
4222 (declare-function org-agenda-skip "org-agenda" ())
4223 (declare-function
4224 org-agenda-format-item "org-agenda"
4225 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4226 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4227 (declare-function org-agenda-change-all-lines "org-agenda"
4228 (newhead hdmarker &optional fixface just-this))
4229 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4230 (declare-function org-agenda-maybe-redo "org-agenda" ())
4231 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4232 (beg end))
4233 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4234 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4235 "org-agenda" (&optional end))
4236 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4237 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4238 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4239 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4240 (declare-function org-indent-mode "org-indent" (&optional arg))
4241 (declare-function parse-time-string "parse-time" (string))
4242 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4243 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4244 (defvar remember-data-file)
4245 (defvar texmathp-why)
4246 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4247 (declare-function table--at-cell-p "table" (position &optional object at-column))
4249 (defvar org-latex-regexps)
4251 ;;; Autoload and prepare some org modules
4253 ;; Some table stuff that needs to be defined here, because it is used
4254 ;; by the functions setting up org-mode or checking for table context.
4256 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4257 "Detect an org-type or table-type table.")
4258 (defconst org-table-line-regexp "^[ \t]*|"
4259 "Detect an org-type table line.")
4260 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4261 "Detect an org-type table line.")
4262 (defconst org-table-hline-regexp "^[ \t]*|-"
4263 "Detect an org-type table hline.")
4264 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4265 "Detect a table-type table hline.")
4266 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4267 "Detect the first line outside a table when searching from within it.
4268 This works for both table types.")
4270 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4271 "Detect a #+TBLFM line.")
4273 ;;;###autoload
4274 (defun turn-on-orgtbl ()
4275 "Unconditionally turn on `orgtbl-mode'."
4276 (require 'org-table)
4277 (orgtbl-mode 1))
4279 (defun org-at-table-p (&optional table-type)
4280 "Return t if the cursor is inside an org-type table.
4281 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4282 (if org-enable-table-editor
4283 (save-excursion
4284 (beginning-of-line 1)
4285 (looking-at (if table-type org-table-any-line-regexp
4286 org-table-line-regexp)))
4287 nil))
4288 (defsubst org-table-p () (org-at-table-p))
4290 (defun org-at-table.el-p ()
4291 "Return t if and only if we are at a table.el table."
4292 (and (org-at-table-p 'any)
4293 (save-excursion
4294 (goto-char (org-table-begin 'any))
4295 (looking-at org-table1-hline-regexp))))
4297 (defun org-table-recognize-table.el ()
4298 "If there is a table.el table nearby, recognize it and move into it."
4299 (if org-table-tab-recognizes-table.el
4300 (if (org-at-table.el-p)
4301 (progn
4302 (beginning-of-line 1)
4303 (if (looking-at org-table-dataline-regexp)
4305 (if (looking-at org-table1-hline-regexp)
4306 (progn
4307 (beginning-of-line 2)
4308 (if (looking-at org-table-any-border-regexp)
4309 (beginning-of-line -1)))))
4310 (if (re-search-forward "|" (org-table-end t) t)
4311 (progn
4312 (require 'table)
4313 (if (table--at-cell-p (point))
4315 (message "recognizing table.el table...")
4316 (table-recognize-table)
4317 (message "recognizing table.el table...done")))
4318 (error "This should not happen"))
4320 nil)
4321 nil))
4323 (defun org-at-table-hline-p ()
4324 "Return t if the cursor is inside a hline in a table."
4325 (if org-enable-table-editor
4326 (save-excursion
4327 (beginning-of-line 1)
4328 (looking-at org-table-hline-regexp))
4329 nil))
4331 (defun org-table-map-tables (function &optional quietly)
4332 "Apply FUNCTION to the start of all tables in the buffer."
4333 (save-excursion
4334 (save-restriction
4335 (widen)
4336 (goto-char (point-min))
4337 (while (re-search-forward org-table-any-line-regexp nil t)
4338 (unless quietly
4339 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4340 (beginning-of-line 1)
4341 (when (and (looking-at org-table-line-regexp)
4342 ;; Exclude tables in src/example/verbatim/clocktable blocks
4343 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4344 (save-excursion (funcall function))
4345 (or (looking-at org-table-line-regexp)
4346 (forward-char 1)))
4347 (re-search-forward org-table-any-border-regexp nil 1))))
4348 (unless quietly (message "Mapping tables: done")))
4350 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4351 (declare-function org-clock-update-mode-line "org-clock" ())
4352 (declare-function org-resolve-clocks "org-clock"
4353 (&optional also-non-dangling-p prompt last-valid))
4355 (defun org-at-TBLFM-p (&optional pos)
4356 "Return t when point (or POS) is in #+TBLFM line."
4357 (save-excursion
4358 (let ((pos pos)))
4359 (goto-char (or pos (point)))
4360 (beginning-of-line 1)
4361 (looking-at org-TBLFM-regexp)))
4363 (defvar org-clock-start-time)
4364 (defvar org-clock-marker (make-marker)
4365 "Marker recording the last clock-in.")
4366 (defvar org-clock-hd-marker (make-marker)
4367 "Marker recording the last clock-in, but the headline position.")
4368 (defvar org-clock-heading ""
4369 "The heading of the current clock entry.")
4370 (defun org-clock-is-active ()
4371 "Return the buffer where the clock is currently running.
4372 Return nil if no clock is running."
4373 (marker-buffer org-clock-marker))
4375 (defun org-check-running-clock ()
4376 "Check if the current buffer contains the running clock.
4377 If yes, offer to stop it and to save the buffer with the changes."
4378 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4379 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4380 (buffer-name))))
4381 (org-clock-out)
4382 (when (y-or-n-p "Save changed buffer?")
4383 (save-buffer))))
4385 (defun org-clocktable-try-shift (dir n)
4386 "Check if this line starts a clock table, if yes, shift the time block."
4387 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4388 (org-clocktable-shift dir n)))
4390 ;;;###autoload
4391 (defun org-clock-persistence-insinuate ()
4392 "Set up hooks for clock persistence."
4393 (require 'org-clock)
4394 (add-hook 'org-mode-hook 'org-clock-load)
4395 (add-hook 'kill-emacs-hook 'org-clock-save))
4397 (defgroup org-archive nil
4398 "Options concerning archiving in Org-mode."
4399 :tag "Org Archive"
4400 :group 'org-structure)
4402 (defcustom org-archive-location "%s_archive::"
4403 "The location where subtrees should be archived.
4405 The value of this variable is a string, consisting of two parts,
4406 separated by a double-colon. The first part is a filename and
4407 the second part is a headline.
4409 When the filename is omitted, archiving happens in the same file.
4410 %s in the filename will be replaced by the current file
4411 name (without the directory part). Archiving to a different file
4412 is useful to keep archived entries from contributing to the
4413 Org-mode Agenda.
4415 The archived entries will be filed as subtrees of the specified
4416 headline. When the headline is omitted, the subtrees are simply
4417 filed away at the end of the file, as top-level entries. Also in
4418 the heading you can use %s to represent the file name, this can be
4419 useful when using the same archive for a number of different files.
4421 Here are a few examples:
4422 \"%s_archive::\"
4423 If the current file is Projects.org, archive in file
4424 Projects.org_archive, as top-level trees. This is the default.
4426 \"::* Archived Tasks\"
4427 Archive in the current file, under the top-level headline
4428 \"* Archived Tasks\".
4430 \"~/org/archive.org::\"
4431 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4433 \"~/org/archive.org::* From %s\"
4434 Archive in file ~/org/archive.org (absolute path), under headlines
4435 \"From FILENAME\" where file name is the current file name.
4437 \"~/org/datetree.org::datetree/* Finished Tasks\"
4438 The \"datetree/\" string is special, signifying to archive
4439 items to the datetree. Items are placed in either the CLOSED
4440 date of the item, or the current date if there is no CLOSED date.
4441 The heading will be a subentry to the current date. There doesn't
4442 need to be a heading, but there always needs to be a slash after
4443 datetree. For example, to store archived items directly in the
4444 datetree, use \"~/org/datetree.org::datetree/\".
4446 \"basement::** Finished Tasks\"
4447 Archive in file ./basement (relative path), as level 3 trees
4448 below the level 2 heading \"** Finished Tasks\".
4450 You may set this option on a per-file basis by adding to the buffer a
4451 line like
4453 #+ARCHIVE: basement::** Finished Tasks
4455 You may also define it locally for a subtree by setting an ARCHIVE property
4456 in the entry. If such a property is found in an entry, or anywhere up
4457 the hierarchy, it will be used."
4458 :group 'org-archive
4459 :type 'string)
4461 (defcustom org-archive-tag "ARCHIVE"
4462 "The tag that marks a subtree as archived.
4463 An archived subtree does not open during visibility cycling, and does
4464 not contribute to the agenda listings.
4465 After changing this, font-lock must be restarted in the relevant buffers to
4466 get the proper fontification."
4467 :group 'org-archive
4468 :group 'org-keywords
4469 :type 'string)
4471 (defcustom org-agenda-skip-archived-trees t
4472 "Non-nil means the agenda will skip any items located in archived trees.
4473 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4474 variable is no longer recommended, you should leave it at the value t.
4475 Instead, use the key `v' to cycle the archives-mode in the agenda."
4476 :group 'org-archive
4477 :group 'org-agenda-skip
4478 :type 'boolean)
4480 (defcustom org-columns-skip-archived-trees t
4481 "Non-nil means ignore archived trees when creating column view."
4482 :group 'org-archive
4483 :group 'org-properties
4484 :type 'boolean)
4486 (defcustom org-cycle-open-archived-trees nil
4487 "Non-nil means `org-cycle' will open archived trees.
4488 An archived tree is a tree marked with the tag ARCHIVE.
4489 When nil, archived trees will stay folded. You can still open them with
4490 normal outline commands like `show-all', but not with the cycling commands."
4491 :group 'org-archive
4492 :group 'org-cycle
4493 :type 'boolean)
4495 (defcustom org-sparse-tree-open-archived-trees nil
4496 "Non-nil means sparse tree construction shows matches in archived trees.
4497 When nil, matches in these trees are highlighted, but the trees are kept in
4498 collapsed state."
4499 :group 'org-archive
4500 :group 'org-sparse-trees
4501 :type 'boolean)
4503 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4504 "The default date type when building a sparse tree.
4505 When this is nil, a date is a scheduled or a deadline timestamp.
4506 Otherwise, these types are allowed:
4508 all: all timestamps
4509 active: only active timestamps (<...>)
4510 inactive: only inactive timestamps (<...)
4511 scheduled: only scheduled timestamps
4512 deadline: only deadline timestamps"
4513 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4514 (const :tag "All timestamps" all)
4515 (const :tag "Only active timestamps" active)
4516 (const :tag "Only inactive timestamps" inactive)
4517 (const :tag "Only scheduled timestamps" scheduled)
4518 (const :tag "Only deadline timestamps" deadline)
4519 (const :tag "Only closed timestamps" closed))
4520 :version "24.3"
4521 :group 'org-sparse-trees)
4523 (defun org-cycle-hide-archived-subtrees (state)
4524 "Re-hide all archived subtrees after a visibility state change."
4525 (when (and (not org-cycle-open-archived-trees)
4526 (not (memq state '(overview folded))))
4527 (save-excursion
4528 (let* ((globalp (memq state '(contents all)))
4529 (beg (if globalp (point-min) (point)))
4530 (end (if globalp (point-max) (org-end-of-subtree t))))
4531 (org-hide-archived-subtrees beg end)
4532 (goto-char beg)
4533 (if (looking-at (concat ".*:" org-archive-tag ":"))
4534 (message "%s" (substitute-command-keys
4535 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4537 (defun org-force-cycle-archived ()
4538 "Cycle subtree even if it is archived."
4539 (interactive)
4540 (setq this-command 'org-cycle)
4541 (let ((org-cycle-open-archived-trees t))
4542 (call-interactively 'org-cycle)))
4544 (defun org-hide-archived-subtrees (beg end)
4545 "Re-hide all archived subtrees after a visibility state change."
4546 (save-excursion
4547 (let* ((re (concat ":" org-archive-tag ":")))
4548 (goto-char beg)
4549 (while (re-search-forward re end t)
4550 (when (org-at-heading-p)
4551 (org-flag-subtree t)
4552 (org-end-of-subtree t))))))
4554 (declare-function outline-end-of-heading "outline" ())
4555 (declare-function outline-flag-region "outline" (from to flag))
4556 (defun org-flag-subtree (flag)
4557 (save-excursion
4558 (org-back-to-heading t)
4559 (outline-end-of-heading)
4560 (outline-flag-region (point)
4561 (progn (org-end-of-subtree t) (point))
4562 flag)))
4564 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4566 ;; Declare Column View Code
4568 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4569 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4570 (declare-function org-columns-compute "org-colview" (property))
4572 ;; Declare ID code
4574 (declare-function org-id-store-link "org-id")
4575 (declare-function org-id-locations-load "org-id")
4576 (declare-function org-id-locations-save "org-id")
4577 (defvar org-id-track-globally)
4579 ;;; Variables for pre-computed regular expressions, all buffer local
4581 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4582 "Matches first line of a hidden block.")
4583 (make-variable-buffer-local 'org-drawer-regexp)
4584 (defvar org-todo-regexp nil
4585 "Matches any of the TODO state keywords.")
4586 (make-variable-buffer-local 'org-todo-regexp)
4587 (defvar org-not-done-regexp nil
4588 "Matches any of the TODO state keywords except the last one.")
4589 (make-variable-buffer-local 'org-not-done-regexp)
4590 (defvar org-not-done-heading-regexp nil
4591 "Matches a TODO headline that is not done.")
4592 (make-variable-buffer-local 'org-not-done-regexp)
4593 (defvar org-todo-line-regexp nil
4594 "Matches a headline and puts TODO state into group 2 if present.")
4595 (make-variable-buffer-local 'org-todo-line-regexp)
4596 (defvar org-complex-heading-regexp nil
4597 "Matches a headline and puts everything into groups:
4598 group 1: the stars
4599 group 2: The todo keyword, maybe
4600 group 3: Priority cookie
4601 group 4: True headline
4602 group 5: Tags")
4603 (make-variable-buffer-local 'org-complex-heading-regexp)
4604 (defvar org-complex-heading-regexp-format nil
4605 "Printf format to make regexp to match an exact headline.
4606 This regexp will match the headline of any node which has the
4607 exact headline text that is put into the format, but may have any
4608 TODO state, priority and tags.")
4609 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4610 (defvar org-todo-line-tags-regexp nil
4611 "Matches a headline and puts TODO state into group 2 if present.
4612 Also put tags into group 4 if tags are present.")
4613 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4614 (defvar org-ds-keyword-length 12
4615 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4616 (make-variable-buffer-local 'org-ds-keyword-length)
4617 (defvar org-deadline-regexp nil
4618 "Matches the DEADLINE keyword.")
4619 (make-variable-buffer-local 'org-deadline-regexp)
4620 (defvar org-deadline-time-regexp nil
4621 "Matches the DEADLINE keyword together with a time stamp.")
4622 (make-variable-buffer-local 'org-deadline-time-regexp)
4623 (defvar org-deadline-time-hour-regexp nil
4624 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4625 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4626 (defvar org-deadline-line-regexp nil
4627 "Matches the DEADLINE keyword and the rest of the line.")
4628 (make-variable-buffer-local 'org-deadline-line-regexp)
4629 (defvar org-scheduled-regexp nil
4630 "Matches the SCHEDULED keyword.")
4631 (make-variable-buffer-local 'org-scheduled-regexp)
4632 (defvar org-scheduled-time-regexp nil
4633 "Matches the SCHEDULED keyword together with a time stamp.")
4634 (make-variable-buffer-local 'org-scheduled-time-regexp)
4635 (defvar org-scheduled-time-hour-regexp nil
4636 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4637 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4638 (defvar org-closed-time-regexp nil
4639 "Matches the CLOSED keyword together with a time stamp.")
4640 (make-variable-buffer-local 'org-closed-time-regexp)
4642 (defvar org-keyword-time-regexp nil
4643 "Matches any of the 4 keywords, together with the time stamp.")
4644 (make-variable-buffer-local 'org-keyword-time-regexp)
4645 (defvar org-keyword-time-not-clock-regexp nil
4646 "Matches any of the 3 keywords, together with the time stamp.")
4647 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4648 (defvar org-maybe-keyword-time-regexp nil
4649 "Matches a timestamp, possibly preceded by a keyword.")
4650 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4651 (defvar org-all-time-keywords nil
4652 "List of time keywords.")
4653 (make-variable-buffer-local 'org-all-time-keywords)
4655 (defconst org-plain-time-of-day-regexp
4656 (concat
4657 "\\(\\<[012]?[0-9]"
4658 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4659 "\\(--?"
4660 "\\(\\<[012]?[0-9]"
4661 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4662 "\\)?")
4663 "Regular expression to match a plain time or time range.
4664 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4665 groups carry important information:
4666 0 the full match
4667 1 the first time, range or not
4668 8 the second time, if it is a range.")
4670 (defconst org-plain-time-extension-regexp
4671 (concat
4672 "\\(\\<[012]?[0-9]"
4673 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4674 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4675 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4676 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4677 groups carry important information:
4678 0 the full match
4679 7 hours of duration
4680 9 minutes of duration")
4682 (defconst org-stamp-time-of-day-regexp
4683 (concat
4684 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4685 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4686 "\\(--?"
4687 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4688 "Regular expression to match a timestamp time or time range.
4689 After a match, the following groups carry important information:
4690 0 the full match
4691 1 date plus weekday, for back referencing to make sure both times are on the same day
4692 2 the first time, range or not
4693 4 the second time, if it is a range.")
4695 (defconst org-startup-options
4696 '(("fold" org-startup-folded t)
4697 ("overview" org-startup-folded t)
4698 ("nofold" org-startup-folded nil)
4699 ("showall" org-startup-folded nil)
4700 ("showeverything" org-startup-folded showeverything)
4701 ("content" org-startup-folded content)
4702 ("indent" org-startup-indented t)
4703 ("noindent" org-startup-indented nil)
4704 ("hidestars" org-hide-leading-stars t)
4705 ("showstars" org-hide-leading-stars nil)
4706 ("odd" org-odd-levels-only t)
4707 ("oddeven" org-odd-levels-only nil)
4708 ("align" org-startup-align-all-tables t)
4709 ("noalign" org-startup-align-all-tables nil)
4710 ("inlineimages" org-startup-with-inline-images t)
4711 ("noinlineimages" org-startup-with-inline-images nil)
4712 ("latexpreview" org-startup-with-latex-preview t)
4713 ("nolatexpreview" org-startup-with-latex-preview nil)
4714 ("customtime" org-display-custom-times t)
4715 ("logdone" org-log-done time)
4716 ("lognotedone" org-log-done note)
4717 ("nologdone" org-log-done nil)
4718 ("lognoteclock-out" org-log-note-clock-out t)
4719 ("nolognoteclock-out" org-log-note-clock-out nil)
4720 ("logrepeat" org-log-repeat state)
4721 ("lognoterepeat" org-log-repeat note)
4722 ("logdrawer" org-log-into-drawer t)
4723 ("nologdrawer" org-log-into-drawer nil)
4724 ("logstatesreversed" org-log-states-order-reversed t)
4725 ("nologstatesreversed" org-log-states-order-reversed nil)
4726 ("nologrepeat" org-log-repeat nil)
4727 ("logreschedule" org-log-reschedule time)
4728 ("lognotereschedule" org-log-reschedule note)
4729 ("nologreschedule" org-log-reschedule nil)
4730 ("logredeadline" org-log-redeadline time)
4731 ("lognoteredeadline" org-log-redeadline note)
4732 ("nologredeadline" org-log-redeadline nil)
4733 ("logrefile" org-log-refile time)
4734 ("lognoterefile" org-log-refile note)
4735 ("nologrefile" org-log-refile nil)
4736 ("fninline" org-footnote-define-inline t)
4737 ("nofninline" org-footnote-define-inline nil)
4738 ("fnlocal" org-footnote-section nil)
4739 ("fnauto" org-footnote-auto-label t)
4740 ("fnprompt" org-footnote-auto-label nil)
4741 ("fnconfirm" org-footnote-auto-label confirm)
4742 ("fnplain" org-footnote-auto-label plain)
4743 ("fnadjust" org-footnote-auto-adjust t)
4744 ("nofnadjust" org-footnote-auto-adjust nil)
4745 ("constcgs" constants-unit-system cgs)
4746 ("constSI" constants-unit-system SI)
4747 ("noptag" org-tag-persistent-alist nil)
4748 ("hideblocks" org-hide-block-startup t)
4749 ("nohideblocks" org-hide-block-startup nil)
4750 ("beamer" org-startup-with-beamer-mode t)
4751 ("entitiespretty" org-pretty-entities t)
4752 ("entitiesplain" org-pretty-entities nil))
4753 "Variable associated with STARTUP options for org-mode.
4754 Each element is a list of three items: the startup options (as written
4755 in the #+STARTUP line), the corresponding variable, and the value to set
4756 this variable to if the option is found. An optional forth element PUSH
4757 means to push this value onto the list in the variable.")
4759 (defun org-update-property-plist (key val props)
4760 "Update PROPS with KEY and VAL."
4761 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4762 (key (if appending (substring key 0 (- (length key) 1)) key))
4763 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4764 (previous (cdr (assoc key props))))
4765 (if appending
4766 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4767 (cons (cons key val) remainder))))
4769 (defconst org-block-regexp
4770 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4771 "Regular expression for hiding blocks.")
4772 (defconst org-heading-keyword-regexp-format
4773 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4774 "Printf format for a regexp matching a headline with some keyword.
4775 This regexp will match the headline of any node which has the
4776 exact keyword that is put into the format. The keyword isn't in
4777 any group by default, but the stars and the body are.")
4778 (defconst org-heading-keyword-maybe-regexp-format
4779 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4780 "Printf format for a regexp matching a headline, possibly with some keyword.
4781 This regexp can match any headline with the specified keyword, or
4782 without a keyword. The keyword isn't in any group by default,
4783 but the stars and the body are.")
4785 (defcustom org-group-tags t
4786 "When non-nil (the default), use group tags.
4787 This can be turned on/off through `org-toggle-tags-groups'."
4788 :group 'org-tags
4789 :group 'org-startup
4790 :type 'boolean)
4792 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4794 (defun org-toggle-tags-groups ()
4795 "Toggle support for group tags.
4796 Support for group tags is controlled by the option
4797 `org-group-tags', which is non-nil by default."
4798 (interactive)
4799 (setq org-group-tags (not org-group-tags))
4800 (cond ((and (derived-mode-p 'org-agenda-mode)
4801 org-group-tags)
4802 (org-agenda-redo))
4803 ((derived-mode-p 'org-mode)
4804 (let ((org-inhibit-startup t)) (org-mode))))
4805 (message "Groups tags support has been turned %s"
4806 (if org-group-tags "on" "off")))
4808 (defun org-set-regexps-and-options-for-tags ()
4809 "Precompute variables used for tags."
4810 (when (derived-mode-p 'org-mode)
4811 (org-set-local 'org-file-tags nil)
4812 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4813 (splitre "[ \t]+")
4814 (start 0)
4815 tags ftags key value)
4816 (save-excursion
4817 (save-restriction
4818 (widen)
4819 (goto-char (point-min))
4820 (while (re-search-forward re nil t)
4821 (setq key (upcase (org-match-string-no-properties 1))
4822 value (org-match-string-no-properties 2))
4823 (if (stringp value) (setq value (org-trim value)))
4824 (cond
4825 ((equal key "TAGS")
4826 (setq tags (append tags (if tags '("\\n") nil)
4827 (org-split-string value splitre))))
4828 ((equal key "FILETAGS")
4829 (when (string-match "\\S-" value)
4830 (setq ftags
4831 (append
4832 ftags
4833 (apply 'append
4834 (mapcar (lambda (x) (org-split-string x ":"))
4835 (org-split-string value)))))))))))
4836 ;; Process the file tags.
4837 (and ftags (org-set-local 'org-file-tags
4838 (mapcar 'org-add-prop-inherited ftags)))
4839 (org-set-local 'org-tag-groups-alist nil)
4840 ;; Process the tags.
4841 (when (and (not tags) org-tag-alist)
4842 (setq tags
4843 (mapcar
4844 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4845 ((eq (car tg) :endgroup) "}")
4846 ((eq (car tg) :grouptags) ":")
4847 ((eq (car tg) :newline) "\n")
4848 (t (concat (car tg)
4849 (if (characterp (cdr tg))
4850 (format "(%s)" (char-to-string (cdr tg))) "")))))
4851 org-tag-alist)))
4852 (let (e tgs g)
4853 (while (setq e (pop tags))
4854 (cond
4855 ((equal e "{")
4856 (progn (push '(:startgroup) tgs)
4857 (when (equal (nth 1 tags) ":")
4858 (push (list (replace-regexp-in-string
4859 "(.+)$" "" (nth 0 tags)))
4860 org-tag-groups-alist)
4861 (setq g 0))))
4862 ((equal e ":") (push '(:grouptags) tgs))
4863 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4864 ((equal e "\\n") (push '(:newline) tgs))
4865 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4866 (push (cons (match-string 1 e)
4867 (string-to-char (match-string 2 e))) tgs)
4868 (if (and g (> g 0))
4869 (setcar org-tag-groups-alist
4870 (append (car org-tag-groups-alist)
4871 (list (match-string 1 e)))))
4872 (if g (setq g (1+ g))))
4873 (t (push (list e) tgs)
4874 (if (and g (> g 0))
4875 (setcar org-tag-groups-alist
4876 (append (car org-tag-groups-alist) (list e))))
4877 (if g (setq g (1+ g))))))
4878 (org-set-local 'org-tag-alist nil)
4879 (while (setq e (pop tgs))
4880 (or (and (stringp (car e))
4881 (assoc (car e) org-tag-alist))
4882 (push e org-tag-alist)))
4883 ;; Return a list with tag variables
4884 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4886 (defvar org-ota nil)
4887 (defun org-set-regexps-and-options ()
4888 "Precompute regular expressions used in the current buffer."
4889 (when (derived-mode-p 'org-mode)
4890 (org-set-local 'org-todo-kwd-alist nil)
4891 (org-set-local 'org-todo-key-alist nil)
4892 (org-set-local 'org-todo-key-trigger nil)
4893 (org-set-local 'org-todo-keywords-1 nil)
4894 (org-set-local 'org-done-keywords nil)
4895 (org-set-local 'org-todo-heads nil)
4896 (org-set-local 'org-todo-sets nil)
4897 (org-set-local 'org-todo-log-states nil)
4898 (org-set-local 'org-file-properties nil)
4899 (let ((re (org-make-options-regexp
4900 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4901 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4902 "SETUPFILE" "OPTIONS")
4903 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4904 (splitre "[ \t]+")
4905 (scripts org-use-sub-superscripts)
4906 kwds kws0 kwsa key log value cat arch const links hw dws
4907 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4908 (start 0))
4909 (save-excursion
4910 (save-restriction
4911 (widen)
4912 (goto-char (point-min))
4913 (while
4914 (or (and
4915 ext-setup-or-nil
4916 (not org-ota)
4917 (let (ret)
4918 (with-temp-buffer
4919 (insert ext-setup-or-nil)
4920 (let ((major-mode 'org-mode) org-ota)
4921 (setq ret (save-match-data
4922 (org-set-regexps-and-options-for-tags)))))
4923 ;; Append setupfile tags to existing tags
4924 (setq org-ota t)
4925 (setq org-file-tags
4926 (delq nil (append org-file-tags (nth 0 ret)))
4927 org-tag-alist
4928 (delq nil (append org-tag-alist (nth 1 ret)))
4929 org-tag-groups-alist
4930 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4931 (and ext-setup-or-nil
4932 (string-match re ext-setup-or-nil start)
4933 (setq start (match-end 0)))
4934 (and (setq ext-setup-or-nil nil start 0)
4935 (re-search-forward re nil t)))
4936 (setq key (upcase (match-string 1 ext-setup-or-nil))
4937 value (org-match-string-no-properties 2 ext-setup-or-nil))
4938 (if (stringp value) (setq value (org-trim value)))
4939 (cond
4940 ((equal key "CATEGORY")
4941 (setq cat value))
4942 ((member key '("SEQ_TODO" "TODO"))
4943 (push (cons 'sequence (org-split-string value splitre)) kwds))
4944 ((equal key "TYP_TODO")
4945 (push (cons 'type (org-split-string value splitre)) kwds))
4946 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4947 ;; general TODO-like setup
4948 (push (cons (intern (downcase (match-string 1 key)))
4949 (org-split-string value splitre)) kwds))
4950 ((equal key "COLUMNS")
4951 (org-set-local 'org-columns-default-format value))
4952 ((equal key "LINK")
4953 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4954 (push (cons (match-string 1 value)
4955 (org-trim (match-string 2 value)))
4956 links)))
4957 ((equal key "PRIORITIES")
4958 (setq prio (org-split-string value " +")))
4959 ((equal key "PROPERTY")
4960 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4961 (setq props (org-update-property-plist (match-string 1 value)
4962 (match-string 2 value)
4963 props))))
4964 ((equal key "DRAWERS")
4965 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4966 ((equal key "CONSTANTS")
4967 (org-table-set-constants))
4968 ((equal key "STARTUP")
4969 (let ((opts (org-split-string value splitre))
4970 l var val)
4971 (while (setq l (pop opts))
4972 (when (setq l (assoc l org-startup-options))
4973 (setq var (nth 1 l) val (nth 2 l))
4974 (if (not (nth 3 l))
4975 (set (make-local-variable var) val)
4976 (if (not (listp (symbol-value var)))
4977 (set (make-local-variable var) nil))
4978 (set (make-local-variable var) (symbol-value var))
4979 (add-to-list var val))))))
4980 ((equal key "ARCHIVE")
4981 (setq arch value)
4982 (remove-text-properties 0 (length arch)
4983 '(face t fontified t) arch))
4984 ((equal key "OPTIONS")
4985 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4986 (setq scripts (read (match-string 2 value)))))
4987 ((and (equal key "SETUPFILE")
4988 ;; Prevent checking in Gnus messages
4989 (not buffer-read-only))
4990 (setq setup-contents (org-file-contents
4991 (expand-file-name
4992 (org-remove-double-quotes value))
4993 'noerror))
4994 (if (not ext-setup-or-nil)
4995 (setq ext-setup-or-nil setup-contents start 0)
4996 (setq ext-setup-or-nil
4997 (concat (substring ext-setup-or-nil 0 start)
4998 "\n" setup-contents "\n"
4999 (substring ext-setup-or-nil start)))))))
5000 ;; search for property blocks
5001 (goto-char (point-min))
5002 (while (re-search-forward org-block-regexp nil t)
5003 (when (equal "PROPERTY" (upcase (match-string 1)))
5004 (setq value (replace-regexp-in-string
5005 "[\n\r]" " " (match-string 4)))
5006 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
5007 (setq props (org-update-property-plist (match-string 1 value)
5008 (match-string 2 value)
5009 props)))))))
5010 (org-set-local 'org-use-sub-superscripts scripts)
5011 (when cat
5012 (org-set-local 'org-category (intern cat))
5013 (push (cons "CATEGORY" cat) props))
5014 (when prio
5015 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5016 (setq prio (mapcar 'string-to-char prio))
5017 (org-set-local 'org-highest-priority (nth 0 prio))
5018 (org-set-local 'org-lowest-priority (nth 1 prio))
5019 (org-set-local 'org-default-priority (nth 2 prio)))
5020 (and props (org-set-local 'org-file-properties (nreverse props)))
5021 (and drawers (org-set-local 'org-drawers drawers))
5022 (and arch (org-set-local 'org-archive-location arch))
5023 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5024 ;; Process the TODO keywords
5025 (unless kwds
5026 ;; Use the global values as if they had been given locally.
5027 (setq kwds (default-value 'org-todo-keywords))
5028 (if (stringp (car kwds))
5029 (setq kwds (list (cons org-todo-interpretation
5030 (default-value 'org-todo-keywords)))))
5031 (setq kwds (reverse kwds)))
5032 (setq kwds (nreverse kwds))
5033 (let (inter kws kw)
5034 (while (setq kws (pop kwds))
5035 (let ((kws (or
5036 (run-hook-with-args-until-success
5037 'org-todo-setup-filter-hook kws)
5038 kws)))
5039 (setq inter (pop kws) sep (member "|" kws)
5040 kws0 (delete "|" (copy-sequence kws))
5041 kwsa nil
5042 kws1 (mapcar
5043 (lambda (x)
5044 ;; 1 2
5045 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5046 (progn
5047 (setq kw (match-string 1 x)
5048 key (and (match-end 2) (match-string 2 x))
5049 log (org-extract-log-state-settings x))
5050 (push (cons kw (and key (string-to-char key))) kwsa)
5051 (and log (push log org-todo-log-states))
5053 (error "Invalid TODO keyword %s" x)))
5054 kws0)
5055 kwsa (if kwsa (append '((:startgroup))
5056 (nreverse kwsa)
5057 '((:endgroup))))
5058 hw (car kws1)
5059 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5060 tail (list inter hw (car dws) (org-last dws))))
5061 (add-to-list 'org-todo-heads hw 'append)
5062 (push kws1 org-todo-sets)
5063 (setq org-done-keywords (append org-done-keywords dws nil))
5064 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5065 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5066 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5067 (setq org-todo-sets (nreverse org-todo-sets)
5068 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5069 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5070 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5071 ;; Compute the regular expressions and other local variables.
5072 ;; Using `org-outline-regexp-bol' would complicate them much,
5073 ;; because of the fixed white space at the end of that string.
5074 (if (not org-done-keywords)
5075 (setq org-done-keywords (and org-todo-keywords-1
5076 (list (org-last org-todo-keywords-1)))))
5077 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5078 (length org-scheduled-string)
5079 (length org-clock-string)
5080 (length org-closed-string)))
5081 org-drawer-regexp
5082 (concat "^[ \t]*:\\("
5083 (mapconcat 'regexp-quote org-drawers "\\|")
5084 "\\):[ \t]*$")
5085 org-not-done-keywords
5086 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5087 org-todo-regexp
5088 (concat "\\("
5089 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5090 "\\)")
5091 org-not-done-regexp
5092 (concat "\\("
5093 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5094 "\\)")
5095 org-not-done-heading-regexp
5096 (format org-heading-keyword-regexp-format org-not-done-regexp)
5097 org-todo-line-regexp
5098 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5099 org-complex-heading-regexp
5100 (concat "^\\(\\*+\\)"
5101 "\\(?: +" org-todo-regexp "\\)?"
5102 "\\(?: +\\(\\[#.\\]\\)\\)?"
5103 "\\(?: +\\(.*?\\)\\)??"
5104 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5105 "[ \t]*$")
5106 org-complex-heading-regexp-format
5107 (concat "^\\(\\*+\\)"
5108 "\\(?: +" org-todo-regexp "\\)?"
5109 "\\(?: +\\(\\[#.\\]\\)\\)?"
5110 "\\(?: +"
5111 ;; Stats cookies can be stuck to body.
5112 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5113 "\\(%s\\)"
5114 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5115 "\\)"
5116 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5117 "[ \t]*$")
5118 org-todo-line-tags-regexp
5119 (concat "^\\(\\*+\\)"
5120 "\\(?: +" org-todo-regexp "\\)?"
5121 "\\(?: +\\(.*?\\)\\)??"
5122 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5123 "[ \t]*$")
5124 org-deadline-regexp (concat "\\<" org-deadline-string)
5125 org-deadline-time-regexp
5126 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5127 org-deadline-time-hour-regexp
5128 (concat "\\<" org-deadline-string
5129 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5130 org-deadline-line-regexp
5131 (concat "\\<\\(" org-deadline-string "\\).*")
5132 org-scheduled-regexp
5133 (concat "\\<" org-scheduled-string)
5134 org-scheduled-time-regexp
5135 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5136 org-scheduled-time-hour-regexp
5137 (concat "\\<" org-scheduled-string
5138 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5139 org-closed-time-regexp
5140 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5141 org-keyword-time-regexp
5142 (concat "\\<\\(" org-scheduled-string
5143 "\\|" org-deadline-string
5144 "\\|" org-closed-string
5145 "\\|" org-clock-string "\\)"
5146 " *[[<]\\([^]>]+\\)[]>]")
5147 org-keyword-time-not-clock-regexp
5148 (concat "\\<\\(" org-scheduled-string
5149 "\\|" org-deadline-string
5150 "\\|" org-closed-string
5151 "\\)"
5152 " *[[<]\\([^]>]+\\)[]>]")
5153 org-maybe-keyword-time-regexp
5154 (concat "\\(\\<\\(" org-scheduled-string
5155 "\\|" org-deadline-string
5156 "\\|" org-closed-string
5157 "\\|" org-clock-string "\\)\\)?"
5158 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5159 org-all-time-keywords
5160 (mapcar (lambda (w) (substring w 0 -1))
5161 (list org-scheduled-string org-deadline-string
5162 org-clock-string org-closed-string)))
5163 (setq org-ota nil)
5164 (org-compute-latex-and-related-regexp))))
5166 (defun org-file-contents (file &optional noerror)
5167 "Return the contents of FILE, as a string."
5168 (if (or (not file) (not (file-readable-p file)))
5169 (if (not noerror)
5170 (error "Cannot read file \"%s\"" file)
5171 (message "Cannot read file \"%s\"" file)
5173 (with-temp-buffer
5174 (insert-file-contents file)
5175 (buffer-string))))
5177 (defun org-extract-log-state-settings (x)
5178 "Extract the log state setting from a TODO keyword string.
5179 This will extract info from a string like \"WAIT(w@/!)\"."
5180 (let (kw key log1 log2)
5181 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5182 (setq kw (match-string 1 x)
5183 key (and (match-end 2) (match-string 2 x))
5184 log1 (and (match-end 3) (match-string 3 x))
5185 log2 (and (match-end 4) (match-string 4 x)))
5186 (and (or log1 log2)
5187 (list kw
5188 (and log1 (if (equal log1 "!") 'time 'note))
5189 (and log2 (if (equal log2 "!") 'time 'note)))))))
5191 (defun org-remove-keyword-keys (list)
5192 "Remove a pair of parenthesis at the end of each string in LIST."
5193 (mapcar (lambda (x)
5194 (if (string-match "(.*)$" x)
5195 (substring x 0 (match-beginning 0))
5197 list))
5199 (defun org-assign-fast-keys (alist)
5200 "Assign fast keys to a keyword-key alist.
5201 Respect keys that are already there."
5202 (let (new e (alt ?0))
5203 (while (setq e (pop alist))
5204 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5205 (cdr e)) ;; Key already assigned.
5206 (push e new)
5207 (let ((clist (string-to-list (downcase (car e))))
5208 (used (append new alist)))
5209 (when (= (car clist) ?@)
5210 (pop clist))
5211 (while (and clist (rassoc (car clist) used))
5212 (pop clist))
5213 (unless clist
5214 (while (rassoc alt used)
5215 (incf alt)))
5216 (push (cons (car e) (or (car clist) alt)) new))))
5217 (nreverse new)))
5219 ;;; Some variables used in various places
5221 (defvar org-window-configuration nil
5222 "Used in various places to store a window configuration.")
5223 (defvar org-selected-window nil
5224 "Used in various places to store a window configuration.")
5225 (defvar org-finish-function nil
5226 "Function to be called when `C-c C-c' is used.
5227 This is for getting out of special buffers like capture.")
5230 ;; FIXME: Occasionally check by commenting these, to make sure
5231 ;; no other functions uses these, forgetting to let-bind them.
5232 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5233 (defvar org-last-state)
5234 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5236 ;; Defined somewhere in this file, but used before definition.
5237 (defvar org-entities) ;; defined in org-entities.el
5238 (defvar org-struct-menu)
5239 (defvar org-org-menu)
5240 (defvar org-tbl-menu)
5242 ;;;; Define the Org-mode
5244 ;; We use a before-change function to check if a table might need
5245 ;; an update.
5246 (defvar org-table-may-need-update t
5247 "Indicates that a table might need an update.
5248 This variable is set by `org-before-change-function'.
5249 `org-table-align' sets it back to nil.")
5250 (defun org-before-change-function (beg end)
5251 "Every change indicates that a table might need an update."
5252 (setq org-table-may-need-update t))
5253 (defvar org-mode-map)
5254 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5255 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5256 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5257 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5258 (defvar org-table-buffer-is-an nil)
5260 (defvar bidi-paragraph-direction)
5261 (defvar buffer-face-mode-face)
5263 (require 'outline)
5264 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5265 (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"))
5266 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5268 ;; Other stuff we need.
5269 (require 'time-date)
5270 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5271 (require 'easymenu)
5272 (require 'overlay)
5274 ;; (require 'org-macs) moved higher up in the file before it is first used
5275 (require 'org-entities)
5276 ;; (require 'org-compat) moved higher up in the file before it is first used
5277 (require 'org-faces)
5278 (require 'org-list)
5279 (require 'org-pcomplete)
5280 (require 'org-src)
5281 (require 'org-footnote)
5282 (require 'org-macro)
5284 ;; babel
5285 (require 'ob)
5287 ;;;###autoload
5288 (define-derived-mode org-mode outline-mode "Org"
5289 "Outline-based notes management and organizer, alias
5290 \"Carsten's outline-mode for keeping track of everything.\"
5292 Org-mode develops organizational tasks around a NOTES file which
5293 contains information about projects as plain text. Org-mode is
5294 implemented on top of outline-mode, which is ideal to keep the content
5295 of large files well structured. It supports ToDo items, deadlines and
5296 time stamps, which magically appear in the diary listing of the Emacs
5297 calendar. Tables are easily created with a built-in table editor.
5298 Plain text URL-like links connect to websites, emails (VM), Usenet
5299 messages (Gnus), BBDB entries, and any files related to the project.
5300 For printing and sharing of notes, an Org-mode file (or a part of it)
5301 can be exported as a structured ASCII or HTML file.
5303 The following commands are available:
5305 \\{org-mode-map}"
5307 ;; Get rid of Outline menus, they are not needed
5308 ;; Need to do this here because define-derived-mode sets up
5309 ;; the keymap so late. Still, it is a waste to call this each time
5310 ;; we switch another buffer into org-mode.
5311 (if (featurep 'xemacs)
5312 (when (boundp 'outline-mode-menu-heading)
5313 ;; Assume this is Greg's port, it uses easymenu
5314 (easy-menu-remove outline-mode-menu-heading)
5315 (easy-menu-remove outline-mode-menu-show)
5316 (easy-menu-remove outline-mode-menu-hide))
5317 (define-key org-mode-map [menu-bar headings] 'undefined)
5318 (define-key org-mode-map [menu-bar hide] 'undefined)
5319 (define-key org-mode-map [menu-bar show] 'undefined))
5321 (org-load-modules-maybe)
5322 (easy-menu-add org-org-menu)
5323 (easy-menu-add org-tbl-menu)
5324 (org-install-agenda-files-menu)
5325 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5326 (add-to-invisibility-spec '(org-cwidth))
5327 (add-to-invisibility-spec '(org-hide-block . t))
5328 (when (featurep 'xemacs)
5329 (org-set-local 'line-move-ignore-invisible t))
5330 (org-set-local 'outline-regexp org-outline-regexp)
5331 (org-set-local 'outline-level 'org-outline-level)
5332 (setq bidi-paragraph-direction 'left-to-right)
5333 (when (and org-ellipsis
5334 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5335 (fboundp 'make-glyph-code))
5336 (unless org-display-table
5337 (setq org-display-table (make-display-table)))
5338 (set-display-table-slot
5339 org-display-table 4
5340 (vconcat (mapcar
5341 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5342 org-ellipsis)))
5343 (if (stringp org-ellipsis) org-ellipsis "..."))))
5344 (setq buffer-display-table org-display-table))
5345 (org-set-regexps-and-options-for-tags)
5346 (org-set-regexps-and-options)
5347 (org-set-font-lock-defaults)
5348 (when (and org-tag-faces (not org-tags-special-faces-re))
5349 ;; tag faces set outside customize.... force initialization.
5350 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5351 ;; Calc embedded
5352 (org-set-local 'calc-embedded-open-mode "# ")
5353 ;; Modify a few syntax entries
5354 (modify-syntax-entry ?@ "w")
5355 (modify-syntax-entry ?\" "\"")
5356 (modify-syntax-entry ?\\ "_")
5357 (modify-syntax-entry ?~ "_")
5358 (if org-startup-truncated (setq truncate-lines t))
5359 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5360 (org-set-local 'font-lock-unfontify-region-function
5361 'org-unfontify-region)
5362 ;; Activate before-change-function
5363 (org-set-local 'org-table-may-need-update t)
5364 (org-add-hook 'before-change-functions 'org-before-change-function nil
5365 'local)
5366 ;; Check for running clock before killing a buffer
5367 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5368 ;; Initialize macros templates.
5369 (org-macro-initialize-templates)
5370 ;; Initialize radio targets.
5371 (org-update-radio-target-regexp)
5372 ;; Indentation.
5373 (org-set-local 'indent-line-function 'org-indent-line)
5374 (org-set-local 'indent-region-function 'org-indent-region)
5375 ;; Filling and auto-filling.
5376 (org-setup-filling)
5377 ;; Comments.
5378 (org-setup-comments-handling)
5379 ;; Beginning/end of defun
5380 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5381 (org-set-local 'end-of-defun-function 'org-forward-element)
5382 ;; Next error for sparse trees
5383 (org-set-local 'next-error-function 'org-occur-next-match)
5384 ;; Make sure dependence stuff works reliably, even for users who set it
5385 ;; too late :-(
5386 (if org-enforce-todo-dependencies
5387 (add-hook 'org-blocker-hook
5388 'org-block-todo-from-children-or-siblings-or-parent)
5389 (remove-hook 'org-blocker-hook
5390 'org-block-todo-from-children-or-siblings-or-parent))
5391 (if org-enforce-todo-checkbox-dependencies
5392 (add-hook 'org-blocker-hook
5393 'org-block-todo-from-checkboxes)
5394 (remove-hook 'org-blocker-hook
5395 'org-block-todo-from-checkboxes))
5397 ;; Align options lines
5398 (org-set-local
5399 'align-mode-rules-list
5400 '((org-in-buffer-settings
5401 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5402 (modes . '(org-mode)))))
5404 ;; Imenu
5405 (org-set-local 'imenu-create-index-function
5406 'org-imenu-get-tree)
5408 ;; Make isearch reveal context
5409 (if (or (featurep 'xemacs)
5410 (not (boundp 'outline-isearch-open-invisible-function)))
5411 ;; Emacs 21 and XEmacs make use of the hook
5412 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5413 ;; Emacs 22 deals with this through a special variable
5414 (org-set-local 'outline-isearch-open-invisible-function
5415 (lambda (&rest ignore) (org-show-context 'isearch)))
5416 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5418 ;; Setup the pcomplete hooks
5419 (set (make-local-variable 'pcomplete-command-completion-function)
5420 'org-pcomplete-initial)
5421 (set (make-local-variable 'pcomplete-command-name-function)
5422 'org-command-at-point)
5423 (set (make-local-variable 'pcomplete-default-completion-function)
5424 'ignore)
5425 (set (make-local-variable 'pcomplete-parse-arguments-function)
5426 'org-parse-arguments)
5427 (set (make-local-variable 'pcomplete-termination-string) "")
5428 (when (>= emacs-major-version 23)
5429 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5431 ;; If empty file that did not turn on org-mode automatically, make it to.
5432 (if (and org-insert-mode-line-in-empty-file
5433 (org-called-interactively-p 'any)
5434 (= (point-min) (point-max)))
5435 (insert "# -*- mode: org -*-\n\n"))
5436 (unless org-inhibit-startup
5437 (org-unmodified
5438 (and org-startup-with-beamer-mode (org-beamer-mode))
5439 (when org-startup-align-all-tables
5440 (org-table-map-tables 'org-table-align 'quietly))
5441 (when org-startup-with-inline-images
5442 (org-display-inline-images))
5443 (when org-startup-with-latex-preview
5444 (org-preview-latex-fragment))
5445 (unless org-inhibit-startup-visibility-stuff
5446 (org-set-startup-visibility))))
5447 ;; Try to set org-hide correctly
5448 (let ((foreground (org-find-invisible-foreground)))
5449 (if foreground
5450 (set-face-foreground 'org-hide foreground))))
5452 ;; Update `customize-package-emacs-version-alist'
5453 (add-to-list 'customize-package-emacs-version-alist
5454 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5455 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5456 ("8.2.6" . "24.4")))
5458 (defvar org-mode-transpose-word-syntax-table
5459 (let ((st (make-syntax-table)))
5460 (mapc (lambda(c) (modify-syntax-entry
5461 (string-to-char (car c)) "w p" st))
5462 org-emphasis-alist)
5463 st))
5465 (when (fboundp 'abbrev-table-put)
5466 (abbrev-table-put org-mode-abbrev-table
5467 :parents (list text-mode-abbrev-table)))
5469 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5471 (defsubst org-fix-ellipsis-at-bol ()
5472 (save-excursion (goto-char (window-start)) (recenter 0)))
5474 (defun org-find-invisible-foreground ()
5475 (let ((candidates (remove
5476 "unspecified-bg"
5477 (nconc
5478 (list (face-background 'default)
5479 (face-background 'org-default))
5480 (mapcar
5481 (lambda (alist)
5482 (when (boundp alist)
5483 (cdr (assoc 'background-color (symbol-value alist)))))
5484 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5485 (list (face-foreground 'org-hide))))))
5486 (car (remove nil candidates))))
5488 (defun org-current-time (&optional rounding-minutes past)
5489 "Current time, possibly rounded to ROUNDING-MINUTES.
5490 When ROUNDING-MINUTES is not an integer, fall back on the car of
5491 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5492 the rounding returns a past time."
5493 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5494 (car org-time-stamp-rounding-minutes)))
5495 (time (decode-time)) res)
5496 (if (< r 1)
5497 (current-time)
5498 (setq res
5499 (apply 'encode-time
5500 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5501 (nthcdr 2 time))))
5502 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5503 (seconds-to-time (- (org-float-time res) (* r 60)))
5504 res))))
5506 (defun org-today ()
5507 "Return today date, considering `org-extend-today-until'."
5508 (time-to-days
5509 (time-subtract (current-time)
5510 (list 0 (* 3600 org-extend-today-until) 0))))
5512 ;;;; Font-Lock stuff, including the activators
5514 (defvar org-mouse-map (make-sparse-keymap))
5515 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5516 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5517 (when org-mouse-1-follows-link
5518 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5519 (when org-tab-follows-link
5520 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5521 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5523 (require 'font-lock)
5525 (defconst org-non-link-chars "]\t\n\r<>")
5526 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5527 "shell" "elisp" "doi" "message"))
5528 (defvar org-link-types-re nil
5529 "Matches a link that has a url-like prefix like \"http:\"")
5530 (defvar org-link-re-with-space nil
5531 "Matches a link with spaces, optional angular brackets around it.")
5532 (defvar org-link-re-with-space2 nil
5533 "Matches a link with spaces, optional angular brackets around it.")
5534 (defvar org-link-re-with-space3 nil
5535 "Matches a link with spaces, only for internal part in bracket links.")
5536 (defvar org-angle-link-re nil
5537 "Matches link with angular brackets, spaces are allowed.")
5538 (defvar org-plain-link-re nil
5539 "Matches plain link, without spaces.")
5540 (defvar org-bracket-link-regexp nil
5541 "Matches a link in double brackets.")
5542 (defvar org-bracket-link-analytic-regexp nil
5543 "Regular expression used to analyze links.
5544 Here is what the match groups contain after a match:
5545 1: http:
5546 2: http
5547 3: path
5548 4: [desc]
5549 5: desc")
5550 (defvar org-bracket-link-analytic-regexp++ nil
5551 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5552 (defvar org-any-link-re nil
5553 "Regular expression matching any link.")
5555 (defconst org-match-sexp-depth 3
5556 "Number of stacked braces for sub/superscript matching.")
5558 (defun org-create-multibrace-regexp (left right n)
5559 "Create a regular expression which will match a balanced sexp.
5560 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5561 as single character strings.
5562 The regexp returned will match the entire expression including the
5563 delimiters. It will also define a single group which contains the
5564 match except for the outermost delimiters. The maximum depth of
5565 stacked delimiters is N. Escaping delimiters is not possible."
5566 (let* ((nothing (concat "[^" left right "]*?"))
5567 (or "\\|")
5568 (re nothing)
5569 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5570 (while (> n 1)
5571 (setq n (1- n)
5572 re (concat re or next)
5573 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5574 (concat left "\\(" re "\\)" right)))
5576 (defvar org-match-substring-regexp
5577 (concat
5578 "\\(\\S-\\)\\([_^]\\)\\("
5579 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5580 "\\|"
5581 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5582 "\\|"
5583 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5584 "The regular expression matching a sub- or superscript.")
5586 (defvar org-match-substring-with-braces-regexp
5587 (concat
5588 "\\(\\S-\\)\\([_^]\\)\\("
5589 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5590 "\\)")
5591 "The regular expression matching a sub- or superscript, forcing braces.")
5593 (defun org-make-link-regexps ()
5594 "Update the link regular expressions.
5595 This should be called after the variable `org-link-types' has changed."
5596 (setq org-link-types-re
5597 (concat "\\`" (regexp-opt org-link-types t) ":\\(?://\\)")
5598 org-link-re-with-space
5599 (concat "<?" (regexp-opt org-link-types t) ":\\(?://\\)"
5600 "\\([^" org-non-link-chars " ]"
5601 "[^" org-non-link-chars "]*"
5602 "[^" org-non-link-chars " ]\\)>?")
5603 org-link-re-with-space2
5604 (concat "<?" (regexp-opt org-link-types t) ":\\(?://\\)?"
5605 "\\([^" org-non-link-chars " ]"
5606 "[^\t\n\r]*"
5607 "[^" org-non-link-chars " ]\\)>?")
5608 org-link-re-with-space3
5609 (concat "<?" (regexp-opt org-link-types t) ":\\(?://\\)?"
5610 "\\([^" org-non-link-chars " ]"
5611 "[^\t\n\r]*\\)")
5612 org-angle-link-re
5613 (concat "<" (regexp-opt org-link-types t) ":\\(?://\\)?"
5614 "\\([^" org-non-link-chars " ]"
5615 "[^" org-non-link-chars "]*"
5616 "\\)>")
5617 org-plain-link-re
5618 (concat
5619 "\\<" (regexp-opt org-link-types t) ":\\(?://\\)?"
5620 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5621 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5622 org-bracket-link-regexp
5623 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5624 org-bracket-link-analytic-regexp
5625 (concat
5626 "\\[\\["
5627 "\\(" (regexp-opt org-link-types t) ":\\(?://\\)?\\)?"
5628 "\\([^]]+\\)"
5629 "\\]"
5630 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5631 "\\]")
5632 org-bracket-link-analytic-regexp++
5633 (concat
5634 "\\[\\["
5635 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\(?://\\)?\\)?"
5636 "\\([^]]+\\)"
5637 "\\]"
5638 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5639 "\\]")
5640 org-any-link-re
5641 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5642 org-angle-link-re "\\)\\|\\("
5643 org-plain-link-re "\\)")))
5645 (org-make-link-regexps)
5647 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5648 "Regular expression for fast time stamp matching.")
5649 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5650 "Regular expression for fast time stamp matching.")
5651 (defconst org-ts-regexp0
5652 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5653 "Regular expression matching time strings for analysis.
5654 This one does not require the space after the date, so it can be used
5655 on a string that terminates immediately after the date.")
5656 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5657 "Regular expression matching time strings for analysis.")
5658 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5659 "Regular expression matching time stamps, with groups.")
5660 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5661 "Regular expression matching time stamps (also [..]), with groups.")
5662 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5663 "Regular expression matching a time stamp range.")
5664 (defconst org-tr-regexp-both
5665 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5666 "Regular expression matching a time stamp range.")
5667 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5668 org-ts-regexp "\\)?")
5669 "Regular expression matching a time stamp or time stamp range.")
5670 (defconst org-tsr-regexp-both
5671 (concat org-ts-regexp-both "\\(--?-?"
5672 org-ts-regexp-both "\\)?")
5673 "Regular expression matching a time stamp or time stamp range.
5674 The time stamps may be either active or inactive.")
5676 (defvar org-emph-face nil)
5678 (defun org-do-emphasis-faces (limit)
5679 "Run through the buffer and add overlays to emphasized strings."
5680 (let (rtn a)
5681 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5682 (let* ((border (char-after (match-beginning 3)))
5683 (bre (regexp-quote (char-to-string border))))
5684 (if (and (not (= border (char-after (match-beginning 4))))
5685 (not (save-match-data
5686 (string-match (concat bre ".*" bre)
5687 (replace-regexp-in-string
5688 "\n" " "
5689 (substring (match-string 2) 1 -1))))))
5690 (progn
5691 (setq rtn t)
5692 (setq a (assoc (match-string 3) org-emphasis-alist))
5693 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5694 'face
5695 (nth 1 a))
5696 (and (nth 2 a)
5697 (org-remove-flyspell-overlays-in
5698 (match-beginning 0) (match-end 0)))
5699 (add-text-properties (match-beginning 2) (match-end 2)
5700 '(font-lock-multiline t org-emphasis t))
5701 (when org-hide-emphasis-markers
5702 (add-text-properties (match-end 4) (match-beginning 5)
5703 '(invisible org-link))
5704 (add-text-properties (match-beginning 3) (match-end 3)
5705 '(invisible org-link))))))
5706 (goto-char (1+ (match-beginning 0))))
5707 rtn))
5709 (defun org-emphasize (&optional char)
5710 "Insert or change an emphasis, i.e. a font like bold or italic.
5711 If there is an active region, change that region to a new emphasis.
5712 If there is no region, just insert the marker characters and position
5713 the cursor between them.
5714 CHAR should be the marker character. If it is a space, it means to
5715 remove the emphasis of the selected region.
5716 If CHAR is not given (for example in an interactive call) it will be
5717 prompted for."
5718 (interactive)
5719 (let ((erc org-emphasis-regexp-components)
5720 (prompt "")
5721 (string "") beg end move c s)
5722 (if (org-region-active-p)
5723 (setq beg (region-beginning) end (region-end)
5724 string (buffer-substring beg end))
5725 (setq move t))
5727 (unless char
5728 (message "Emphasis marker or tag: [%s]"
5729 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5730 (setq char (read-char-exclusive)))
5731 (if (equal char ?\ )
5732 (setq s "" move nil)
5733 (unless (assoc (char-to-string char) org-emphasis-alist)
5734 (user-error "No such emphasis marker: \"%c\"" char))
5735 (setq s (char-to-string char)))
5736 (while (and (> (length string) 1)
5737 (equal (substring string 0 1) (substring string -1))
5738 (assoc (substring string 0 1) org-emphasis-alist))
5739 (setq string (substring string 1 -1)))
5740 (setq string (concat s string s))
5741 (if beg (delete-region beg end))
5742 (unless (or (bolp)
5743 (string-match (concat "[" (nth 0 erc) "\n]")
5744 (char-to-string (char-before (point)))))
5745 (insert " "))
5746 (unless (or (eobp)
5747 (string-match (concat "[" (nth 1 erc) "\n]")
5748 (char-to-string (char-after (point)))))
5749 (insert " ") (backward-char 1))
5750 (insert string)
5751 (and move (backward-char 1))))
5753 (defconst org-nonsticky-props
5754 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5756 (defsubst org-rear-nonsticky-at (pos)
5757 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5759 (defun org-activate-plain-links (limit)
5760 "Run through the buffer and add overlays to links."
5761 (let (f hl)
5762 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5763 (not (org-in-src-block-p)))
5764 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5765 (setq f (get-text-property (match-beginning 0) 'face))
5766 (setq hl (org-match-string-no-properties 0))
5767 (if (or (eq f 'org-tag)
5768 (and (listp f) (memq 'org-tag f)))
5770 (add-text-properties (match-beginning 0) (match-end 0)
5771 (list 'mouse-face 'highlight
5772 'face 'org-link
5773 'htmlize-link `(:uri ,hl)
5774 'keymap org-mouse-map))
5775 (org-rear-nonsticky-at (match-end 0)))
5776 t)))
5778 (defun org-activate-code (limit)
5779 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5780 (progn
5781 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5782 (remove-text-properties (match-beginning 0) (match-end 0)
5783 '(display t invisible t intangible t))
5784 t)))
5786 (defcustom org-src-fontify-natively nil
5787 "When non-nil, fontify code in code blocks."
5788 :type 'boolean
5789 :version "24.1"
5790 :group 'org-appearance
5791 :group 'org-babel)
5793 (defcustom org-allow-promoting-top-level-subtree nil
5794 "When non-nil, allow promoting a top level subtree.
5795 The leading star of the top level headline will be replaced
5796 by a #."
5797 :type 'boolean
5798 :version "24.1"
5799 :group 'org-appearance)
5801 (defun org-fontify-meta-lines-and-blocks (limit)
5802 (condition-case nil
5803 (org-fontify-meta-lines-and-blocks-1 limit)
5804 (error (message "org-mode fontification error"))))
5806 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5807 "Fontify #+ lines and blocks."
5808 (let ((case-fold-search t))
5809 (if (re-search-forward
5810 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5811 limit t)
5812 (let ((beg (match-beginning 0))
5813 (block-start (match-end 0))
5814 (block-end nil)
5815 (lang (match-string 7))
5816 (beg1 (line-beginning-position 2))
5817 (dc1 (downcase (match-string 2)))
5818 (dc3 (downcase (match-string 3)))
5819 end end1 quoting block-type ovl)
5820 (cond
5821 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5822 ;; a single line of backend-specific content
5823 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5824 (remove-text-properties (match-beginning 0) (match-end 0)
5825 '(display t invisible t intangible t))
5826 (add-text-properties (match-beginning 1) (match-end 3)
5827 '(font-lock-fontified t face org-meta-line))
5828 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5829 '(font-lock-fontified t face org-block))
5830 ; for backend-specific code
5832 ((and (match-end 4) (equal dc3 "+begin"))
5833 ;; Truly a block
5834 (setq block-type (downcase (match-string 5))
5835 quoting (member block-type org-protecting-blocks))
5836 (when (re-search-forward
5837 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5838 nil t) ;; on purpose, we look further than LIMIT
5839 (setq end (min (point-max) (match-end 0))
5840 end1 (min (point-max) (1- (match-beginning 0))))
5841 (setq block-end (match-beginning 0))
5842 (when quoting
5843 (remove-text-properties beg end
5844 '(display t invisible t intangible t)))
5845 (add-text-properties
5846 beg end
5847 '(font-lock-fontified t font-lock-multiline t))
5848 (add-text-properties beg beg1 '(face org-meta-line))
5849 (add-text-properties end1 (min (point-max) (1+ end))
5850 '(face org-meta-line)) ; for end_src
5851 (cond
5852 ((and lang (not (string= lang "")) org-src-fontify-natively)
5853 (org-src-font-lock-fontify-block lang block-start block-end)
5854 ;; remove old background overlays
5855 (mapc (lambda (ov)
5856 (if (eq (overlay-get ov 'face) 'org-block-background)
5857 (delete-overlay ov)))
5858 (overlays-at (/ (+ beg1 block-end) 2)))
5859 ;; add a background overlay
5860 (setq ovl (make-overlay beg1 block-end))
5861 (overlay-put ovl 'face 'org-block-background)
5862 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5863 (quoting
5864 (add-text-properties beg1 (min (point-max) (1+ end1))
5865 '(face org-block))) ; end of source block
5866 ((not org-fontify-quote-and-verse-blocks))
5867 ((string= block-type "quote")
5868 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5869 ((string= block-type "verse")
5870 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5871 (add-text-properties beg beg1 '(face org-block-begin-line))
5872 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5873 '(face org-block-end-line))
5875 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5876 (add-text-properties
5877 beg (match-end 3)
5878 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5879 '(font-lock-fontified t invisible t)
5880 '(font-lock-fontified t face org-document-info-keyword)))
5881 (add-text-properties
5882 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5883 (if (string-equal dc1 "+title:")
5884 '(font-lock-fontified t face org-document-title)
5885 '(font-lock-fontified t face org-document-info))))
5886 ((or (equal dc1 "+results")
5887 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5888 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5889 "+call:" "+header:" "+headers:" "+name:"))
5890 (and (match-end 4) (equal dc3 "+attr")))
5891 (add-text-properties
5892 beg (match-end 0)
5893 '(font-lock-fontified t face org-meta-line))
5895 ((member dc3 '(" " ""))
5896 (add-text-properties
5897 beg (match-end 0)
5898 '(font-lock-fontified t face font-lock-comment-face)))
5899 ((not (member (char-after beg) '(?\ ?\t)))
5900 ;; just any other in-buffer setting, but not indented
5901 (add-text-properties
5902 beg (match-end 0)
5903 '(font-lock-fontified t face org-meta-line))
5905 (t nil))))))
5907 (defun org-activate-angle-links (limit)
5908 "Run through the buffer and add overlays to links."
5909 (if (and (re-search-forward org-angle-link-re limit t)
5910 (not (org-in-src-block-p)))
5911 (progn
5912 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5913 (add-text-properties (match-beginning 0) (match-end 0)
5914 (list 'mouse-face 'highlight
5915 'keymap org-mouse-map))
5916 (org-rear-nonsticky-at (match-end 0))
5917 t)))
5919 (defun org-activate-footnote-links (limit)
5920 "Run through the buffer and add overlays to footnotes."
5921 (let ((fn (org-footnote-next-reference-or-definition limit)))
5922 (when fn
5923 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5924 (org-remove-flyspell-overlays-in beg end)
5925 (add-text-properties beg end
5926 (list 'mouse-face 'highlight
5927 'keymap org-mouse-map
5928 'help-echo
5929 (if (= (point-at-bol) beg)
5930 "Footnote definition"
5931 "Footnote reference")
5932 'font-lock-fontified t
5933 'font-lock-multiline t
5934 'face 'org-footnote))))))
5936 (defun org-activate-bracket-links (limit)
5937 "Run through the buffer and add overlays to bracketed links."
5938 (if (and (re-search-forward org-bracket-link-regexp limit t)
5939 (not (org-in-src-block-p)))
5940 (let* ((hl (org-match-string-no-properties 1))
5941 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5942 (ip (org-maybe-intangible
5943 (list 'invisible 'org-link
5944 'keymap org-mouse-map 'mouse-face 'highlight
5945 'font-lock-multiline t 'help-echo help
5946 'htmlize-link `(:uri ,hl))))
5947 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5948 'font-lock-multiline t 'help-echo help
5949 'htmlize-link `(:uri ,hl))))
5950 ;; We need to remove the invisible property here. Table narrowing
5951 ;; may have made some of this invisible.
5952 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5953 (remove-text-properties (match-beginning 0) (match-end 0)
5954 '(invisible nil))
5955 (if (match-end 3)
5956 (progn
5957 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5958 (org-rear-nonsticky-at (match-beginning 3))
5959 (add-text-properties (match-beginning 3) (match-end 3) vp)
5960 (org-rear-nonsticky-at (match-end 3))
5961 (add-text-properties (match-end 3) (match-end 0) ip)
5962 (org-rear-nonsticky-at (match-end 0)))
5963 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5964 (org-rear-nonsticky-at (match-beginning 1))
5965 (add-text-properties (match-beginning 1) (match-end 1) vp)
5966 (org-rear-nonsticky-at (match-end 1))
5967 (add-text-properties (match-end 1) (match-end 0) ip)
5968 (org-rear-nonsticky-at (match-end 0)))
5969 t)))
5971 (defun org-activate-dates (limit)
5972 "Run through the buffer and add overlays to dates."
5973 (if (and (re-search-forward org-tsr-regexp-both limit t)
5974 (not (equal (char-before (match-beginning 0)) 91)))
5975 (progn
5976 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5977 (add-text-properties (match-beginning 0) (match-end 0)
5978 (list 'mouse-face 'highlight
5979 'keymap org-mouse-map))
5980 (org-rear-nonsticky-at (match-end 0))
5981 (when org-display-custom-times
5982 (if (match-end 3)
5983 (org-display-custom-time (match-beginning 3) (match-end 3)))
5984 (org-display-custom-time (match-beginning 1) (match-end 1)))
5985 t)))
5987 (defvar org-target-link-regexp nil
5988 "Regular expression matching radio targets in plain text.")
5989 (make-variable-buffer-local 'org-target-link-regexp)
5990 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5991 "Regular expression matching a link target.")
5992 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5993 "Regular expression matching a radio target.")
5994 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5995 "Regular expression matching any target.")
5997 (defun org-activate-target-links (limit)
5998 "Run through the buffer and add overlays to target matches."
5999 (when org-target-link-regexp
6000 (let ((case-fold-search t))
6001 (if (re-search-forward org-target-link-regexp limit t)
6002 (progn
6003 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6004 (add-text-properties (match-beginning 0) (match-end 0)
6005 (list 'mouse-face 'highlight
6006 'keymap org-mouse-map
6007 'help-echo "Radio target link"
6008 'org-linked-text t))
6009 (org-rear-nonsticky-at (match-end 0))
6010 t)))))
6012 (defun org-update-radio-target-regexp ()
6013 "Find all radio targets in this file and update the regular expression."
6014 (interactive)
6015 (when (memq 'radio org-activate-links)
6016 (setq org-target-link-regexp
6017 (org-make-target-link-regexp (org-all-targets 'radio)))
6018 (org-restart-font-lock)))
6020 (defun org-hide-wide-columns (limit)
6021 (let (s e)
6022 (setq s (text-property-any (point) (or limit (point-max))
6023 'org-cwidth t))
6024 (when s
6025 (setq e (next-single-property-change s 'org-cwidth))
6026 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6027 (goto-char e)
6028 t)))
6030 (defvar org-latex-and-related-regexp nil
6031 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6032 (defvar org-match-substring-regexp)
6033 (defvar org-match-substring-with-braces-regexp)
6035 (defun org-compute-latex-and-related-regexp ()
6036 "Compute regular expression for LaTeX, entities and sub/superscript.
6037 Result depends on variable `org-highlight-latex-and-related'."
6038 (org-set-local
6039 'org-latex-and-related-regexp
6040 (let* ((re-sub
6041 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6042 ((eq org-use-sub-superscripts '{})
6043 (list org-match-substring-with-braces-regexp))
6044 (org-use-sub-superscripts (list org-match-substring-regexp))))
6045 (re-latex
6046 (when (memq 'latex org-highlight-latex-and-related)
6047 (let ((matchers (plist-get org-format-latex-options :matchers)))
6048 (delq nil
6049 (mapcar (lambda (x)
6050 (and (member (car x) matchers) (nth 1 x)))
6051 org-latex-regexps)))))
6052 (re-entities
6053 (when (memq 'entities org-highlight-latex-and-related)
6054 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6055 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6057 (defun org-do-latex-and-related (limit)
6058 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6059 LIMIT bounds the search for syntax to highlight. Stop at first
6060 highlighted object, if any. Return t if some highlighting was
6061 done, nil otherwise."
6062 (when (org-string-nw-p org-latex-and-related-regexp)
6063 (catch 'found
6064 (while (re-search-forward org-latex-and-related-regexp limit t)
6065 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6066 'face))
6067 '(org-code org-verbatim underline))
6068 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6069 '(?_ ?^))
6071 0)))
6072 (font-lock-prepend-text-property
6073 (+ offset (match-beginning 0)) (match-end 0)
6074 'face 'org-latex-and-related)
6075 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6076 '(font-lock-multiline t)))
6077 (throw 'found t)))
6078 nil)))
6080 (defun org-restart-font-lock ()
6081 "Restart `font-lock-mode', to force refontification."
6082 (when (and (boundp 'font-lock-mode) font-lock-mode)
6083 (font-lock-mode -1)
6084 (font-lock-mode 1)))
6086 (defun org-all-targets (&optional radio)
6087 "Return a list of all targets in this file.
6088 When optional argument RADIO is non-nil, only find radio
6089 targets."
6090 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6091 (save-excursion
6092 (goto-char (point-min))
6093 (while (re-search-forward re nil t)
6094 ;; Make sure point is really within the object.
6095 (backward-char)
6096 (let ((obj (org-element-context)))
6097 (when (memq (org-element-type obj) '(radio-target target))
6098 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6099 rtn)))
6101 (defun org-make-target-link-regexp (targets)
6102 "Make regular expression matching all strings in TARGETS.
6103 The regular expression finds the targets also if there is a line break
6104 between words."
6105 (and targets
6106 (concat
6107 "\\_<\\("
6108 (mapconcat
6109 (lambda (x)
6110 (setq x (regexp-quote x))
6111 (while (string-match " +" x)
6112 (setq x (replace-match "\\s-+" t t x)))
6114 targets
6115 "\\|")
6116 "\\)\\_>")))
6118 (defun org-activate-tags (limit)
6119 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6120 (progn
6121 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6122 (add-text-properties (match-beginning 1) (match-end 1)
6123 (list 'mouse-face 'highlight
6124 'keymap org-mouse-map))
6125 (org-rear-nonsticky-at (match-end 1))
6126 t)))
6128 (defun org-outline-level ()
6129 "Compute the outline level of the heading at point.
6130 If this is called at a normal headline, the level is the number of stars.
6131 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6132 (save-excursion
6133 (if (not (condition-case nil
6134 (org-back-to-heading t)
6135 (error nil)))
6137 (looking-at org-outline-regexp)
6138 (1- (- (match-end 0) (match-beginning 0))))))
6140 (defvar org-font-lock-keywords nil)
6142 (defsubst org-re-property (property &optional literal)
6143 "Return a regexp matching a PROPERTY line.
6144 Match group 3 will be set to the value if it exists."
6145 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6146 (if literal property (regexp-quote property))
6147 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6149 (defconst org-property-re
6150 (org-re-property ".*?" 'literal)
6151 "Regular expression matching a property line.
6152 There are four matching groups:
6153 1: :PROPKEY: including the leading and trailing colon,
6154 2: PROPKEY without the leading and trailing colon,
6155 3: PROPVAL without leading or trailing spaces,
6156 4: the indentation of the current line,
6157 5: trailing whitespace.")
6159 (defvar org-font-lock-hook nil
6160 "Functions to be called for special font lock stuff.")
6162 (defvar org-font-lock-set-keywords-hook nil
6163 "Functions that can manipulate `org-font-lock-extra-keywords'.
6164 This is called after `org-font-lock-extra-keywords' is defined, but before
6165 it is installed to be used by font lock. This can be useful if something
6166 needs to be inserted at a specific position in the font-lock sequence.")
6168 (defun org-font-lock-hook (limit)
6169 "Run `org-font-lock-hook' within LIMIT."
6170 (run-hook-with-args 'org-font-lock-hook limit))
6172 (defun org-set-font-lock-defaults ()
6173 "Set font lock defaults for the current buffer."
6174 (let* ((em org-fontify-emphasized-text)
6175 (lk org-activate-links)
6176 (org-font-lock-extra-keywords
6177 (list
6178 ;; Call the hook
6179 '(org-font-lock-hook)
6180 ;; Headlines
6181 `(,(if org-fontify-whole-heading-line
6182 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6183 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6184 (1 (org-get-level-face 1))
6185 (2 (org-get-level-face 2))
6186 (3 (org-get-level-face 3)))
6187 ;; Table lines
6188 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6189 (1 'org-table t))
6190 ;; Table internals
6191 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6192 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6193 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6194 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6195 ;; Drawers
6196 (list org-drawer-regexp '(0 'org-special-keyword t))
6197 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6198 ;; Properties
6199 (list org-property-re
6200 '(1 'org-special-keyword t)
6201 '(3 'org-property-value t))
6202 ;; Links
6203 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6204 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6205 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6206 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6207 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6208 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6209 (if (memq 'footnote lk) '(org-activate-footnote-links))
6210 ;; Targets.
6211 (list org-any-target-regexp '(0 'org-target t))
6212 ;; Diary sexps.
6213 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6214 ;; Macro
6215 '("{{{.+}}}" (0 'org-macro t))
6216 '(org-hide-wide-columns (0 nil append))
6217 ;; TODO keyword
6218 (list (format org-heading-keyword-regexp-format
6219 org-todo-regexp)
6220 '(2 (org-get-todo-face 2) t))
6221 ;; DONE
6222 (if org-fontify-done-headline
6223 (list (format org-heading-keyword-regexp-format
6224 (concat
6225 "\\(?:"
6226 (mapconcat 'regexp-quote org-done-keywords "\\|")
6227 "\\)"))
6228 '(2 'org-headline-done t))
6229 nil)
6230 ;; Priorities
6231 '(org-font-lock-add-priority-faces)
6232 ;; Tags
6233 '(org-font-lock-add-tag-faces)
6234 ;; Tags groups
6235 (if (and org-group-tags org-tag-groups-alist)
6236 (list (concat org-outline-regexp-bol ".+\\(:"
6237 (regexp-opt (mapcar 'car org-tag-groups-alist))
6238 ":\\).*$")
6239 '(1 'org-tag-group prepend)))
6240 ;; Special keywords
6241 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6242 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6243 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6244 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6245 ;; Emphasis
6246 (if em
6247 (if (featurep 'xemacs)
6248 '(org-do-emphasis-faces (0 nil append))
6249 '(org-do-emphasis-faces)))
6250 ;; Checkboxes
6251 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6252 1 'org-checkbox prepend)
6253 (if (cdr (assq 'checkbox org-list-automatic-rules))
6254 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6255 (0 (org-get-checkbox-statistics-face) t)))
6256 ;; Description list items
6257 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6258 1 'org-list-dt prepend)
6259 ;; ARCHIVEd headings
6260 (list (concat
6261 org-outline-regexp-bol
6262 "\\(.*:" org-archive-tag ":.*\\)")
6263 '(1 'org-archived prepend))
6264 ;; Specials
6265 '(org-do-latex-and-related)
6266 '(org-fontify-entities)
6267 '(org-raise-scripts)
6268 ;; Code
6269 '(org-activate-code (1 'org-code t))
6270 ;; COMMENT
6271 (list (format org-heading-keyword-regexp-format
6272 (concat "\\("
6273 org-comment-string "\\|" org-quote-string
6274 "\\)"))
6275 '(2 'org-special-keyword t))
6276 ;; Blocks and meta lines
6277 '(org-fontify-meta-lines-and-blocks))))
6278 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6279 (run-hooks 'org-font-lock-set-keywords-hook)
6280 ;; Now set the full font-lock-keywords
6281 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6282 (org-set-local 'font-lock-defaults
6283 '(org-font-lock-keywords t nil nil backward-paragraph))
6284 (kill-local-variable 'font-lock-keywords) nil))
6286 (defun org-toggle-pretty-entities ()
6287 "Toggle the composition display of entities as UTF8 characters."
6288 (interactive)
6289 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6290 (org-restart-font-lock)
6291 (if org-pretty-entities
6292 (message "Entities are now displayed as UTF8 characters")
6293 (save-restriction
6294 (widen)
6295 (org-decompose-region (point-min) (point-max))
6296 (message "Entities are now displayed as plain text"))))
6298 (defvar org-custom-properties-overlays nil
6299 "List of overlays used for custom properties.")
6300 (make-variable-buffer-local 'org-custom-properties-overlays)
6302 (defun org-toggle-custom-properties-visibility ()
6303 "Display or hide properties in `org-custom-properties'."
6304 (interactive)
6305 (if org-custom-properties-overlays
6306 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6307 (setq org-custom-properties-overlays nil))
6308 (unless (not org-custom-properties)
6309 (save-excursion
6310 (save-restriction
6311 (widen)
6312 (goto-char (point-min))
6313 (while (re-search-forward org-property-re nil t)
6314 (mapc (lambda(p)
6315 (when (equal p (substring (match-string 1) 1 -1))
6316 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6317 (overlay-put o 'invisible t)
6318 (overlay-put o 'org-custom-property t)
6319 (push o org-custom-properties-overlays))))
6320 org-custom-properties)))))))
6322 (defun org-fontify-entities (limit)
6323 "Find an entity to fontify."
6324 (let (ee)
6325 (when org-pretty-entities
6326 (catch 'match
6327 (while (re-search-forward
6328 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6329 limit t)
6330 (if (and (not (org-in-indented-comment-line))
6331 (setq ee (org-entity-get (match-string 1)))
6332 (= (length (nth 6 ee)) 1))
6333 (let*
6334 ((end (if (equal (match-string 2) "{}")
6335 (match-end 2)
6336 (match-end 1))))
6337 (add-text-properties
6338 (match-beginning 0) end
6339 (list 'font-lock-fontified t))
6340 (compose-region (match-beginning 0) end
6341 (nth 6 ee) nil)
6342 (backward-char 1)
6343 (throw 'match t))))
6344 nil))))
6346 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6347 "Fontify string S like in Org-mode."
6348 (with-temp-buffer
6349 (insert s)
6350 (let ((org-odd-levels-only odd-levels))
6351 (org-mode)
6352 (font-lock-fontify-buffer)
6353 (buffer-string))))
6355 (defvar org-m nil)
6356 (defvar org-l nil)
6357 (defvar org-f nil)
6358 (defun org-get-level-face (n)
6359 "Get the right face for match N in font-lock matching of headlines."
6360 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6361 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6362 (if org-cycle-level-faces
6363 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6364 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6365 (cond
6366 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6367 ((eq n 2) org-f)
6368 (t (if org-level-color-stars-only nil org-f))))
6371 (defun org-get-todo-face (kwd)
6372 "Get the right face for a TODO keyword KWD.
6373 If KWD is a number, get the corresponding match group."
6374 (if (numberp kwd) (setq kwd (match-string kwd)))
6375 (or (org-face-from-face-or-color
6376 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6377 (and (member kwd org-done-keywords) 'org-done)
6378 'org-todo))
6380 (defun org-face-from-face-or-color (context inherit face-or-color)
6381 "Create a face list that inherits INHERIT, but sets the foreground color.
6382 When FACE-OR-COLOR is not a string, just return it."
6383 (if (stringp face-or-color)
6384 (list :inherit inherit
6385 (cdr (assoc context org-faces-easy-properties))
6386 face-or-color)
6387 face-or-color))
6389 (defun org-font-lock-add-tag-faces (limit)
6390 "Add the special tag faces."
6391 (when (and org-tag-faces org-tags-special-faces-re)
6392 (while (re-search-forward org-tags-special-faces-re limit t)
6393 (add-text-properties (match-beginning 1) (match-end 1)
6394 (list 'face (org-get-tag-face 1)
6395 'font-lock-fontified t))
6396 (backward-char 1))))
6398 (defun org-font-lock-add-priority-faces (limit)
6399 "Add the special priority faces."
6400 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6401 (when (save-match-data (org-at-heading-p))
6402 (add-text-properties
6403 (match-beginning 0) (match-end 0)
6404 (list 'face (or (org-face-from-face-or-color
6405 'priority 'org-priority
6406 (cdr (assoc (char-after (match-beginning 1))
6407 org-priority-faces)))
6408 'org-priority)
6409 'font-lock-fontified t)))))
6411 (defun org-get-tag-face (kwd)
6412 "Get the right face for a TODO keyword KWD.
6413 If KWD is a number, get the corresponding match group."
6414 (if (numberp kwd) (setq kwd (match-string kwd)))
6415 (or (org-face-from-face-or-color
6416 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6417 'org-tag))
6419 (defun org-unfontify-region (beg end &optional maybe_loudly)
6420 "Remove fontification and activation overlays from links."
6421 (font-lock-default-unfontify-region beg end)
6422 (let* ((buffer-undo-list t)
6423 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6424 (inhibit-modification-hooks t)
6425 deactivate-mark buffer-file-name buffer-file-truename)
6426 (org-decompose-region beg end)
6427 (remove-text-properties beg end
6428 '(mouse-face t keymap t org-linked-text t
6429 invisible t intangible t
6430 org-no-flyspell t org-emphasis t))
6431 (org-remove-font-lock-display-properties beg end)))
6433 (defconst org-script-display '(((raise -0.3) (height 0.7))
6434 ((raise 0.3) (height 0.7))
6435 ((raise -0.5))
6436 ((raise 0.5)))
6437 "Display properties for showing superscripts and subscripts.")
6439 (defun org-remove-font-lock-display-properties (beg end)
6440 "Remove specific display properties that have been added by font lock.
6441 The will remove the raise properties that are used to show superscripts
6442 and subscripts."
6443 (let (next prop)
6444 (while (< beg end)
6445 (setq next (next-single-property-change beg 'display nil end)
6446 prop (get-text-property beg 'display))
6447 (if (member prop org-script-display)
6448 (put-text-property beg next 'display nil))
6449 (setq beg next))))
6451 (defun org-raise-scripts (limit)
6452 "Add raise properties to sub/superscripts."
6453 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6454 (if (re-search-forward
6455 (if (eq org-use-sub-superscripts t)
6456 org-match-substring-regexp
6457 org-match-substring-with-braces-regexp)
6458 limit t)
6459 (let* ((pos (point)) table-p comment-p
6460 (mpos (match-beginning 3))
6461 (emph-p (get-text-property mpos 'org-emphasis))
6462 (link-p (get-text-property mpos 'mouse-face))
6463 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6464 (goto-char (point-at-bol))
6465 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6466 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6467 (goto-char pos)
6468 ;; Handle a_b^c
6469 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6470 (if (or comment-p emph-p link-p keyw-p)
6472 (put-text-property (match-beginning 3) (match-end 0)
6473 'display
6474 (if (equal (char-after (match-beginning 2)) ?^)
6475 (nth (if table-p 3 1) org-script-display)
6476 (nth (if table-p 2 0) org-script-display)))
6477 (add-text-properties (match-beginning 2) (match-end 2)
6478 (list 'invisible t
6479 'org-dwidth t 'org-dwidth-n 1))
6480 (if (and (eq (char-after (match-beginning 3)) ?{)
6481 (eq (char-before (match-end 3)) ?}))
6482 (progn
6483 (add-text-properties
6484 (match-beginning 3) (1+ (match-beginning 3))
6485 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6486 (add-text-properties
6487 (1- (match-end 3)) (match-end 3)
6488 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6489 t)))))
6491 ;;;; Visibility cycling, including org-goto and indirect buffer
6493 ;;; Cycling
6495 (defvar org-cycle-global-status nil)
6496 (make-variable-buffer-local 'org-cycle-global-status)
6497 (put 'org-cycle-global-status 'org-state t)
6498 (defvar org-cycle-subtree-status nil)
6499 (make-variable-buffer-local 'org-cycle-subtree-status)
6500 (put 'org-cycle-subtree-status 'org-state t)
6502 (defvar org-inlinetask-min-level)
6504 (defun org-unlogged-message (&rest args)
6505 "Display a message, but avoid logging it in the *Messages* buffer."
6506 (let ((message-log-max nil))
6507 (apply 'message args)))
6509 ;;;###autoload
6510 (defun org-cycle (&optional arg)
6511 "TAB-action and visibility cycling for Org-mode.
6513 This is the command invoked in Org-mode by the TAB key. Its main purpose
6514 is outline visibility cycling, but it also invokes other actions
6515 in special contexts.
6517 - When this function is called with a prefix argument, rotate the entire
6518 buffer through 3 states (global cycling)
6519 1. OVERVIEW: Show only top-level headlines.
6520 2. CONTENTS: Show all headlines of all levels, but no body text.
6521 3. SHOW ALL: Show everything.
6522 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6523 determined by the variable `org-startup-folded', and by any VISIBILITY
6524 properties in the buffer.
6525 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6526 including any drawers.
6528 - When inside a table, re-align the table and move to the next field.
6530 - When point is at the beginning of a headline, rotate the subtree started
6531 by this line through 3 different states (local cycling)
6532 1. FOLDED: Only the main headline is shown.
6533 2. CHILDREN: The main headline and the direct children are shown.
6534 From this state, you can move to one of the children
6535 and zoom in further.
6536 3. SUBTREE: Show the entire subtree, including body text.
6537 If there is no subtree, switch directly from CHILDREN to FOLDED.
6539 - When point is at the beginning of an empty headline and the variable
6540 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6541 of the headline by demoting and promoting it to likely levels. This
6542 speeds up creation document structure by pressing TAB once or several
6543 times right after creating a new headline.
6545 - When there is a numeric prefix, go up to a heading with level ARG, do
6546 a `show-subtree' and return to the previous cursor position. If ARG
6547 is negative, go up that many levels.
6549 - When point is not at the beginning of a headline, execute the global
6550 binding for TAB, which is re-indenting the line. See the option
6551 `org-cycle-emulate-tab' for details.
6553 - Special case: if point is at the beginning of the buffer and there is
6554 no headline in line 1, this function will act as if called with prefix arg
6555 (C-u TAB, same as S-TAB) also when called without prefix arg.
6556 But only if also the variable `org-cycle-global-at-bob' is t."
6557 (interactive "P")
6558 (org-load-modules-maybe)
6559 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6560 (and org-cycle-level-after-item/entry-creation
6561 (or (org-cycle-level)
6562 (org-cycle-item-indentation))))
6563 (let* ((limit-level
6564 (or org-cycle-max-level
6565 (and (boundp 'org-inlinetask-min-level)
6566 org-inlinetask-min-level
6567 (1- org-inlinetask-min-level))))
6568 (nstars (and limit-level
6569 (if org-odd-levels-only
6570 (and limit-level (1- (* limit-level 2)))
6571 limit-level)))
6572 (org-outline-regexp
6573 (if (not (derived-mode-p 'org-mode))
6574 outline-regexp
6575 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6576 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6577 (not (looking-at org-outline-regexp))))
6578 (org-cycle-hook
6579 (if bob-special
6580 (delq 'org-optimize-window-after-visibility-change
6581 (copy-sequence org-cycle-hook))
6582 org-cycle-hook))
6583 (pos (point)))
6585 (if (or bob-special (equal arg '(4)))
6586 ;; special case: use global cycling
6587 (setq arg t))
6589 (cond
6591 ((equal arg '(16))
6592 (setq last-command 'dummy)
6593 (org-set-startup-visibility)
6594 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6596 ((equal arg '(64))
6597 (show-all)
6598 (org-unlogged-message "Entire buffer visible, including drawers"))
6600 ;; Try cdlatex TAB completion
6601 ((org-try-cdlatex-tab))
6603 ;; Table: enter it or move to the next field.
6604 ((org-at-table-p 'any)
6605 (if (org-at-table.el-p)
6606 (message "Use C-c ' to edit table.el tables")
6607 (if arg (org-table-edit-field t)
6608 (org-table-justify-field-maybe)
6609 (call-interactively 'org-table-next-field))))
6611 ((run-hook-with-args-until-success
6612 'org-tab-after-check-for-table-hook))
6614 ;; Global cycling: delegate to `org-cycle-internal-global'.
6615 ((eq arg t) (org-cycle-internal-global))
6617 ;; Drawers: delegate to `org-flag-drawer'.
6618 ((and org-drawers org-drawer-regexp
6619 (save-excursion
6620 (beginning-of-line 1)
6621 (looking-at org-drawer-regexp)))
6622 (org-flag-drawer ; toggle block visibility
6623 (not (get-char-property (match-end 0) 'invisible))))
6625 ;; Show-subtree, ARG levels up from here.
6626 ((integerp arg)
6627 (save-excursion
6628 (org-back-to-heading)
6629 (outline-up-heading (if (< arg 0) (- arg)
6630 (- (funcall outline-level) arg)))
6631 (org-show-subtree)))
6633 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6634 ((and (featurep 'org-inlinetask)
6635 (org-inlinetask-at-task-p)
6636 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6637 (org-inlinetask-toggle-visibility))
6639 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6640 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6641 (save-excursion (beginning-of-line 1)
6642 (looking-at org-outline-regexp)))
6643 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6644 (org-cycle-internal-local))
6646 ;; From there: TAB emulation and template completion.
6647 (buffer-read-only (org-back-to-heading))
6649 ((run-hook-with-args-until-success
6650 'org-tab-after-check-for-cycling-hook))
6652 ((org-try-structure-completion))
6654 ((run-hook-with-args-until-success
6655 'org-tab-before-tab-emulation-hook))
6657 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6658 (or (not (bolp))
6659 (not (looking-at org-outline-regexp))))
6660 (call-interactively (global-key-binding "\t")))
6662 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6663 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6664 (or (and (eq org-cycle-emulate-tab 'white)
6665 (= (match-end 0) (point-at-eol)))
6666 (and (eq org-cycle-emulate-tab 'whitestart)
6667 (>= (match-end 0) pos))))
6669 (eq org-cycle-emulate-tab t))
6670 (call-interactively (global-key-binding "\t")))
6672 (t (save-excursion
6673 (org-back-to-heading)
6674 (org-cycle)))))))
6676 (defun org-cycle-internal-global ()
6677 "Do the global cycling action."
6678 ;; Hack to avoid display of messages for .org attachments in Gnus
6679 (let ((ga (string-match "\\*fontification" (buffer-name))))
6680 (cond
6681 ((and (eq last-command this-command)
6682 (eq org-cycle-global-status 'overview))
6683 ;; We just created the overview - now do table of contents
6684 ;; This can be slow in very large buffers, so indicate action
6685 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6686 (unless ga (org-unlogged-message "CONTENTS..."))
6687 (org-content)
6688 (unless ga (org-unlogged-message "CONTENTS...done"))
6689 (setq org-cycle-global-status 'contents)
6690 (run-hook-with-args 'org-cycle-hook 'contents))
6692 ((and (eq last-command this-command)
6693 (eq org-cycle-global-status 'contents))
6694 ;; We just showed the table of contents - now show everything
6695 (run-hook-with-args 'org-pre-cycle-hook 'all)
6696 (show-all)
6697 (unless ga (org-unlogged-message "SHOW ALL"))
6698 (setq org-cycle-global-status 'all)
6699 (run-hook-with-args 'org-cycle-hook 'all))
6702 ;; Default action: go to overview
6703 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6704 (org-overview)
6705 (unless ga (org-unlogged-message "OVERVIEW"))
6706 (setq org-cycle-global-status 'overview)
6707 (run-hook-with-args 'org-cycle-hook 'overview)))))
6709 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6711 (defun org-cycle-internal-local ()
6712 "Do the local cycling action."
6713 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6714 ;; First, determine end of headline (EOH), end of subtree or item
6715 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6716 (save-excursion
6717 (if (org-at-item-p)
6718 (progn
6719 (beginning-of-line)
6720 (setq struct (org-list-struct))
6721 (setq eoh (point-at-eol))
6722 (setq eos (org-list-get-item-end-before-blank (point) struct))
6723 (setq has-children (org-list-has-child-p (point) struct)))
6724 (org-back-to-heading)
6725 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6726 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6727 (setq has-children
6728 (or (save-excursion
6729 (let ((level (funcall outline-level)))
6730 (outline-next-heading)
6731 (and (org-at-heading-p t)
6732 (> (funcall outline-level) level))))
6733 (save-excursion
6734 (org-list-search-forward (org-item-beginning-re) eos t)))))
6735 ;; Determine end invisible part of buffer (EOL)
6736 (beginning-of-line 2)
6737 ;; XEmacs doesn't have `next-single-char-property-change'
6738 (if (featurep 'xemacs)
6739 (while (and (not (eobp)) ;; this is like `next-line'
6740 (get-char-property (1- (point)) 'invisible))
6741 (beginning-of-line 2))
6742 (while (and (not (eobp)) ;; this is like `next-line'
6743 (get-char-property (1- (point)) 'invisible))
6744 (goto-char (next-single-char-property-change (point) 'invisible))
6745 (and (eolp) (beginning-of-line 2))))
6746 (setq eol (point)))
6747 ;; Find out what to do next and set `this-command'
6748 (cond
6749 ((= eos eoh)
6750 ;; Nothing is hidden behind this heading
6751 (unless (org-before-first-heading-p)
6752 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6753 (org-unlogged-message "EMPTY ENTRY")
6754 (setq org-cycle-subtree-status nil)
6755 (save-excursion
6756 (goto-char eos)
6757 (outline-next-heading)
6758 (if (outline-invisible-p) (org-flag-heading nil))))
6759 ((and (or (>= eol eos)
6760 (not (string-match "\\S-" (buffer-substring eol eos))))
6761 (or has-children
6762 (not (setq children-skipped
6763 org-cycle-skip-children-state-if-no-children))))
6764 ;; Entire subtree is hidden in one line: children view
6765 (unless (org-before-first-heading-p)
6766 (run-hook-with-args 'org-pre-cycle-hook 'children))
6767 (if (org-at-item-p)
6768 (org-list-set-item-visibility (point-at-bol) struct 'children)
6769 (org-show-entry)
6770 (org-with-limited-levels (show-children))
6771 ;; FIXME: This slows down the func way too much.
6772 ;; How keep drawers hidden in subtree anyway?
6773 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6774 ;; (org-cycle-hide-drawers 'subtree))
6776 ;; Fold every list in subtree to top-level items.
6777 (when (eq org-cycle-include-plain-lists 'integrate)
6778 (save-excursion
6779 (org-back-to-heading)
6780 (while (org-list-search-forward (org-item-beginning-re) eos t)
6781 (beginning-of-line 1)
6782 (let* ((struct (org-list-struct))
6783 (prevs (org-list-prevs-alist struct))
6784 (end (org-list-get-bottom-point struct)))
6785 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6786 (org-list-get-all-items (point) struct prevs))
6787 (goto-char (if (< end eos) end eos)))))))
6788 (org-unlogged-message "CHILDREN")
6789 (save-excursion
6790 (goto-char eos)
6791 (outline-next-heading)
6792 (if (outline-invisible-p) (org-flag-heading nil)))
6793 (setq org-cycle-subtree-status 'children)
6794 (unless (org-before-first-heading-p)
6795 (run-hook-with-args 'org-cycle-hook 'children)))
6796 ((or children-skipped
6797 (and (eq last-command this-command)
6798 (eq org-cycle-subtree-status 'children)))
6799 ;; We just showed the children, or no children are there,
6800 ;; now show everything.
6801 (unless (org-before-first-heading-p)
6802 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6803 (outline-flag-region eoh eos nil)
6804 (org-unlogged-message
6805 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6806 (setq org-cycle-subtree-status 'subtree)
6807 (unless (org-before-first-heading-p)
6808 (run-hook-with-args 'org-cycle-hook 'subtree)))
6810 ;; Default action: hide the subtree.
6811 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6812 (outline-flag-region eoh eos t)
6813 (org-unlogged-message "FOLDED")
6814 (setq org-cycle-subtree-status 'folded)
6815 (unless (org-before-first-heading-p)
6816 (run-hook-with-args 'org-cycle-hook 'folded))))))
6818 ;;;###autoload
6819 (defun org-global-cycle (&optional arg)
6820 "Cycle the global visibility. For details see `org-cycle'.
6821 With \\[universal-argument] prefix arg, switch to startup visibility.
6822 With a numeric prefix, show all headlines up to that level."
6823 (interactive "P")
6824 (let ((org-cycle-include-plain-lists
6825 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6826 (cond
6827 ((integerp arg)
6828 (show-all)
6829 (hide-sublevels arg)
6830 (setq org-cycle-global-status 'contents))
6831 ((equal arg '(4))
6832 (org-set-startup-visibility)
6833 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6835 (org-cycle '(4))))))
6837 (defun org-set-startup-visibility ()
6838 "Set the visibility required by startup options and properties."
6839 (cond
6840 ((eq org-startup-folded t)
6841 (org-overview))
6842 ((eq org-startup-folded 'content)
6843 (org-content))
6844 ((or (eq org-startup-folded 'showeverything)
6845 (eq org-startup-folded nil))
6846 (show-all)))
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 ((pos (point))
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 (goto-char pos)))
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 (org-overview)
6912 (save-excursion
6913 ;; Visit all headings and show their offspring
6914 (and (integerp arg) (org-overview))
6915 (goto-char (point-max))
6916 (catch 'exit
6917 (while (and (progn (condition-case nil
6918 (outline-previous-visible-heading 1)
6919 (error (goto-char (point-min))))
6921 (looking-at org-outline-regexp))
6922 (if (integerp arg)
6923 (show-children (1- arg))
6924 (show-branches))
6925 (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 tasks when switching to 'contents or 'children
7071 visibility state."
7072 (case state
7073 (contents
7074 (when (org-bound-and-true-p org-inlinetask-min-level)
7075 (hide-sublevels (1- org-inlinetask-min-level))))
7076 (children
7077 (when (featurep 'org-inlinetask)
7078 (save-excursion
7079 (while (and (outline-next-heading)
7080 (org-inlinetask-at-task-p))
7081 (org-inlinetask-toggle-visibility)
7082 (org-inlinetask-goto-end)))))))
7084 (defun org-flag-drawer (flag)
7085 "When FLAG is non-nil, hide the drawer we are within.
7086 Otherwise make it visible."
7087 (save-excursion
7088 (beginning-of-line 1)
7089 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7090 (let ((b (match-end 0)))
7091 (if (re-search-forward
7092 "^[ \t]*:END:"
7093 (save-excursion (outline-next-heading) (point)) t)
7094 (outline-flag-region b (point-at-eol) flag)
7095 (user-error ":END: line missing at position %s" b))))))
7097 (defun org-subtree-end-visible-p ()
7098 "Is the end of the current subtree visible?"
7099 (pos-visible-in-window-p
7100 (save-excursion (org-end-of-subtree t) (point))))
7102 (defun org-first-headline-recenter (&optional N)
7103 "Move cursor to the first headline and recenter the headline.
7104 Optional argument N means put the headline into the Nth line of the window."
7105 (goto-char (point-min))
7106 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7107 (beginning-of-line)
7108 (recenter (prefix-numeric-value N))))
7110 ;;; Saving and restoring visibility
7112 (defun org-outline-overlay-data (&optional use-markers)
7113 "Return a list of the locations of all outline overlays.
7114 These are overlays with the `invisible' property value `outline'.
7115 The return value is a list of cons cells, with start and stop
7116 positions for each overlay.
7117 If USE-MARKERS is set, return the positions as markers."
7118 (let (beg end)
7119 (save-excursion
7120 (save-restriction
7121 (widen)
7122 (delq nil
7123 (mapcar (lambda (o)
7124 (when (eq (overlay-get o 'invisible) 'outline)
7125 (setq beg (overlay-start o)
7126 end (overlay-end o))
7127 (and beg end (> end beg)
7128 (if use-markers
7129 (cons (move-marker (make-marker) beg)
7130 (move-marker (make-marker) end))
7131 (cons beg end)))))
7132 (overlays-in (point-min) (point-max))))))))
7134 (defun org-set-outline-overlay-data (data)
7135 "Create visibility overlays for all positions in DATA.
7136 DATA should have been made by `org-outline-overlay-data'."
7137 (let (o)
7138 (save-excursion
7139 (save-restriction
7140 (widen)
7141 (show-all)
7142 (mapc (lambda (c)
7143 (outline-flag-region (car c) (cdr c) t))
7144 data)))))
7146 ;;; Folding of blocks
7148 (defvar org-hide-block-overlays nil
7149 "Overlays hiding blocks.")
7150 (make-variable-buffer-local 'org-hide-block-overlays)
7152 (defun org-block-map (function &optional start end)
7153 "Call FUNCTION at the head of all source blocks in the current buffer.
7154 Optional arguments START and END can be used to limit the range."
7155 (let ((start (or start (point-min)))
7156 (end (or end (point-max))))
7157 (save-excursion
7158 (goto-char start)
7159 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7160 (save-excursion
7161 (save-match-data
7162 (goto-char (match-beginning 0))
7163 (funcall function)))))))
7165 (defun org-hide-block-toggle-all ()
7166 "Toggle the visibility of all blocks in the current buffer."
7167 (org-block-map #'org-hide-block-toggle))
7169 (defun org-hide-block-all ()
7170 "Fold all blocks in the current buffer."
7171 (interactive)
7172 (org-show-block-all)
7173 (org-block-map #'org-hide-block-toggle-maybe))
7175 (defun org-show-block-all ()
7176 "Unfold all blocks in the current buffer."
7177 (interactive)
7178 (mapc 'delete-overlay org-hide-block-overlays)
7179 (setq org-hide-block-overlays nil))
7181 (defun org-hide-block-toggle-maybe ()
7182 "Toggle visibility of block at point."
7183 (interactive)
7184 (let ((case-fold-search t))
7185 (if (save-excursion
7186 (beginning-of-line 1)
7187 (looking-at org-block-regexp))
7188 (progn (org-hide-block-toggle)
7189 t) ;; to signal that we took action
7190 nil))) ;; to signal that we did not
7192 (defun org-hide-block-toggle (&optional force)
7193 "Toggle the visibility of the current block."
7194 (interactive)
7195 (save-excursion
7196 (beginning-of-line)
7197 (if (re-search-forward org-block-regexp nil t)
7198 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7199 (end (match-end 0)) ;; end of entire body
7201 (if (memq t (mapcar (lambda (overlay)
7202 (eq (overlay-get overlay 'invisible)
7203 'org-hide-block))
7204 (overlays-at start)))
7205 (if (or (not force) (eq force 'off))
7206 (mapc (lambda (ov)
7207 (when (member ov org-hide-block-overlays)
7208 (setq org-hide-block-overlays
7209 (delq ov org-hide-block-overlays)))
7210 (when (eq (overlay-get ov 'invisible)
7211 'org-hide-block)
7212 (delete-overlay ov)))
7213 (overlays-at start)))
7214 (setq ov (make-overlay start end))
7215 (overlay-put ov 'invisible 'org-hide-block)
7216 ;; make the block accessible to isearch
7217 (overlay-put
7218 ov 'isearch-open-invisible
7219 (lambda (ov)
7220 (when (member ov org-hide-block-overlays)
7221 (setq org-hide-block-overlays
7222 (delq ov org-hide-block-overlays)))
7223 (when (eq (overlay-get ov 'invisible)
7224 'org-hide-block)
7225 (delete-overlay ov))))
7226 (push ov org-hide-block-overlays)))
7227 (user-error "Not looking at a source block"))))
7229 ;; org-tab-after-check-for-cycling-hook
7230 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7231 ;; Remove overlays when changing major mode
7232 (add-hook 'org-mode-hook
7233 (lambda () (org-add-hook 'change-major-mode-hook
7234 'org-show-block-all 'append 'local)))
7236 ;;; Org-goto
7238 (defvar org-goto-window-configuration nil)
7239 (defvar org-goto-marker nil)
7240 (defvar org-goto-map)
7241 (defun org-goto-map ()
7242 "Set the keymap `org-goto'."
7243 (setq org-goto-map
7244 (let ((map (make-sparse-keymap)))
7245 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7246 mouse-drag-region universal-argument org-occur))
7247 cmd)
7248 (while (setq cmd (pop cmds))
7249 (substitute-key-definition cmd cmd map global-map)))
7250 (suppress-keymap map)
7251 (org-defkey map "\C-m" 'org-goto-ret)
7252 (org-defkey map [(return)] 'org-goto-ret)
7253 (org-defkey map [(left)] 'org-goto-left)
7254 (org-defkey map [(right)] 'org-goto-right)
7255 (org-defkey map [(control ?g)] 'org-goto-quit)
7256 (org-defkey map "\C-i" 'org-cycle)
7257 (org-defkey map [(tab)] 'org-cycle)
7258 (org-defkey map [(down)] 'outline-next-visible-heading)
7259 (org-defkey map [(up)] 'outline-previous-visible-heading)
7260 (if org-goto-auto-isearch
7261 (if (fboundp 'define-key-after)
7262 (define-key-after map [t] 'org-goto-local-auto-isearch)
7263 nil)
7264 (org-defkey map "q" 'org-goto-quit)
7265 (org-defkey map "n" 'outline-next-visible-heading)
7266 (org-defkey map "p" 'outline-previous-visible-heading)
7267 (org-defkey map "f" 'outline-forward-same-level)
7268 (org-defkey map "b" 'outline-backward-same-level)
7269 (org-defkey map "u" 'outline-up-heading))
7270 (org-defkey map "/" 'org-occur)
7271 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7272 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7273 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7274 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7275 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7276 map)))
7278 (defconst org-goto-help
7279 "Browse buffer copy, to find location or copy text.%s
7280 RET=jump to location C-g=quit and return to previous location
7281 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7283 (defvar org-goto-start-pos) ; dynamically scoped parameter
7285 (defun org-goto (&optional alternative-interface)
7286 "Look up a different location in the current file, keeping current visibility.
7288 When you want look-up or go to a different location in a
7289 document, the fastest way is often to fold the entire buffer and
7290 then dive into the tree. This method has the disadvantage, that
7291 the previous location will be folded, which may not be what you
7292 want.
7294 This command works around this by showing a copy of the current
7295 buffer in an indirect buffer, in overview mode. You can dive
7296 into the tree in that copy, use org-occur and incremental search
7297 to find a location. When pressing RET or `Q', the command
7298 returns to the original buffer in which the visibility is still
7299 unchanged. After RET it will also jump to the location selected
7300 in the indirect buffer and expose the headline hierarchy above.
7302 With a prefix argument, use the alternative interface: e.g. if
7303 `org-goto-interface' is 'outline use 'outline-path-completion."
7304 (interactive "P")
7305 (org-goto-map)
7306 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7307 (org-refile-use-outline-path t)
7308 (org-refile-target-verify-function nil)
7309 (interface
7310 (if (not alternative-interface)
7311 org-goto-interface
7312 (if (eq org-goto-interface 'outline)
7313 'outline-path-completion
7314 'outline)))
7315 (org-goto-start-pos (point))
7316 (selected-point
7317 (if (eq interface 'outline)
7318 (car (org-get-location (current-buffer) org-goto-help))
7319 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7320 (org-refile-check-position pa)
7321 (nth 3 pa)))))
7322 (if selected-point
7323 (progn
7324 (org-mark-ring-push org-goto-start-pos)
7325 (goto-char selected-point)
7326 (if (or (outline-invisible-p) (org-invisible-p2))
7327 (org-show-context 'org-goto)))
7328 (message "Quit"))))
7330 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7331 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7332 (defvar org-goto-local-auto-isearch-map) ; defined below
7334 (defun org-get-location (buf help)
7335 "Let the user select a location in the Org-mode buffer BUF.
7336 This function uses a recursive edit. It returns the selected position
7337 or nil."
7338 (org-no-popups
7339 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7340 (isearch-hide-immediately nil)
7341 (isearch-search-fun-function
7342 (lambda () 'org-goto-local-search-headings))
7343 (org-goto-selected-point org-goto-exit-command))
7344 (save-excursion
7345 (save-window-excursion
7346 (delete-other-windows)
7347 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7348 (org-pop-to-buffer-same-window
7349 (condition-case nil
7350 (make-indirect-buffer (current-buffer) "*org-goto*")
7351 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7352 (with-output-to-temp-buffer "*Org Help*"
7353 (princ (format help (if org-goto-auto-isearch
7354 " Just type for auto-isearch."
7355 " n/p/f/b/u to navigate, q to quit."))))
7356 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7357 (setq buffer-read-only nil)
7358 (let ((org-startup-truncated t)
7359 (org-startup-folded nil)
7360 (org-startup-align-all-tables nil))
7361 (org-mode)
7362 (org-overview))
7363 (setq buffer-read-only t)
7364 (if (and (boundp 'org-goto-start-pos)
7365 (integer-or-marker-p org-goto-start-pos))
7366 (let ((org-show-hierarchy-above t)
7367 (org-show-siblings t)
7368 (org-show-following-heading t))
7369 (goto-char org-goto-start-pos)
7370 (and (outline-invisible-p) (org-show-context)))
7371 (goto-char (point-min)))
7372 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7373 (message "Select location and press RET")
7374 (use-local-map org-goto-map)
7375 (recursive-edit)))
7376 (kill-buffer "*org-goto*")
7377 (cons org-goto-selected-point org-goto-exit-command))))
7379 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7380 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7381 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7382 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7384 (defun org-goto-local-search-headings (string bound noerror)
7385 "Search and make sure that any matches are in headlines."
7386 (catch 'return
7387 (while (if isearch-forward
7388 (search-forward string bound noerror)
7389 (search-backward string bound noerror))
7390 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7391 (and (member :headline context)
7392 (not (member :tags context))))
7393 (throw 'return (point))))))
7395 (defun org-goto-local-auto-isearch ()
7396 "Start isearch."
7397 (interactive)
7398 (goto-char (point-min))
7399 (let ((keys (this-command-keys)))
7400 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7401 (isearch-mode t)
7402 (isearch-process-search-char (string-to-char keys)))))
7404 (defun org-goto-ret (&optional arg)
7405 "Finish `org-goto' by going to the new location."
7406 (interactive "P")
7407 (setq org-goto-selected-point (point)
7408 org-goto-exit-command 'return)
7409 (throw 'exit nil))
7411 (defun org-goto-left ()
7412 "Finish `org-goto' by going to the new location."
7413 (interactive)
7414 (if (org-at-heading-p)
7415 (progn
7416 (beginning-of-line 1)
7417 (setq org-goto-selected-point (point)
7418 org-goto-exit-command 'left)
7419 (throw 'exit nil))
7420 (user-error "Not on a heading")))
7422 (defun org-goto-right ()
7423 "Finish `org-goto' by going to the new location."
7424 (interactive)
7425 (if (org-at-heading-p)
7426 (progn
7427 (setq org-goto-selected-point (point)
7428 org-goto-exit-command 'right)
7429 (throw 'exit nil))
7430 (user-error "Not on a heading")))
7432 (defun org-goto-quit ()
7433 "Finish `org-goto' without cursor motion."
7434 (interactive)
7435 (setq org-goto-selected-point nil)
7436 (setq org-goto-exit-command 'quit)
7437 (throw 'exit nil))
7439 ;;; Indirect buffer display of subtrees
7441 (defvar org-indirect-dedicated-frame nil
7442 "This is the frame being used for indirect tree display.")
7443 (defvar org-last-indirect-buffer nil)
7445 (defun org-tree-to-indirect-buffer (&optional arg)
7446 "Create indirect buffer and narrow it to current subtree.
7447 With a numerical prefix ARG, go up to this level and then take that tree.
7448 If ARG is negative, go up that many levels.
7450 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7451 indirect buffer previously made with this command, to avoid proliferation of
7452 indirect buffers. However, when you call the command with a \
7453 \\[universal-argument] prefix, or
7454 when `org-indirect-buffer-display' is `new-frame', the last buffer
7455 is kept so that you can work with several indirect buffers at the same time.
7456 If `org-indirect-buffer-display' is `dedicated-frame', the \
7457 \\[universal-argument] prefix also
7458 requests that a new frame be made for the new buffer, so that the dedicated
7459 frame is not changed."
7460 (interactive "P")
7461 (let ((cbuf (current-buffer))
7462 (cwin (selected-window))
7463 (pos (point))
7464 beg end level heading ibuf)
7465 (save-excursion
7466 (org-back-to-heading t)
7467 (when (numberp arg)
7468 (setq level (org-outline-level))
7469 (if (< arg 0) (setq arg (+ level arg)))
7470 (while (> (setq level (org-outline-level)) arg)
7471 (org-up-heading-safe)))
7472 (setq beg (point)
7473 heading (org-get-heading))
7474 (org-end-of-subtree t t)
7475 (if (org-at-heading-p) (backward-char 1))
7476 (setq end (point)))
7477 (if (and (buffer-live-p org-last-indirect-buffer)
7478 (not (eq org-indirect-buffer-display 'new-frame))
7479 (not arg))
7480 (kill-buffer org-last-indirect-buffer))
7481 (setq ibuf (org-get-indirect-buffer cbuf)
7482 org-last-indirect-buffer ibuf)
7483 (cond
7484 ((or (eq org-indirect-buffer-display 'new-frame)
7485 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7486 (select-frame (make-frame))
7487 (delete-other-windows)
7488 (org-pop-to-buffer-same-window ibuf)
7489 (org-set-frame-title heading))
7490 ((eq org-indirect-buffer-display 'dedicated-frame)
7491 (raise-frame
7492 (select-frame (or (and org-indirect-dedicated-frame
7493 (frame-live-p org-indirect-dedicated-frame)
7494 org-indirect-dedicated-frame)
7495 (setq org-indirect-dedicated-frame (make-frame)))))
7496 (delete-other-windows)
7497 (org-pop-to-buffer-same-window ibuf)
7498 (org-set-frame-title (concat "Indirect: " heading)))
7499 ((eq org-indirect-buffer-display 'current-window)
7500 (org-pop-to-buffer-same-window ibuf))
7501 ((eq org-indirect-buffer-display 'other-window)
7502 (pop-to-buffer ibuf))
7503 (t (error "Invalid value")))
7504 (if (featurep 'xemacs)
7505 (save-excursion (org-mode) (turn-on-font-lock)))
7506 (narrow-to-region beg end)
7507 (show-all)
7508 (goto-char pos)
7509 (run-hook-with-args 'org-cycle-hook 'all)
7510 (and (window-live-p cwin) (select-window cwin))))
7512 (defun org-get-indirect-buffer (&optional buffer)
7513 (setq buffer (or buffer (current-buffer)))
7514 (let ((n 1) (base (buffer-name buffer)) bname)
7515 (while (buffer-live-p
7516 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7517 (setq n (1+ n)))
7518 (condition-case nil
7519 (make-indirect-buffer buffer bname 'clone)
7520 (error (make-indirect-buffer buffer bname)))))
7522 (defun org-set-frame-title (title)
7523 "Set the title of the current frame to the string TITLE."
7524 ;; FIXME: how to name a single frame in XEmacs???
7525 (unless (featurep 'xemacs)
7526 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7528 ;;;; Structure editing
7530 ;;; Inserting headlines
7532 (defun org-previous-line-empty-p (&optional next)
7533 "Is the previous line a blank line?
7534 When NEXT is non-nil, check the next line instead."
7535 (save-excursion
7536 (and (not (bobp))
7537 (or (beginning-of-line (if next 2 0)) t)
7538 (save-match-data
7539 (looking-at "[ \t]*$")))))
7541 (defun org-insert-heading (&optional arg invisible-ok)
7542 "Insert a new heading or item with same depth at point.
7543 If point is in a plain list and ARG is nil, create a new list item.
7544 With one universal prefix argument, insert a heading even in lists.
7545 With two universal prefix arguments, insert the heading at the end
7546 of the parent subtree.
7548 If point is at the beginning of a headline, insert a sibling before
7549 the current headline. If point is not at the beginning, split the line
7550 and create a new headline with the text in the current line after point
7551 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7553 If point is at the beginning of a normal line, turn this line into
7554 a heading.
7556 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7557 This is important for non-interactive uses of the command."
7558 (interactive "P")
7559 (if (org-called-interactively-p 'any) (org-reveal))
7560 (let ((itemp (org-in-item-p))
7561 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7562 (respect-content (or org-insert-heading-respect-content
7563 (equal arg '(4))))
7564 (initial-content "")
7565 (adjust-empty-lines t))
7567 (cond
7569 ((or (= (buffer-size) 0)
7570 (and (not (save-excursion
7571 (and (ignore-errors (org-back-to-heading invisible-ok))
7572 (org-at-heading-p))))
7573 (or arg (not itemp))))
7574 ;; At beginning of buffer or so high up that only a heading
7575 ;; makes sense.
7576 (insert
7577 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7578 (if (org-in-src-block-p) ",* " "* "))
7579 (run-hooks 'org-insert-heading-hook))
7581 ((and itemp (not (equal arg '(4))))
7582 ;; Insert an item
7583 (org-insert-item))
7586 ;; Maybe move at the end of the subtree
7587 (when (equal arg '(16))
7588 (org-up-heading-safe)
7589 (org-end-of-subtree t))
7590 ;; Insert a heading
7591 (save-restriction
7592 (widen)
7593 (let* ((level nil)
7594 (on-heading (org-at-heading-p))
7595 (empty-line-p (if on-heading
7596 (org-previous-line-empty-p)
7597 ;; We will decide later
7598 nil))
7599 ;; Get a level string to fall back on
7600 (fix-level
7601 (save-excursion
7602 (org-back-to-heading t)
7603 (if (org-previous-line-empty-p) (setq empty-line-p t))
7604 (looking-at org-outline-regexp)
7605 (make-string (1- (length (match-string 0))) ?*)))
7606 (stars
7607 (save-excursion
7608 (condition-case nil
7609 (progn
7610 (org-back-to-heading invisible-ok)
7611 (when (and (not on-heading)
7612 (featurep 'org-inlinetask)
7613 (integerp org-inlinetask-min-level)
7614 (>= (length (match-string 0))
7615 org-inlinetask-min-level))
7616 ;; Find a heading level before the inline task
7617 (while (and (setq level (org-up-heading-safe))
7618 (>= level org-inlinetask-min-level)))
7619 (if (org-at-heading-p)
7620 (org-back-to-heading invisible-ok)
7621 (error "This should not happen")))
7622 (unless (and (save-excursion
7623 (save-match-data
7624 (org-backward-heading-same-level
7625 1 invisible-ok))
7626 (= (point) (match-beginning 0)))
7627 (not (org-previous-line-empty-p t)))
7628 (setq empty-line-p (or empty-line-p
7629 (org-previous-line-empty-p))))
7630 (match-string 0))
7631 (error (or fix-level "* ")))))
7632 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7633 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7634 pos hide-previous previous-pos)
7636 ;; If we insert after content, move there and clean up whitespace
7637 (when respect-content
7638 (org-end-of-subtree nil t)
7639 (skip-chars-backward " \r\n")
7640 (and (not (looking-back "^\*+"))
7641 (looking-at "[ \t]+") (replace-match ""))
7642 (unless (eobp) (forward-char 1))
7643 (when (looking-at "^\\*")
7644 (unless (bobp) (backward-char 1))
7645 (insert "\n")))
7647 ;; If we are splitting, grab the text that should be moved to the new headline
7648 (when may-split
7649 (if (org-on-heading-p)
7650 ;; This is a heading, we split intelligently (keeping tags)
7651 (let ((pos (point)))
7652 (goto-char (point-at-bol))
7653 (unless (looking-at org-complex-heading-regexp)
7654 (error "This should not happen"))
7655 (when (and (match-beginning 4)
7656 (> pos (match-beginning 4))
7657 (< pos (match-end 4)))
7658 (setq initial-content (buffer-substring pos (match-end 4)))
7659 (goto-char pos)
7660 (delete-region (point) (match-end 4))
7661 (if (looking-at "[ \t]*$")
7662 (replace-match "")
7663 (insert (make-string (length initial-content) ?\ )))
7664 (setq initial-content (org-trim initial-content)))
7665 (goto-char pos))
7666 ;; a normal line
7667 (unless (bolp)
7668 (setq initial-content (buffer-substring (point) (point-at-eol)))
7669 (delete-region (point) (point-at-eol))
7670 (setq initial-content (org-trim initial-content)))))
7672 ;; If we are at the beginning of the line, insert before it. Else after
7673 (cond
7674 ((and (bolp) (looking-at "[ \t]*$")))
7675 ((and (bolp) (not (looking-at "[ \t]*$")))
7676 (open-line 1))
7678 (goto-char (point-at-eol))
7679 (insert "\n")))
7681 ;; Insert the new heading
7682 (insert stars)
7683 (just-one-space)
7684 (insert initial-content)
7685 (when adjust-empty-lines
7686 (if (or (not blank)
7687 (and blank (not (org-previous-line-empty-p))))
7688 (org-N-empty-lines-before-current (if blank 1 0))))
7689 (run-hooks 'org-insert-heading-hook)))))))
7691 (defun org-N-empty-lines-before-current (N)
7692 "Make the number of empty lines before current exactly N.
7693 So this will delete or add empty lines."
7694 (save-excursion
7695 (goto-char (point-at-bol))
7696 (if (looking-back "\\s-+" nil 'greedy)
7697 (replace-match ""))
7698 (or (bobp) (insert "\n"))
7699 (while (> N 0)
7700 (insert "\n")
7701 (setq N (1- N)))))
7703 (defun org-get-heading (&optional no-tags no-todo)
7704 "Return the heading of the current entry, without the stars.
7705 When NO-TAGS is non-nil, don't include tags.
7706 When NO-TODO is non-nil, don't include TODO keywords."
7707 (save-excursion
7708 (org-back-to-heading t)
7709 (cond
7710 ((and no-tags no-todo)
7711 (looking-at org-complex-heading-regexp)
7712 (match-string 4))
7713 (no-tags
7714 (looking-at (concat org-outline-regexp
7715 "\\(.*?\\)"
7716 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7717 (match-string 1))
7718 (no-todo
7719 (looking-at org-todo-line-regexp)
7720 (match-string 3))
7721 (t (looking-at org-heading-regexp)
7722 (match-string 2)))))
7724 (defvar orgstruct-mode) ; defined below
7726 (defun org-heading-components ()
7727 "Return the components of the current heading.
7728 This is a list with the following elements:
7729 - the level as an integer
7730 - the reduced level, different if `org-odd-levels-only' is set.
7731 - the TODO keyword, or nil
7732 - the priority character, like ?A, or nil if no priority is given
7733 - the headline text itself, or the tags string if no headline text
7734 - the tags string, or nil."
7735 (save-excursion
7736 (org-back-to-heading t)
7737 (if (let (case-fold-search)
7738 (looking-at
7739 (if orgstruct-mode
7740 org-heading-regexp
7741 org-complex-heading-regexp)))
7742 (if orgstruct-mode
7743 (list (length (match-string 1))
7744 (org-reduced-level (length (match-string 1)))
7747 (match-string 2)
7748 nil)
7749 (list (length (match-string 1))
7750 (org-reduced-level (length (match-string 1)))
7751 (org-match-string-no-properties 2)
7752 (and (match-end 3) (aref (match-string 3) 2))
7753 (org-match-string-no-properties 4)
7754 (org-match-string-no-properties 5))))))
7756 (defun org-get-entry ()
7757 "Get the entry text, after heading, entire subtree."
7758 (save-excursion
7759 (org-back-to-heading t)
7760 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7762 (defun org-insert-heading-after-current ()
7763 "Insert a new heading with same level as current, after current subtree."
7764 (interactive)
7765 (org-back-to-heading)
7766 (org-insert-heading)
7767 (org-move-subtree-down)
7768 (end-of-line 1))
7770 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7771 "Insert heading with `org-insert-heading-respect-content' set to t."
7772 (interactive "P")
7773 (let ((org-insert-heading-respect-content t))
7774 (org-insert-heading '(4) invisible-ok)))
7776 (defun org-insert-todo-heading-respect-content (&optional force-state)
7777 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7778 (interactive "P")
7779 (let ((org-insert-heading-respect-content t))
7780 (org-insert-todo-heading force-state '(4))))
7782 (defun org-insert-todo-heading (arg &optional force-heading)
7783 "Insert a new heading with the same level and TODO state as current heading.
7784 If the heading has no TODO state, or if the state is DONE, use the first
7785 state (TODO by default). Also with one prefix arg, force first state. With
7786 two prefix args, force inserting at the end of the parent subtree."
7787 (interactive "P")
7788 (when (or force-heading (not (org-insert-item 'checkbox)))
7789 (org-insert-heading (or (and (equal arg '(16)) '(16))
7790 force-heading))
7791 (save-excursion
7792 (org-back-to-heading)
7793 (outline-previous-heading)
7794 (looking-at org-todo-line-regexp))
7795 (let*
7796 ((new-mark-x
7797 (if (or (equal arg '(4))
7798 (not (match-beginning 2))
7799 (member (match-string 2) org-done-keywords))
7800 (car org-todo-keywords-1)
7801 (match-string 2)))
7802 (new-mark
7804 (run-hook-with-args-until-success
7805 'org-todo-get-default-hook new-mark-x nil)
7806 new-mark-x)))
7807 (beginning-of-line 1)
7808 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7809 (if org-treat-insert-todo-heading-as-state-change
7810 (org-todo new-mark)
7811 (insert new-mark " "))))
7812 (when org-provide-todo-statistics
7813 (org-update-parent-todo-statistics))))
7815 (defun org-insert-subheading (arg)
7816 "Insert a new subheading and demote it.
7817 Works for outline headings and for plain lists alike."
7818 (interactive "P")
7819 (org-insert-heading arg)
7820 (cond
7821 ((org-at-heading-p) (org-do-demote))
7822 ((org-at-item-p) (org-indent-item))))
7824 (defun org-insert-todo-subheading (arg)
7825 "Insert a new subheading with TODO keyword or checkbox and demote it.
7826 Works for outline headings and for plain lists alike."
7827 (interactive "P")
7828 (org-insert-todo-heading arg)
7829 (cond
7830 ((org-at-heading-p) (org-do-demote))
7831 ((org-at-item-p) (org-indent-item))))
7833 ;;; Promotion and Demotion
7835 (defvar org-after-demote-entry-hook nil
7836 "Hook run after an entry has been demoted.
7837 The cursor will be at the beginning of the entry.
7838 When a subtree is being demoted, the hook will be called for each node.")
7840 (defvar org-after-promote-entry-hook nil
7841 "Hook run after an entry has been promoted.
7842 The cursor will be at the beginning of the entry.
7843 When a subtree is being promoted, the hook will be called for each node.")
7845 (defun org-promote-subtree ()
7846 "Promote the entire subtree.
7847 See also `org-promote'."
7848 (interactive)
7849 (save-excursion
7850 (org-with-limited-levels (org-map-tree 'org-promote)))
7851 (org-fix-position-after-promote))
7853 (defun org-demote-subtree ()
7854 "Demote the entire subtree. See `org-demote'.
7855 See also `org-promote'."
7856 (interactive)
7857 (save-excursion
7858 (org-with-limited-levels (org-map-tree 'org-demote)))
7859 (org-fix-position-after-promote))
7862 (defun org-do-promote ()
7863 "Promote the current heading higher up the tree.
7864 If the region is active in `transient-mark-mode', promote all headings
7865 in the region."
7866 (interactive)
7867 (save-excursion
7868 (if (org-region-active-p)
7869 (org-map-region 'org-promote (region-beginning) (region-end))
7870 (org-promote)))
7871 (org-fix-position-after-promote))
7873 (defun org-do-demote ()
7874 "Demote the current heading lower down the tree.
7875 If the region is active in `transient-mark-mode', demote all headings
7876 in the region."
7877 (interactive)
7878 (save-excursion
7879 (if (org-region-active-p)
7880 (org-map-region 'org-demote (region-beginning) (region-end))
7881 (org-demote)))
7882 (org-fix-position-after-promote))
7884 (defun org-fix-position-after-promote ()
7885 "Make sure that after pro/demotion cursor position is right."
7886 (let ((pos (point)))
7887 (when (save-excursion
7888 (beginning-of-line 1)
7889 (looking-at org-todo-line-regexp)
7890 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7891 (cond ((eobp) (insert " "))
7892 ((eolp) (insert " "))
7893 ((equal (char-after) ?\ ) (forward-char 1))))))
7895 (defun org-current-level ()
7896 "Return the level of the current entry, or nil if before the first headline.
7897 The level is the number of stars at the beginning of the headline."
7898 (save-excursion
7899 (org-with-limited-levels
7900 (if (ignore-errors (org-back-to-heading t))
7901 (funcall outline-level)))))
7903 (defun org-get-previous-line-level ()
7904 "Return the outline depth of the last headline before the current line.
7905 Returns 0 for the first headline in the buffer, and nil if before the
7906 first headline."
7907 (and (org-current-level)
7908 (or (and (/= (line-beginning-position) (point-min))
7909 (save-excursion (beginning-of-line 0) (org-current-level)))
7910 0)))
7912 (defun org-reduced-level (l)
7913 "Compute the effective level of a heading.
7914 This takes into account the setting of `org-odd-levels-only'."
7915 (cond
7916 ((zerop l) 0)
7917 (org-odd-levels-only (1+ (floor (/ l 2))))
7918 (t l)))
7920 (defun org-level-increment ()
7921 "Return the number of stars that will be added or removed at a
7922 time to headlines when structure editing, based on the value of
7923 `org-odd-levels-only'."
7924 (if org-odd-levels-only 2 1))
7926 (defun org-get-valid-level (level &optional change)
7927 "Rectify a level change under the influence of `org-odd-levels-only'
7928 LEVEL is a current level, CHANGE is by how much the level should be
7929 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7930 even level numbers will become the next higher odd number."
7931 (if org-odd-levels-only
7932 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7933 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7934 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7935 (max 1 (+ level (or change 0)))))
7937 (if (boundp 'define-obsolete-function-alias)
7938 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7939 (define-obsolete-function-alias 'org-get-legal-level
7940 'org-get-valid-level)
7941 (define-obsolete-function-alias 'org-get-legal-level
7942 'org-get-valid-level "23.1")))
7944 (defun org-promote ()
7945 "Promote the current heading higher up the tree.
7946 If the region is active in `transient-mark-mode', promote all headings
7947 in the region."
7948 (org-back-to-heading t)
7949 (let* ((level (save-match-data (funcall outline-level)))
7950 (after-change-functions (remove 'flyspell-after-change-function
7951 after-change-functions))
7952 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7953 (diff (abs (- level (length up-head) -1))))
7954 (cond ((and (= level 1) org-called-with-limited-levels
7955 org-allow-promoting-top-level-subtree)
7956 (replace-match "# " nil t))
7957 ((= level 1)
7958 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7959 (t (replace-match up-head nil t)))
7960 ;; Fixup tag positioning
7961 (unless (= level 1)
7962 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7963 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7964 (run-hooks 'org-after-promote-entry-hook)))
7966 (defun org-demote ()
7967 "Demote the current heading lower down the tree.
7968 If the region is active in `transient-mark-mode', demote all headings
7969 in the region."
7970 (org-back-to-heading t)
7971 (let* ((level (save-match-data (funcall outline-level)))
7972 (after-change-functions (remove 'flyspell-after-change-function
7973 after-change-functions))
7974 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7975 (diff (abs (- level (length down-head) -1))))
7976 (replace-match down-head nil t)
7977 ;; Fixup tag positioning
7978 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7979 (if org-adapt-indentation (org-fixup-indentation diff))
7980 (run-hooks 'org-after-demote-entry-hook)))
7982 (defun org-cycle-level ()
7983 "Cycle the level of an empty headline through possible states.
7984 This goes first to child, then to parent, level, then up the hierarchy.
7985 After top level, it switches back to sibling level."
7986 (interactive)
7987 (let ((org-adapt-indentation nil))
7988 (when (org-point-at-end-of-empty-headline)
7989 (setq this-command 'org-cycle-level) ; Only needed for caching
7990 (let ((cur-level (org-current-level))
7991 (prev-level (org-get-previous-line-level)))
7992 (cond
7993 ;; If first headline in file, promote to top-level.
7994 ((= prev-level 0)
7995 (loop repeat (/ (- cur-level 1) (org-level-increment))
7996 do (org-do-promote)))
7997 ;; If same level as prev, demote one.
7998 ((= prev-level cur-level)
7999 (org-do-demote))
8000 ;; If parent is top-level, promote to top level if not already.
8001 ((= prev-level 1)
8002 (loop repeat (/ (- cur-level 1) (org-level-increment))
8003 do (org-do-promote)))
8004 ;; If top-level, return to prev-level.
8005 ((= cur-level 1)
8006 (loop repeat (/ (- prev-level 1) (org-level-increment))
8007 do (org-do-demote)))
8008 ;; If less than prev-level, promote one.
8009 ((< cur-level prev-level)
8010 (org-do-promote))
8011 ;; If deeper than prev-level, promote until higher than
8012 ;; prev-level.
8013 ((> cur-level prev-level)
8014 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8015 do (org-do-promote))))
8016 t))))
8018 (defun org-map-tree (fun)
8019 "Call FUN for every heading underneath the current one."
8020 (org-back-to-heading)
8021 (let ((level (funcall outline-level)))
8022 (save-excursion
8023 (funcall fun)
8024 (while (and (progn
8025 (outline-next-heading)
8026 (> (funcall outline-level) level))
8027 (not (eobp)))
8028 (funcall fun)))))
8030 (defun org-map-region (fun beg end)
8031 "Call FUN for every heading between BEG and END."
8032 (let ((org-ignore-region t))
8033 (save-excursion
8034 (setq end (copy-marker end))
8035 (goto-char beg)
8036 (if (and (re-search-forward org-outline-regexp-bol nil t)
8037 (< (point) end))
8038 (funcall fun))
8039 (while (and (progn
8040 (outline-next-heading)
8041 (< (point) end))
8042 (not (eobp)))
8043 (funcall fun)))))
8045 (defvar org-property-end-re) ; silence byte-compiler
8046 (defun org-fixup-indentation (diff)
8047 "Change the indentation in the current entry by DIFF.
8048 However, if any line in the current entry has no indentation, or if it
8049 would end up with no indentation after the change, nothing at all is done."
8050 (save-excursion
8051 (let ((end (save-excursion (outline-next-heading)
8052 (point-marker)))
8053 (prohibit (if (> diff 0)
8054 "^\\S-"
8055 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8056 col)
8057 (unless (save-excursion (end-of-line 1)
8058 (re-search-forward prohibit end t))
8059 (while (and (< (point) end)
8060 (re-search-forward "^[ \t]+" end t))
8061 (goto-char (match-end 0))
8062 (setq col (current-column))
8063 (if (< diff 0) (replace-match ""))
8064 (org-indent-to-column (+ diff col))))
8065 (move-marker end nil))))
8067 (defun org-convert-to-odd-levels ()
8068 "Convert an org-mode file with all levels allowed to one with odd levels.
8069 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8070 level 5 etc."
8071 (interactive)
8072 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8073 (let ((outline-level 'org-outline-level)
8074 (org-odd-levels-only nil) n)
8075 (save-excursion
8076 (goto-char (point-min))
8077 (while (re-search-forward "^\\*\\*+ " nil t)
8078 (setq n (- (length (match-string 0)) 2))
8079 (while (>= (setq n (1- n)) 0)
8080 (org-demote))
8081 (end-of-line 1))))))
8083 (defun org-convert-to-oddeven-levels ()
8084 "Convert an org-mode file with only odd levels to one with odd/even levels.
8085 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8086 file contains a section with an even level, conversion would
8087 destroy the structure of the file. An error is signaled in this
8088 case."
8089 (interactive)
8090 (goto-char (point-min))
8091 ;; First check if there are no even levels
8092 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8093 (org-show-context t)
8094 (error "Not all levels are odd in this file. Conversion not possible"))
8095 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8096 (let ((outline-regexp org-outline-regexp)
8097 (outline-level 'org-outline-level)
8098 (org-odd-levels-only nil) n)
8099 (save-excursion
8100 (goto-char (point-min))
8101 (while (re-search-forward "^\\*\\*+ " nil t)
8102 (setq n (/ (1- (length (match-string 0))) 2))
8103 (while (>= (setq n (1- n)) 0)
8104 (org-promote))
8105 (end-of-line 1))))))
8107 (defun org-tr-level (n)
8108 "Make N odd if required."
8109 (if org-odd-levels-only (1+ (/ n 2)) n))
8111 ;;; Vertical tree motion, cutting and pasting of subtrees
8113 (defun org-move-subtree-up (&optional arg)
8114 "Move the current subtree up past ARG headlines of the same level."
8115 (interactive "p")
8116 (org-move-subtree-down (- (prefix-numeric-value arg))))
8118 (defun org-move-subtree-down (&optional arg)
8119 "Move the current subtree down past ARG headlines of the same level."
8120 (interactive "p")
8121 (setq arg (prefix-numeric-value arg))
8122 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8123 'org-get-last-sibling))
8124 (ins-point (make-marker))
8125 (cnt (abs arg))
8126 (col (current-column))
8127 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8128 ;; Select the tree
8129 (org-back-to-heading)
8130 (setq beg0 (point))
8131 (save-excursion
8132 (setq ne-beg (org-back-over-empty-lines))
8133 (setq beg (point)))
8134 (save-match-data
8135 (save-excursion (outline-end-of-heading)
8136 (setq folded (outline-invisible-p)))
8137 (outline-end-of-subtree))
8138 (outline-next-heading)
8139 (setq ne-end (org-back-over-empty-lines))
8140 (setq end (point))
8141 (goto-char beg0)
8142 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8143 ;; include less whitespace
8144 (save-excursion
8145 (goto-char beg)
8146 (forward-line (- ne-beg ne-end))
8147 (setq beg (point))))
8148 ;; Find insertion point, with error handling
8149 (while (> cnt 0)
8150 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8151 (progn (goto-char beg0)
8152 (user-error "Cannot move past superior level or buffer limit")))
8153 (setq cnt (1- cnt)))
8154 (if (> arg 0)
8155 ;; Moving forward - still need to move over subtree
8156 (progn (org-end-of-subtree t t)
8157 (save-excursion
8158 (org-back-over-empty-lines)
8159 (or (bolp) (newline)))))
8160 (setq ne-ins (org-back-over-empty-lines))
8161 (move-marker ins-point (point))
8162 (setq txt (buffer-substring beg end))
8163 (org-save-markers-in-region beg end)
8164 (delete-region beg end)
8165 (org-remove-empty-overlays-at beg)
8166 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8167 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8168 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8169 (let ((bbb (point)))
8170 (insert-before-markers txt)
8171 (org-reinstall-markers-in-region bbb)
8172 (move-marker ins-point bbb))
8173 (or (bolp) (insert "\n"))
8174 (setq ins-end (point))
8175 (goto-char ins-point)
8176 (org-skip-whitespace)
8177 (when (and (< arg 0)
8178 (org-first-sibling-p)
8179 (> ne-ins ne-beg))
8180 ;; Move whitespace back to beginning
8181 (save-excursion
8182 (goto-char ins-end)
8183 (let ((kill-whole-line t))
8184 (kill-line (- ne-ins ne-beg)) (point)))
8185 (insert (make-string (- ne-ins ne-beg) ?\n)))
8186 (move-marker ins-point nil)
8187 (if folded
8188 (hide-subtree)
8189 (org-show-entry)
8190 (show-children)
8191 (org-cycle-hide-drawers 'children))
8192 (org-clean-visibility-after-subtree-move)
8193 ;; move back to the initial column we were at
8194 (move-to-column col)))
8196 (defvar org-subtree-clip ""
8197 "Clipboard for cut and paste of subtrees.
8198 This is actually only a copy of the kill, because we use the normal kill
8199 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8201 (defvar org-subtree-clip-folded nil
8202 "Was the last copied subtree folded?
8203 This is used to fold the tree back after pasting.")
8205 (defun org-cut-subtree (&optional n)
8206 "Cut the current subtree into the clipboard.
8207 With prefix arg N, cut this many sequential subtrees.
8208 This is a short-hand for marking the subtree and then cutting it."
8209 (interactive "p")
8210 (org-copy-subtree n 'cut))
8212 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8213 "Copy the current subtree it in the clipboard.
8214 With prefix arg N, copy this many sequential subtrees.
8215 This is a short-hand for marking the subtree and then copying it.
8216 If CUT is non-nil, actually cut the subtree.
8217 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8218 of some markers in the region, even if CUT is non-nil. This is
8219 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8220 (interactive "p")
8221 (let (beg end folded (beg0 (point)))
8222 (if (org-called-interactively-p 'any)
8223 (org-back-to-heading nil) ; take what looks like a subtree
8224 (org-back-to-heading t)) ; take what is really there
8225 (setq beg (point))
8226 (skip-chars-forward " \t\r\n")
8227 (save-match-data
8228 (if nosubtrees
8229 (outline-next-heading)
8230 (save-excursion (outline-end-of-heading)
8231 (setq folded (outline-invisible-p)))
8232 (condition-case nil
8233 (org-forward-heading-same-level (1- n) t)
8234 (error nil))
8235 (org-end-of-subtree t t)))
8236 (setq end (point))
8237 (goto-char beg0)
8238 (when (> end beg)
8239 (setq org-subtree-clip-folded folded)
8240 (when (or cut force-store-markers)
8241 (org-save-markers-in-region beg end))
8242 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8243 (setq org-subtree-clip (current-kill 0))
8244 (message "%s: Subtree(s) with %d characters"
8245 (if cut "Cut" "Copied")
8246 (length org-subtree-clip)))))
8248 (defun org-paste-subtree (&optional level tree for-yank)
8249 "Paste the clipboard as a subtree, with modification of headline level.
8250 The entire subtree is promoted or demoted in order to match a new headline
8251 level.
8253 If the cursor is at the beginning of a headline, the same level as
8254 that headline is used to paste the tree.
8256 If not, the new level is derived from the *visible* headings
8257 before and after the insertion point, and taken to be the inferior headline
8258 level of the two. So if the previous visible heading is level 3 and the
8259 next is level 4 (or vice versa), level 4 will be used for insertion.
8260 This makes sure that the subtree remains an independent subtree and does
8261 not swallow low level entries.
8263 You can also force a different level, either by using a numeric prefix
8264 argument, or by inserting the heading marker by hand. For example, if the
8265 cursor is after \"*****\", then the tree will be shifted to level 5.
8267 If optional TREE is given, use this text instead of the kill ring.
8269 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8270 move back over whitespace before inserting, and move point to the end of
8271 the inserted text when done."
8272 (interactive "P")
8273 (setq tree (or tree (and kill-ring (current-kill 0))))
8274 (unless (org-kill-is-subtree-p tree)
8275 (user-error "%s"
8276 (substitute-command-keys
8277 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8278 (org-with-limited-levels
8279 (let* ((visp (not (outline-invisible-p)))
8280 (txt tree)
8281 (^re_ "\\(\\*+\\)[ \t]*")
8282 (old-level (if (string-match org-outline-regexp-bol txt)
8283 (- (match-end 0) (match-beginning 0) 1)
8284 -1))
8285 (force-level (cond (level (prefix-numeric-value level))
8286 ((and (looking-at "[ \t]*$")
8287 (string-match
8288 "^\\*+$" (buffer-substring
8289 (point-at-bol) (point))))
8290 (- (match-end 1) (match-beginning 1)))
8291 ((and (bolp)
8292 (looking-at org-outline-regexp))
8293 (- (match-end 0) (point) 1))))
8294 (previous-level (save-excursion
8295 (condition-case nil
8296 (progn
8297 (outline-previous-visible-heading 1)
8298 (if (looking-at ^re_)
8299 (- (match-end 0) (match-beginning 0) 1)
8301 (error 1))))
8302 (next-level (save-excursion
8303 (condition-case nil
8304 (progn
8305 (or (looking-at org-outline-regexp)
8306 (outline-next-visible-heading 1))
8307 (if (looking-at ^re_)
8308 (- (match-end 0) (match-beginning 0) 1)
8310 (error 1))))
8311 (new-level (or force-level (max previous-level next-level)))
8312 (shift (if (or (= old-level -1)
8313 (= new-level -1)
8314 (= old-level new-level))
8316 (- new-level old-level)))
8317 (delta (if (> shift 0) -1 1))
8318 (func (if (> shift 0) 'org-demote 'org-promote))
8319 (org-odd-levels-only nil)
8320 beg end newend)
8321 ;; Remove the forced level indicator
8322 (if force-level
8323 (delete-region (point-at-bol) (point)))
8324 ;; Paste
8325 (beginning-of-line (if (bolp) 1 2))
8326 (setq beg (point))
8327 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8328 (insert-before-markers txt)
8329 (unless (string-match "\n\\'" txt) (insert "\n"))
8330 (setq newend (point))
8331 (org-reinstall-markers-in-region beg)
8332 (setq end (point))
8333 (goto-char beg)
8334 (skip-chars-forward " \t\n\r")
8335 (setq beg (point))
8336 (if (and (outline-invisible-p) visp)
8337 (save-excursion (outline-show-heading)))
8338 ;; Shift if necessary
8339 (unless (= shift 0)
8340 (save-restriction
8341 (narrow-to-region beg end)
8342 (while (not (= shift 0))
8343 (org-map-region func (point-min) (point-max))
8344 (setq shift (+ delta shift)))
8345 (goto-char (point-min))
8346 (setq newend (point-max))))
8347 (when (or (org-called-interactively-p 'interactive) for-yank)
8348 (message "Clipboard pasted as level %d subtree" new-level))
8349 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8350 kill-ring
8351 (eq org-subtree-clip (current-kill 0))
8352 org-subtree-clip-folded)
8353 ;; The tree was folded before it was killed/copied
8354 (hide-subtree))
8355 (and for-yank (goto-char newend)))))
8357 (defun org-kill-is-subtree-p (&optional txt)
8358 "Check if the current kill is an outline subtree, or a set of trees.
8359 Returns nil if kill does not start with a headline, or if the first
8360 headline level is not the largest headline level in the tree.
8361 So this will actually accept several entries of equal levels as well,
8362 which is OK for `org-paste-subtree'.
8363 If optional TXT is given, check this string instead of the current kill."
8364 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8365 (re (org-get-limited-outline-regexp))
8366 (^re (concat "^" re))
8367 (start-level (and kill
8368 (string-match
8369 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8370 kill)
8371 (- (match-end 2) (match-beginning 2) 1)))
8372 (start (1+ (or (match-beginning 2) -1))))
8373 (if (not start-level)
8374 (progn
8375 nil) ;; does not even start with a heading
8376 (catch 'exit
8377 (while (setq start (string-match ^re kill (1+ start)))
8378 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8379 (throw 'exit nil)))
8380 t))))
8382 (defvar org-markers-to-move nil
8383 "Markers that should be moved with a cut-and-paste operation.
8384 Those markers are stored together with their positions relative to
8385 the start of the region.")
8387 (defun org-save-markers-in-region (beg end)
8388 "Check markers in region.
8389 If these markers are between BEG and END, record their position relative
8390 to BEG, so that after moving the block of text, we can put the markers back
8391 into place.
8392 This function gets called just before an entry or tree gets cut from the
8393 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8394 called immediately, to move the markers with the entries."
8395 (setq org-markers-to-move nil)
8396 (when (featurep 'org-clock)
8397 (org-clock-save-markers-for-cut-and-paste beg end))
8398 (when (featurep 'org-agenda)
8399 (org-agenda-save-markers-for-cut-and-paste beg end)))
8401 (defun org-check-and-save-marker (marker beg end)
8402 "Check if MARKER is between BEG and END.
8403 If yes, remember the marker and the distance to BEG."
8404 (when (and (marker-buffer marker)
8405 (equal (marker-buffer marker) (current-buffer)))
8406 (if (and (>= marker beg) (< marker end))
8407 (push (cons marker (- marker beg)) org-markers-to-move))))
8409 (defun org-reinstall-markers-in-region (beg)
8410 "Move all remembered markers to their position relative to BEG."
8411 (mapc (lambda (x)
8412 (move-marker (car x) (+ beg (cdr x))))
8413 org-markers-to-move)
8414 (setq org-markers-to-move nil))
8416 (defun org-narrow-to-subtree ()
8417 "Narrow buffer to the current subtree."
8418 (interactive)
8419 (save-excursion
8420 (save-match-data
8421 (org-with-limited-levels
8422 (narrow-to-region
8423 (progn (org-back-to-heading t) (point))
8424 (progn (org-end-of-subtree t t)
8425 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8426 (point)))))))
8428 (defun org-narrow-to-block ()
8429 "Narrow buffer to the current block."
8430 (interactive)
8431 (let* ((case-fold-search t)
8432 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8433 "^[ \t]*#\\+end_.*")))
8434 (if blockp
8435 (narrow-to-region (car blockp) (cdr blockp))
8436 (user-error "Not in a block"))))
8438 (eval-when-compile
8439 (defvar org-property-drawer-re))
8441 (defvar org-property-start-re) ;; defined below
8442 (defun org-clone-subtree-with-time-shift (n &optional shift)
8443 "Clone the task (subtree) at point N times.
8444 The clones will be inserted as siblings.
8446 In interactive use, the user will be prompted for the number of
8447 clones to be produced. If the entry has a timestamp, the user
8448 will also be prompted for a time shift, which may be a repeater
8449 as used in time stamps, for example `+3d'. To disable this,
8450 you can call the function with a universal prefix argument.
8452 When a valid repeater is given and the entry contains any time
8453 stamps, the clones will become a sequence in time, with time
8454 stamps in the subtree shifted for each clone produced. If SHIFT
8455 is nil or the empty string, time stamps will be left alone. The
8456 ID property of the original subtree is removed.
8458 If the original subtree did contain time stamps with a repeater,
8459 the following will happen:
8460 - the repeater will be removed in each clone
8461 - an additional clone will be produced, with the current, unshifted
8462 date(s) in the entry.
8463 - the original entry will be placed *after* all the clones, with
8464 repeater intact.
8465 - the start days in the repeater in the original entry will be shifted
8466 to past the last clone.
8467 In this way you can spell out a number of instances of a repeating task,
8468 and still retain the repeater to cover future instances of the task."
8469 (interactive "nNumber of clones to produce: ")
8470 (let ((shift
8471 (or shift
8472 (if (and (not (equal current-prefix-arg '(4)))
8473 (save-excursion
8474 (re-search-forward org-ts-regexp-both
8475 (save-excursion
8476 (org-end-of-subtree t)
8477 (point)) t)))
8478 (read-from-minibuffer
8479 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8480 ""))) ;; No time shift
8481 (n-no-remove -1)
8482 (drawer-re org-drawer-regexp)
8483 beg end template task idprop
8484 shift-n shift-what doshift nmin nmax)
8485 (if (not (and (integerp n) (> n 0)))
8486 (error "Invalid number of replications %s" n))
8487 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8488 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8489 shift)))
8490 (error "Invalid shift specification %s" shift))
8491 (when doshift
8492 (setq shift-n (string-to-number (match-string 1 shift))
8493 shift-what (cdr (assoc (match-string 2 shift)
8494 '(("d" . day) ("w" . week)
8495 ("m" . month) ("y" . year))))))
8496 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8497 (setq nmin 1 nmax n)
8498 (org-back-to-heading t)
8499 (setq beg (point))
8500 (setq idprop (org-entry-get nil "ID"))
8501 (org-end-of-subtree t t)
8502 (or (bolp) (insert "\n"))
8503 (setq end (point))
8504 (setq template (buffer-substring beg end))
8505 (when (and doshift
8506 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8507 (delete-region beg end)
8508 (setq end beg)
8509 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8510 (goto-char end)
8511 (loop for n from nmin to nmax do
8512 ;; prepare clone
8513 (with-temp-buffer
8514 (insert template)
8515 (org-mode)
8516 (goto-char (point-min))
8517 (org-show-subtree)
8518 (and idprop (if org-clone-delete-id
8519 (org-entry-delete nil "ID")
8520 (org-id-get-create t)))
8521 (unless (= n 0)
8522 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8523 (kill-whole-line))
8524 (goto-char (point-min))
8525 (while (re-search-forward drawer-re nil t)
8526 (mapc (lambda (d)
8527 (org-remove-empty-drawer-at d (point))) org-drawers)))
8528 (goto-char (point-min))
8529 (when doshift
8530 (while (re-search-forward org-ts-regexp-both nil t)
8531 (org-timestamp-change (* n shift-n) shift-what))
8532 (unless (= n n-no-remove)
8533 (goto-char (point-min))
8534 (while (re-search-forward org-ts-regexp nil t)
8535 (save-excursion
8536 (goto-char (match-beginning 0))
8537 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8538 (delete-region (match-beginning 1) (match-end 1)))))))
8539 (setq task (buffer-string)))
8540 (insert task))
8541 (goto-char beg)))
8543 ;;; Outline Sorting
8545 (defun org-sort (with-case)
8546 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8547 Optional argument WITH-CASE means sort case-sensitively."
8548 (interactive "P")
8549 (cond
8550 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8551 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8553 (org-call-with-arg 'org-sort-entries with-case))))
8555 (defun org-sort-remove-invisible (s)
8556 "Remove invisible links from string S."
8557 (remove-text-properties 0 (length s) org-rm-props s)
8558 (while (string-match org-bracket-link-regexp s)
8559 (setq s (replace-match (if (match-end 2)
8560 (match-string 3 s)
8561 (match-string 1 s)) t t s)))
8562 (let ((st (format " %s " s)))
8563 (while (string-match org-emph-re st)
8564 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8565 (setq s (substring st 1 -1)))
8568 (defvar org-priority-regexp) ; defined later in the file
8570 (defvar org-after-sorting-entries-or-items-hook nil
8571 "Hook that is run after a bunch of entries or items have been sorted.
8572 When children are sorted, the cursor is in the parent line when this
8573 hook gets called. When a region or a plain list is sorted, the cursor
8574 will be in the first entry of the sorted region/list.")
8576 (defun org-sort-entries
8577 (&optional with-case sorting-type getkey-func compare-func property)
8578 "Sort entries on a certain level of an outline tree.
8579 If there is an active region, the entries in the region are sorted.
8580 Else, if the cursor is before the first entry, sort the top-level items.
8581 Else, the children of the entry at point are sorted.
8583 Sorting can be alphabetically, numerically, by date/time as given by
8584 a time stamp, by a property, by priority order, or by a custom function.
8586 The command prompts for the sorting type unless it has been given to the
8587 function through the SORTING-TYPE argument, which needs to be a character,
8588 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8589 precise meaning of each character:
8591 n Numerically, by converting the beginning of the entry/item to a number.
8592 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8593 o By order of TODO keywords.
8594 t By date/time, either the first active time stamp in the entry, or, if
8595 none exist, by the first inactive one.
8596 s By the scheduled date/time.
8597 d By deadline date/time.
8598 c By creation time, which is assumed to be the first inactive time stamp
8599 at the beginning of a line.
8600 p By priority according to the cookie.
8601 r By the value of a property.
8603 Capital letters will reverse the sort order.
8605 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8606 called with point at the beginning of the record. It must return either
8607 a string or a number that should serve as the sorting key for that record.
8609 Comparing entries ignores case by default. However, with an optional argument
8610 WITH-CASE, the sorting considers case as well.
8612 Sorting is done against the visible part of the headlines, it ignores hidden
8613 links."
8614 (interactive "P")
8615 (let ((case-func (if with-case 'identity 'downcase))
8616 (cmstr
8617 ;; The clock marker is lost when using `sort-subr', let's
8618 ;; store the clocking string.
8619 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8620 (save-excursion
8621 (goto-char org-clock-marker)
8622 (looking-back "^.*") (match-string-no-properties 0))))
8623 start beg end stars re re2
8624 txt what tmp)
8625 ;; Find beginning and end of region to sort
8626 (cond
8627 ((org-region-active-p)
8628 ;; we will sort the region
8629 (setq end (region-end)
8630 what "region")
8631 (goto-char (region-beginning))
8632 (if (not (org-at-heading-p)) (outline-next-heading))
8633 (setq start (point)))
8634 ((or (org-at-heading-p)
8635 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8636 ;; we will sort the children of the current headline
8637 (org-back-to-heading)
8638 (setq start (point)
8639 end (progn (org-end-of-subtree t t)
8640 (or (bolp) (insert "\n"))
8641 (org-back-over-empty-lines)
8642 (point))
8643 what "children")
8644 (goto-char start)
8645 (show-subtree)
8646 (outline-next-heading))
8648 ;; we will sort the top-level entries in this file
8649 (goto-char (point-min))
8650 (or (org-at-heading-p) (outline-next-heading))
8651 (setq start (point))
8652 (goto-char (point-max))
8653 (beginning-of-line 1)
8654 (when (looking-at ".*?\\S-")
8655 ;; File ends in a non-white line
8656 (end-of-line 1)
8657 (insert "\n"))
8658 (setq end (point-max))
8659 (setq what "top-level")
8660 (goto-char start)
8661 (show-all)))
8663 (setq beg (point))
8664 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8666 (looking-at "\\(\\*+\\)")
8667 (setq stars (match-string 1)
8668 re (concat "^" (regexp-quote stars) " +")
8669 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8670 txt (buffer-substring beg end))
8671 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8672 (if (and (not (equal stars "*")) (string-match re2 txt))
8673 (user-error "Region to sort contains a level above the first entry"))
8675 (unless sorting-type
8676 (message
8677 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8678 [t]ime [s]cheduled [d]eadline [c]reated
8679 A/N/P/R/O/F/T/S/D/C means reversed:"
8680 what)
8681 (setq sorting-type (read-char-exclusive))
8683 (unless getkey-func
8684 (and (= (downcase sorting-type) ?f)
8685 (setq getkey-func
8686 (org-icompleting-read "Sort using function: "
8687 obarray 'fboundp t nil nil))
8688 (setq getkey-func (intern getkey-func))))
8690 (and (= (downcase sorting-type) ?r)
8691 (not property)
8692 (setq property
8693 (org-icompleting-read "Property: "
8694 (mapcar 'list (org-buffer-property-keys t))
8695 nil t))))
8697 (message "Sorting entries...")
8699 (save-restriction
8700 (narrow-to-region start end)
8701 (let ((dcst (downcase sorting-type))
8702 (case-fold-search nil)
8703 (now (current-time)))
8704 (sort-subr
8705 (/= dcst sorting-type)
8706 ;; This function moves to the beginning character of the "record" to
8707 ;; be sorted.
8708 (lambda nil
8709 (if (re-search-forward re nil t)
8710 (goto-char (match-beginning 0))
8711 (goto-char (point-max))))
8712 ;; This function moves to the last character of the "record" being
8713 ;; sorted.
8714 (lambda nil
8715 (save-match-data
8716 (condition-case nil
8717 (outline-forward-same-level 1)
8718 (error
8719 (goto-char (point-max))))))
8720 ;; This function returns the value that gets sorted against.
8721 (lambda nil
8722 (cond
8723 ((= dcst ?n)
8724 (if (looking-at org-complex-heading-regexp)
8725 (string-to-number (org-sort-remove-invisible (match-string 4)))
8726 nil))
8727 ((= dcst ?a)
8728 (if (looking-at org-complex-heading-regexp)
8729 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8730 nil))
8731 ((= dcst ?t)
8732 (let ((end (save-excursion (outline-next-heading) (point))))
8733 (if (or (re-search-forward org-ts-regexp end t)
8734 (re-search-forward org-ts-regexp-both end t))
8735 (org-time-string-to-seconds (match-string 0))
8736 (org-float-time now))))
8737 ((= dcst ?c)
8738 (let ((end (save-excursion (outline-next-heading) (point))))
8739 (if (re-search-forward
8740 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8741 end t)
8742 (org-time-string-to-seconds (match-string 0))
8743 (org-float-time now))))
8744 ((= dcst ?s)
8745 (let ((end (save-excursion (outline-next-heading) (point))))
8746 (if (re-search-forward org-scheduled-time-regexp end t)
8747 (org-time-string-to-seconds (match-string 1))
8748 (org-float-time now))))
8749 ((= dcst ?d)
8750 (let ((end (save-excursion (outline-next-heading) (point))))
8751 (if (re-search-forward org-deadline-time-regexp end t)
8752 (org-time-string-to-seconds (match-string 1))
8753 (org-float-time now))))
8754 ((= dcst ?p)
8755 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8756 (string-to-char (match-string 2))
8757 org-default-priority))
8758 ((= dcst ?r)
8759 (or (org-entry-get nil property) ""))
8760 ((= dcst ?o)
8761 (if (looking-at org-complex-heading-regexp)
8762 (- 9999 (length (member (match-string 2)
8763 org-todo-keywords-1)))))
8764 ((= dcst ?f)
8765 (if getkey-func
8766 (progn
8767 (setq tmp (funcall getkey-func))
8768 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8769 tmp)
8770 (error "Invalid key function `%s'" getkey-func)))
8771 (t (error "Invalid sorting type `%c'" sorting-type))))
8773 (cond
8774 ((= dcst ?a) 'string<)
8775 ((= dcst ?f) compare-func)
8776 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8777 (run-hooks 'org-after-sorting-entries-or-items-hook)
8778 ;; Reset the clock marker if needed
8779 (when cmstr
8780 (save-excursion
8781 (goto-char start)
8782 (search-forward cmstr nil t)
8783 (move-marker org-clock-marker (point))))
8784 (message "Sorting entries...done")))
8786 (defun org-do-sort (table what &optional with-case sorting-type)
8787 "Sort TABLE of WHAT according to SORTING-TYPE.
8788 The user will be prompted for the SORTING-TYPE if the call to this
8789 function does not specify it. WHAT is only for the prompt, to indicate
8790 what is being sorted. The sorting key will be extracted from
8791 the car of the elements of the table.
8792 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8793 (unless sorting-type
8794 (message
8795 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8796 what)
8797 (setq sorting-type (read-char-exclusive)))
8798 (let ((dcst (downcase sorting-type))
8799 extractfun comparefun)
8800 ;; Define the appropriate functions
8801 (cond
8802 ((= dcst ?n)
8803 (setq extractfun 'string-to-number
8804 comparefun (if (= dcst sorting-type) '< '>)))
8805 ((= dcst ?a)
8806 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8807 (lambda(x) (downcase (org-sort-remove-invisible x))))
8808 comparefun (if (= dcst sorting-type)
8809 'string<
8810 (lambda (a b) (and (not (string< a b))
8811 (not (string= a b)))))))
8812 ((= dcst ?t)
8813 (setq extractfun
8814 (lambda (x)
8815 (if (or (string-match org-ts-regexp x)
8816 (string-match org-ts-regexp-both x))
8817 (org-float-time
8818 (org-time-string-to-time (match-string 0 x)))
8820 comparefun (if (= dcst sorting-type) '< '>)))
8821 (t (error "Invalid sorting type `%c'" sorting-type)))
8823 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8824 table)
8825 (lambda (a b) (funcall comparefun (car a) (car b))))))
8828 ;;; The orgstruct minor mode
8830 ;; Define a minor mode which can be used in other modes in order to
8831 ;; integrate the org-mode structure editing commands.
8833 ;; This is really a hack, because the org-mode structure commands use
8834 ;; keys which normally belong to the major mode. Here is how it
8835 ;; works: The minor mode defines all the keys necessary to operate the
8836 ;; structure commands, but wraps the commands into a function which
8837 ;; tests if the cursor is currently at a headline or a plain list
8838 ;; item. If that is the case, the structure command is used,
8839 ;; temporarily setting many Org-mode variables like regular
8840 ;; expressions for filling etc. However, when any of those keys is
8841 ;; used at a different location, function uses `key-binding' to look
8842 ;; up if the key has an associated command in another currently active
8843 ;; keymap (minor modes, major mode, global), and executes that
8844 ;; command. There might be problems if any of the keys is otherwise
8845 ;; used as a prefix key.
8847 (defcustom orgstruct-heading-prefix-regexp ""
8848 "Regexp that matches the custom prefix of Org headlines in
8849 orgstruct(++)-mode."
8850 :group 'org
8851 :version "24.4"
8852 :package-version '(Org . "8.3")
8853 :type 'regexp)
8854 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8856 (defcustom orgstruct-setup-hook nil
8857 "Hook run after orgstruct-mode-map is filled."
8858 :group 'org
8859 :version "24.4"
8860 :package-version '(Org . "8.0")
8861 :type 'hook)
8863 (defvar orgstruct-initialized nil)
8865 (defvar org-local-vars nil
8866 "List of local variables, for use by `orgstruct-mode'.")
8868 ;;;###autoload
8869 (define-minor-mode orgstruct-mode
8870 "Toggle the minor mode `orgstruct-mode'.
8871 This mode is for using Org-mode structure commands in other
8872 modes. The following keys behave as if Org-mode were active, if
8873 the cursor is on a headline, or on a plain list item (both as
8874 defined by Org-mode)."
8875 nil " OrgStruct" (make-sparse-keymap)
8876 (funcall (if orgstruct-mode
8877 'add-to-invisibility-spec
8878 'remove-from-invisibility-spec)
8879 '(outline . t))
8880 (when orgstruct-mode
8881 (org-load-modules-maybe)
8882 (unless orgstruct-initialized
8883 (orgstruct-setup)
8884 (setq orgstruct-initialized t))))
8886 ;;;###autoload
8887 (defun turn-on-orgstruct ()
8888 "Unconditionally turn on `orgstruct-mode'."
8889 (orgstruct-mode 1))
8891 (defvar org-fb-vars nil)
8892 (make-variable-buffer-local 'org-fb-vars)
8893 (defun orgstruct++-mode (&optional arg)
8894 "Toggle `orgstruct-mode', the enhanced version of it.
8895 In addition to setting orgstruct-mode, this also exports all
8896 indentation and autofilling variables from org-mode into the
8897 buffer. It will also recognize item context in multiline items."
8898 (interactive "P")
8899 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8900 (if (< arg 1)
8901 (progn (orgstruct-mode -1)
8902 (mapc (lambda(v)
8903 (org-set-local (car v)
8904 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8905 org-fb-vars))
8906 (orgstruct-mode 1)
8907 (setq org-fb-vars nil)
8908 (unless org-local-vars
8909 (setq org-local-vars (org-get-local-variables)))
8910 (let (var val)
8911 (mapc
8912 (lambda (x)
8913 (when (string-match
8914 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8915 (symbol-name (car x)))
8916 (setq var (car x) val (nth 1 x))
8917 (push (list var `(quote ,(eval var))) org-fb-vars)
8918 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8919 org-local-vars)
8920 (org-set-local 'orgstruct-is-++ t))))
8922 (defvar orgstruct-is-++ nil
8923 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8924 (make-variable-buffer-local 'orgstruct-is-++)
8926 ;;;###autoload
8927 (defun turn-on-orgstruct++ ()
8928 "Unconditionally turn on `orgstruct++-mode'."
8929 (orgstruct++-mode 1))
8931 (defun orgstruct-error ()
8932 "Error when there is no default binding for a structure key."
8933 (interactive)
8934 (funcall (if (fboundp 'user-error)
8935 'user-error
8936 'error)
8937 "This key has no function outside structure elements"))
8939 (defun orgstruct-setup ()
8940 "Setup orgstruct keymap."
8941 (dolist (cell '((org-demote . t)
8942 (org-metaleft . t)
8943 (org-metaright . t)
8944 (org-promote . t)
8945 (org-shiftmetaleft . t)
8946 (org-shiftmetaright . t)
8947 org-backward-element
8948 org-backward-heading-same-level
8949 org-ctrl-c-ret
8950 org-ctrl-c-minus
8951 org-ctrl-c-star
8952 org-cycle
8953 org-forward-heading-same-level
8954 org-insert-heading
8955 org-insert-heading-respect-content
8956 org-kill-note-or-show-branches
8957 org-mark-subtree
8958 org-meta-return
8959 org-metadown
8960 org-metaup
8961 org-narrow-to-subtree
8962 org-promote-subtree
8963 org-reveal
8964 org-shiftdown
8965 org-shiftleft
8966 org-shiftmetadown
8967 org-shiftmetaup
8968 org-shiftright
8969 org-shifttab
8970 org-shifttab
8971 org-shiftup
8972 org-show-subtree
8973 org-sort
8974 org-up-element
8975 outline-demote
8976 outline-next-visible-heading
8977 outline-previous-visible-heading
8978 outline-promote
8979 outline-up-heading
8980 show-children))
8981 (let ((f (or (car-safe cell) cell))
8982 (disable-when-heading-prefix (cdr-safe cell)))
8983 (when (fboundp f)
8984 (let ((new-bindings))
8985 (dolist (binding (nconc (where-is-internal f org-mode-map)
8986 (where-is-internal f outline-mode-map)))
8987 (push binding new-bindings)
8988 ;; TODO use local-function-key-map
8989 (dolist (rep '(("<tab>" . "TAB")
8990 ("<return>" . "RET")
8991 ("<escape>" . "ESC")
8992 ("<delete>" . "DEL")))
8993 (setq binding (read-kbd-macro
8994 (let ((case-fold-search))
8995 (replace-regexp-in-string
8996 (regexp-quote (cdr rep))
8997 (car rep)
8998 (key-description binding)))))
8999 (pushnew binding new-bindings :test 'equal)))
9000 (dolist (binding new-bindings)
9001 (let ((key (lookup-key orgstruct-mode-map binding)))
9002 (when (or (not key) (numberp key))
9003 (condition-case nil
9004 (org-defkey orgstruct-mode-map
9005 binding
9006 (orgstruct-make-binding f binding disable-when-heading-prefix))
9007 (error nil)))))))))
9008 (run-hooks 'orgstruct-setup-hook))
9010 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9011 "Create a function for binding in the structure minor mode.
9012 FUN is the command to call inside a table. KEY is the key that
9013 should be checked in for a command to execute outside of tables.
9014 Non-nil `disable-when-heading-prefix' means to disable the command
9015 if `orgstruct-heading-prefix-regexp' is not empty."
9016 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9017 (let ((nname name)
9018 (i 0))
9019 (while (fboundp (intern nname))
9020 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9021 (setq name (intern nname)))
9022 (eval
9023 (let ((bindings '((org-heading-regexp
9024 (concat "^"
9025 orgstruct-heading-prefix-regexp
9026 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9027 (org-outline-regexp
9028 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9029 (org-outline-regexp-bol
9030 (concat "^" org-outline-regexp))
9031 (outline-regexp org-outline-regexp)
9032 (outline-heading-end-regexp "\n")
9033 (outline-level 'org-outline-level)
9034 (outline-heading-alist))))
9035 `(defun ,name (arg)
9036 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9037 "Outside of structure, run the binding of `"
9038 (key-description key) "'."
9039 (when disable-when-heading-prefix
9040 (concat
9041 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9042 "back to the default binding due to limitations of Org's implementation of\n"
9043 "`" (symbol-name fun) "'.")))
9044 (interactive "p")
9045 (let* ((disable
9046 ,(and disable-when-heading-prefix
9047 '(not (string= orgstruct-heading-prefix-regexp ""))))
9048 (fallback
9049 (or disable
9050 (not
9051 (let* ,bindings
9052 (org-context-p 'headline 'item
9053 ,(when (memq fun
9054 '(org-insert-heading
9055 org-insert-heading-respect-content
9056 org-meta-return))
9057 '(when orgstruct-is-++
9058 'item-body))))))))
9059 (if fallback
9060 (let* ((orgstruct-mode)
9061 (binding
9062 (loop with key = ,key
9063 for rep in
9064 '(nil
9065 ("<\\([^>]*\\)tab>" . "\\1TAB")
9066 ("<\\([^>]*\\)return>" . "\\1RET")
9067 ("<\\([^>]*\\)escape>" . "\\1ESC")
9068 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9070 (when rep
9071 (setq key (read-kbd-macro
9072 (let ((case-fold-search))
9073 (replace-regexp-in-string
9074 (car rep)
9075 (cdr rep)
9076 (key-description key))))))
9077 thereis (key-binding key))))
9078 (if (keymapp binding)
9079 (org-set-transient-map binding)
9080 (let ((func (or binding
9081 (unless disable
9082 'orgstruct-error))))
9083 (when func
9084 (call-interactively func)))))
9085 (org-run-like-in-org-mode
9086 (lambda ()
9087 (interactive)
9088 (let* ,bindings
9089 (call-interactively ',fun)))))))))
9090 name))
9092 (defun org-contextualize-keys (alist contexts)
9093 "Return valid elements in ALIST depending on CONTEXTS.
9095 `org-agenda-custom-commands' or `org-capture-templates' are the
9096 values used for ALIST, and `org-agenda-custom-commands-contexts'
9097 or `org-capture-templates-contexts' are the associated contexts
9098 definitions."
9099 (let ((contexts
9100 ;; normalize contexts
9101 (mapcar
9102 (lambda(c) (cond ((listp (cadr c))
9103 (list (car c) (car c) (cadr c)))
9104 ((string= "" (cadr c))
9105 (list (car c) (car c) (caddr c)))
9106 (t c))) contexts))
9107 (a alist) c r s)
9108 ;; loop over all commands or templates
9109 (while (setq c (pop a))
9110 (let (vrules repl)
9111 (cond
9112 ((not (assoc (car c) contexts))
9113 (push c r))
9114 ((and (assoc (car c) contexts)
9115 (setq vrules (org-contextualize-validate-key
9116 (car c) contexts)))
9117 (mapc (lambda (vr)
9118 (when (not (equal (car vr) (cadr vr)))
9119 (setq repl vr))) vrules)
9120 (if (not repl) (push c r)
9121 (push (cadr repl) s)
9122 (push
9123 (cons (car c)
9124 (cdr (or (assoc (cadr repl) alist)
9125 (error "Undefined key `%s' as contextual replacement for `%s'"
9126 (cadr repl) (car c)))))
9127 r))))))
9128 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9129 (delq
9131 (delete-dups
9132 (mapcar (lambda (x)
9133 (let ((tpl (car x)))
9134 (when (not (delq
9136 (mapcar (lambda(y)
9137 (equal y tpl)) s))) x)))
9138 (reverse r))))))
9140 (defun org-contextualize-validate-key (key contexts)
9141 "Check CONTEXTS for agenda or capture KEY."
9142 (let (r rr res)
9143 (while (setq r (pop contexts))
9144 (mapc
9145 (lambda (rr)
9146 (when
9147 (and (equal key (car r))
9148 (if (functionp rr) (funcall rr)
9149 (or (and (eq (car rr) 'in-file)
9150 (buffer-file-name)
9151 (string-match (cdr rr) (buffer-file-name)))
9152 (and (eq (car rr) 'in-mode)
9153 (string-match (cdr rr) (symbol-name major-mode)))
9154 (and (eq (car rr) 'in-buffer)
9155 (string-match (cdr rr) (buffer-name)))
9156 (if (and (eq (car rr) 'not-in-file)
9157 (buffer-file-name))
9158 (not (string-match (cdr rr) (buffer-file-name)))
9160 (when (eq (car rr) 'not-in-mode)
9161 (not (string-match (cdr rr) (symbol-name major-mode))))
9162 (when (eq (car rr) 'not-in-buffer)
9163 (not (string-match (cdr rr) (buffer-name)))))))
9164 (push r res)))
9165 (car (last r))))
9166 (delete-dups (delq nil res))))
9168 (defun org-context-p (&rest contexts)
9169 "Check if local context is any of CONTEXTS.
9170 Possible values in the list of contexts are `table', `headline', and `item'."
9171 (let ((pos (point)))
9172 (goto-char (point-at-bol))
9173 (prog1 (or (and (memq 'table contexts)
9174 (looking-at "[ \t]*|"))
9175 (and (memq 'headline contexts)
9176 (looking-at org-outline-regexp))
9177 (and (memq 'item contexts)
9178 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9179 (and (memq 'item-body contexts)
9180 (org-in-item-p)))
9181 (goto-char pos))))
9183 (defun org-get-local-variables ()
9184 "Return a list of all local variables in an Org mode buffer."
9185 (let (varlist)
9186 (with-current-buffer (get-buffer-create "*Org tmp*")
9187 (erase-buffer)
9188 (org-mode)
9189 (setq varlist (buffer-local-variables)))
9190 (kill-buffer "*Org tmp*")
9191 (delq nil
9192 (mapcar
9193 (lambda (x)
9194 (setq x
9195 (if (symbolp x)
9196 (list x)
9197 (list (car x) (cdr x))))
9198 (if (and (not (get (car x) 'org-state))
9199 (string-match
9200 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9201 (symbol-name (car x))))
9202 x nil))
9203 varlist))))
9205 (defun org-clone-local-variables (from-buffer &optional regexp)
9206 "Clone local variables from FROM-BUFFER.
9207 Optional argument REGEXP selects variables to clone."
9208 (mapc
9209 (lambda (pair)
9210 (and (symbolp (car pair))
9211 (or (null regexp)
9212 (string-match regexp (symbol-name (car pair))))
9213 (set (make-local-variable (car pair))
9214 (cdr pair))))
9215 (buffer-local-variables from-buffer)))
9217 ;;;###autoload
9218 (defun org-run-like-in-org-mode (cmd)
9219 "Run a command, pretending that the current buffer is in Org-mode.
9220 This will temporarily bind local variables that are typically bound in
9221 Org-mode to the values they have in Org-mode, and then interactively
9222 call CMD."
9223 (org-load-modules-maybe)
9224 (unless org-local-vars
9225 (setq org-local-vars (org-get-local-variables)))
9226 (let (binds)
9227 (dolist (var org-local-vars)
9228 (when (or (not (boundp (car var)))
9229 (eq (symbol-value (car var))
9230 (default-value (car var))))
9231 (push (list (car var) `(quote ,(cadr var))) binds)))
9232 (eval `(let ,binds
9233 (call-interactively (quote ,cmd))))))
9235 ;;;; Archiving
9237 (defun org-get-category (&optional pos force-refresh)
9238 "Get the category applying to position POS."
9239 (save-match-data
9240 (if force-refresh (org-refresh-category-properties))
9241 (let ((pos (or pos (point))))
9242 (or (get-text-property pos 'org-category)
9243 (progn (org-refresh-category-properties)
9244 (get-text-property pos 'org-category))))))
9246 (defun org-refresh-category-properties ()
9247 "Refresh category text properties in the buffer."
9248 (let ((case-fold-search t)
9249 (inhibit-read-only t)
9250 (def-cat (cond
9251 ((null org-category)
9252 (if buffer-file-name
9253 (file-name-sans-extension
9254 (file-name-nondirectory buffer-file-name))
9255 "???"))
9256 ((symbolp org-category) (symbol-name org-category))
9257 (t org-category)))
9258 beg end cat pos optionp)
9259 (org-with-silent-modifications
9260 (save-excursion
9261 (save-restriction
9262 (widen)
9263 (goto-char (point-min))
9264 (put-text-property (point) (point-max) 'org-category def-cat)
9265 (while (re-search-forward
9266 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9267 (setq pos (match-end 0)
9268 optionp (equal (char-after (match-beginning 0)) ?#)
9269 cat (org-trim (match-string 2)))
9270 (if optionp
9271 (setq beg (point-at-bol) end (point-max))
9272 (org-back-to-heading t)
9273 (setq beg (point) end (org-end-of-subtree t t)))
9274 (put-text-property beg end 'org-category cat)
9275 (put-text-property beg end 'org-category-position beg)
9276 (goto-char pos)))))))
9278 (defun org-refresh-properties (dprop tprop)
9279 "Refresh buffer text properties.
9280 DPROP is the drawer property and TPROP is the corresponding text
9281 property to set."
9282 (let ((case-fold-search t)
9283 (inhibit-read-only t) p)
9284 (org-with-silent-modifications
9285 (save-excursion
9286 (save-restriction
9287 (widen)
9288 (goto-char (point-min))
9289 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9290 (setq p (org-match-string-no-properties 1))
9291 (save-excursion
9292 (org-back-to-heading t)
9293 (put-text-property
9294 (point-at-bol) (or (outline-next-heading) (point-max)) tprop p))))))))
9297 ;;;; Link Stuff
9299 ;;; Link abbreviations
9301 (defun org-link-expand-abbrev (link)
9302 "Apply replacements as defined in `org-link-abbrev-alist'."
9303 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9304 (let* ((key (match-string 1 link))
9305 (as (or (assoc key org-link-abbrev-alist-local)
9306 (assoc key org-link-abbrev-alist)))
9307 (tag (and (match-end 2) (match-string 3 link)))
9308 rpl)
9309 (if (not as)
9310 link
9311 (setq rpl (cdr as))
9312 (cond
9313 ((symbolp rpl) (funcall rpl tag))
9314 ((string-match "%(\\([^)]+\\))" rpl)
9315 (replace-match
9316 (save-match-data
9317 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9318 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9319 ((string-match "%h" rpl)
9320 (replace-match (url-hexify-string (or tag "")) t t rpl))
9321 (t (concat rpl tag)))))
9322 link))
9324 ;;; Storing and inserting links
9326 (defvar org-insert-link-history nil
9327 "Minibuffer history for links inserted with `org-insert-link'.")
9329 (defvar org-stored-links nil
9330 "Contains the links stored with `org-store-link'.")
9332 (defvar org-store-link-plist nil
9333 "Plist with info about the most recently link created with `org-store-link'.")
9335 (defvar org-link-protocols nil
9336 "Link protocols added to Org-mode using `org-add-link-type'.")
9338 (defvar org-store-link-functions nil
9339 "List of functions that are called to create and store a link.
9340 Each function will be called in turn until one returns a non-nil
9341 value. Each function should check if it is responsible for creating
9342 this link (for example by looking at the major mode).
9343 If not, it must exit and return nil.
9344 If yes, it should return a non-nil value after a calling
9345 `org-store-link-props' with a list of properties and values.
9346 Special properties are:
9348 :type The link prefix, like \"http\". This must be given.
9349 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9350 This is obligatory as well.
9351 :description Optional default description for the second pair
9352 of brackets in an Org-mode link. The user can still change
9353 this when inserting this link into an Org-mode buffer.
9355 In addition to these, any additional properties can be specified
9356 and then used in capture templates.")
9358 (defun org-add-link-type (type &optional follow export)
9359 "Add TYPE to the list of `org-link-types'.
9360 Re-compute all regular expressions depending on `org-link-types'
9362 FOLLOW and EXPORT are two functions.
9364 FOLLOW should take the link path as the single argument and do whatever
9365 is necessary to follow the link, for example find a file or display
9366 a mail message.
9368 EXPORT should format the link path for export to one of the export formats.
9369 It should be a function accepting three arguments:
9371 path the path of the link, the text after the prefix (like \"http:\")
9372 desc the description of the link, if any, or a description added by
9373 org-export-normalize-links if there is none
9374 format the export format, a symbol like `html' or `latex' or `ascii'..
9376 The function may use the FORMAT information to return different values
9377 depending on the format. The return value will be put literally into
9378 the exported file. If the return value is nil, this means Org should
9379 do what it normally does with links which do not have EXPORT defined.
9381 Org-mode has a built-in default for exporting links. If you are happy with
9382 this default, there is no need to define an export function for the link
9383 type. For a simple example of an export function, see `org-bbdb.el'."
9384 (add-to-list 'org-link-types type t)
9385 (org-make-link-regexps)
9386 (if (assoc type org-link-protocols)
9387 (setcdr (assoc type org-link-protocols) (list follow export))
9388 (push (list type follow export) org-link-protocols)))
9390 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9391 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9393 ;;;###autoload
9394 (defun org-store-link (arg)
9395 "\\<org-mode-map>Store an org-link to the current location.
9396 This link is added to `org-stored-links' and can later be inserted
9397 into an org-buffer with \\[org-insert-link].
9399 For some link types, a prefix arg is interpreted.
9400 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9401 For file links, arg negates `org-context-in-file-links'.
9403 A double prefix arg force skipping storing functions that are not
9404 part of Org's core.
9406 A triple prefix arg force storing a link for each line in the
9407 active region."
9408 (interactive "P")
9409 (org-load-modules-maybe)
9410 (if (and (equal arg '(64)) (org-region-active-p))
9411 (save-excursion
9412 (let ((end (region-end)))
9413 (goto-char (region-beginning))
9414 (set-mark (point))
9415 (while (< (point-at-eol) end)
9416 (move-end-of-line 1) (activate-mark)
9417 (let (current-prefix-arg)
9418 (call-interactively 'org-store-link))
9419 (move-beginning-of-line 2)
9420 (set-mark (point)))))
9421 (org-with-limited-levels
9422 (setq org-store-link-plist nil)
9423 (let (link cpltxt desc description search
9424 txt custom-id agenda-link sfuns sfunsn)
9425 (cond
9427 ;; Store a link using an external link type
9428 ((and (not (equal arg '(16)))
9429 (setq sfuns
9430 (delq
9431 nil (mapcar (lambda (f)
9432 (let (fs) (if (funcall f) (push f fs))))
9433 org-store-link-functions))
9434 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9435 (or (and (cdr sfuns)
9436 (funcall (intern
9437 (completing-read
9438 "Which function for creating the link? "
9439 sfunsn nil t (car sfunsn)))))
9440 (funcall (caar sfuns)))
9441 (setq link (plist-get org-store-link-plist :link)
9442 desc (or (plist-get org-store-link-plist
9443 :description) link))))
9445 ;; Store a link from a source code buffer
9446 ((org-src-edit-buffer-p)
9447 (let (label gc)
9448 (while (or (not label)
9449 (save-excursion
9450 (save-restriction
9451 (widen)
9452 (goto-char (point-min))
9453 (re-search-forward
9454 (regexp-quote (format org-coderef-label-format label))
9455 nil t))))
9456 (when label (message "Label exists already") (sit-for 2))
9457 (setq label (read-string "Code line label: " label)))
9458 (end-of-line 1)
9459 (setq link (format org-coderef-label-format label))
9460 (setq gc (- 79 (length link)))
9461 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9462 (insert link)
9463 (setq link (concat "(" label ")") desc nil)))
9465 ;; We are in the agenda, link to referenced location
9466 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9467 (let ((m (or (get-text-property (point) 'org-hd-marker)
9468 (get-text-property (point) 'org-marker))))
9469 (when m
9470 (org-with-point-at m
9471 (setq agenda-link
9472 (if (org-called-interactively-p 'any)
9473 (call-interactively 'org-store-link)
9474 (org-store-link nil)))))))
9476 ((eq major-mode 'calendar-mode)
9477 (let ((cd (calendar-cursor-to-date)))
9478 (setq link
9479 (format-time-string
9480 (car org-time-stamp-formats)
9481 (apply 'encode-time
9482 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9483 nil nil nil))))
9484 (org-store-link-props :type "calendar" :date cd)))
9486 ((eq major-mode 'help-mode)
9487 (setq link (concat "help:" (save-excursion
9488 (goto-char (point-min))
9489 (looking-at "^[^ ]+")
9490 (match-string 0))))
9491 (org-store-link-props :type "help"))
9493 ((eq major-mode 'w3-mode)
9494 (setq cpltxt (if (and (buffer-name)
9495 (not (string-match "Untitled" (buffer-name))))
9496 (buffer-name)
9497 (url-view-url t))
9498 link (url-view-url t))
9499 (org-store-link-props :type "w3" :url (url-view-url t)))
9501 ((eq major-mode 'image-mode)
9502 (setq cpltxt (concat "file:"
9503 (abbreviate-file-name buffer-file-name))
9504 link cpltxt)
9505 (org-store-link-props :type "image" :file buffer-file-name))
9507 ;; In dired, store a link to the file of the current line
9508 ((eq major-mode 'dired-mode)
9509 (let ((file (dired-get-filename nil t)))
9510 (setq file (if file
9511 (abbreviate-file-name
9512 (expand-file-name (dired-get-filename nil t)))
9513 ;; otherwise, no file so use current directory.
9514 default-directory))
9515 (setq cpltxt (concat "file:" file)
9516 link cpltxt)))
9518 ((setq search (run-hook-with-args-until-success
9519 'org-create-file-search-functions))
9520 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9521 "::" search))
9522 (setq cpltxt (or description link)))
9524 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9525 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9526 (cond
9527 ;; Store a link using the target at point
9528 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9529 (setq cpltxt
9530 (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))
9533 "::" (match-string 1))
9534 link cpltxt))
9535 ((and (featurep 'org-id)
9536 (or (eq org-id-link-to-org-use-id t)
9537 (and (org-called-interactively-p 'any)
9538 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9539 (and (eq org-id-link-to-org-use-id
9540 'create-if-interactive-and-no-custom-id)
9541 (not custom-id))))
9542 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9543 ;; Store a link using the ID at point
9544 (setq link (condition-case nil
9545 (prog1 (org-id-store-link)
9546 (setq desc (or (plist-get org-store-link-plist
9547 :description)
9548 "")))
9549 (error
9550 ;; Probably before first headline, link only to file
9551 (concat "file:"
9552 (abbreviate-file-name
9553 (buffer-file-name (buffer-base-buffer))))))))
9555 ;; Just link to current headline
9556 (setq cpltxt (concat "file:"
9557 (abbreviate-file-name
9558 (buffer-file-name (buffer-base-buffer)))))
9559 ;; Add a context search string
9560 (when (org-xor org-context-in-file-links arg)
9561 (let* ((ee (org-element-at-point))
9562 (et (org-element-type ee))
9563 (ev (plist-get (cadr ee) :value))
9564 (ek (plist-get (cadr ee) :key))
9565 (eok (and (stringp ek) (string-match "name" ek))))
9566 (setq txt (cond
9567 ((org-at-heading-p) nil)
9568 ((and (eq et 'keyword) eok) ev)
9569 ((org-region-active-p)
9570 (buffer-substring (region-beginning) (region-end)))))
9571 (when (or (null txt) (string-match "\\S-" txt))
9572 (setq cpltxt
9573 (concat cpltxt "::"
9574 (condition-case nil
9575 (org-make-org-heading-search-string txt)
9576 (error "")))
9577 desc (or (and (eq et 'keyword) eok ev)
9578 (nth 4 (ignore-errors (org-heading-components)))
9579 "NONE")))))
9580 (if (string-match "::\\'" cpltxt)
9581 (setq cpltxt (substring cpltxt 0 -2)))
9582 (setq link cpltxt))))
9584 ((buffer-file-name (buffer-base-buffer))
9585 ;; Just link to this file here.
9586 (setq cpltxt (concat "file:"
9587 (abbreviate-file-name
9588 (buffer-file-name (buffer-base-buffer)))))
9589 ;; Add a context string.
9590 (when (org-xor org-context-in-file-links arg)
9591 (setq txt (if (org-region-active-p)
9592 (buffer-substring (region-beginning) (region-end))
9593 (buffer-substring (point-at-bol) (point-at-eol))))
9594 ;; Only use search option if there is some text.
9595 (when (string-match "\\S-" txt)
9596 (setq cpltxt
9597 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9598 desc "NONE")))
9599 (setq link cpltxt))
9601 ((org-called-interactively-p 'interactive)
9602 (user-error "No method for storing a link from this buffer"))
9604 (t (setq link nil)))
9606 ;; We're done setting link and desc, clean up
9607 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9608 (setq link (or link cpltxt)
9609 desc (or desc cpltxt))
9610 (cond ((equal desc "NONE") (setq desc nil))
9611 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9612 (let ((d0 (match-string 3 desc))
9613 (p0 (match-string 5 desc)))
9614 (setq desc
9615 (replace-regexp-in-string
9616 org-bracket-link-regexp
9617 (concat (or p0 d0)
9618 (if (equal (length (match-string 0 desc))
9619 (length desc)) "*" "")) desc)))))
9621 ;; Return the link
9622 (if (not (and (or (org-called-interactively-p 'any)
9623 executing-kbd-macro) link))
9624 (or agenda-link (and link (org-make-link-string link desc)))
9625 (push (list link desc) org-stored-links)
9626 (message "Stored: %s" (or desc link))
9627 (when custom-id
9628 (setq link (concat "file:" (abbreviate-file-name
9629 (buffer-file-name)) "::#" custom-id))
9630 (push (list link desc) org-stored-links))
9631 (car org-stored-links))))))
9633 (defun org-store-link-props (&rest plist)
9634 "Store link properties, extract names and addresses."
9635 (let (x adr)
9636 (when (setq x (plist-get plist :from))
9637 (setq adr (mail-extract-address-components x))
9638 (setq plist (plist-put plist :fromname (car adr)))
9639 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9640 (when (setq x (plist-get plist :to))
9641 (setq adr (mail-extract-address-components x))
9642 (setq plist (plist-put plist :toname (car adr)))
9643 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9644 (let ((from (plist-get plist :from))
9645 (to (plist-get plist :to)))
9646 (when (and from to org-from-is-user-regexp)
9647 (setq plist
9648 (plist-put plist :fromto
9649 (if (string-match org-from-is-user-regexp from)
9650 (concat "to %t")
9651 (concat "from %f"))))))
9652 (setq org-store-link-plist plist))
9654 (defun org-add-link-props (&rest plist)
9655 "Add these properties to the link property list."
9656 (let (key value)
9657 (while plist
9658 (setq key (pop plist) value (pop plist))
9659 (setq org-store-link-plist
9660 (plist-put org-store-link-plist key value)))))
9662 (defun org-email-link-description (&optional fmt)
9663 "Return the description part of an email link.
9664 This takes information from `org-store-link-plist' and formats it
9665 according to FMT (default from `org-email-link-description-format')."
9666 (setq fmt (or fmt org-email-link-description-format))
9667 (let* ((p org-store-link-plist)
9668 (to (plist-get p :toaddress))
9669 (from (plist-get p :fromaddress))
9670 (table
9671 (list
9672 (cons "%c" (plist-get p :fromto))
9673 (cons "%F" (plist-get p :from))
9674 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9675 (cons "%T" (plist-get p :to))
9676 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9677 (cons "%s" (plist-get p :subject))
9678 (cons "%d" (plist-get p :date))
9679 (cons "%m" (plist-get p :message-id)))))
9680 (when (string-match "%c" fmt)
9681 ;; Check if the user wrote this message
9682 (if (and org-from-is-user-regexp from to
9683 (save-match-data (string-match org-from-is-user-regexp from)))
9684 (setq fmt (replace-match "to %t" t t fmt))
9685 (setq fmt (replace-match "from %f" t t fmt))))
9686 (org-replace-escapes fmt table)))
9688 (defun org-make-org-heading-search-string (&optional string)
9689 "Make search string for the current headline or STRING."
9690 (let ((s (or string
9691 (and (derived-mode-p 'org-mode)
9692 (save-excursion
9693 (org-back-to-heading t)
9694 (org-element-property :raw-value (org-element-at-point))))))
9695 (lines org-context-in-file-links))
9696 (or string (setq s (concat "*" s))) ; Add * for headlines
9697 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9698 (when (and string (integerp lines) (> lines 0))
9699 (let ((slines (org-split-string s "\n")))
9700 (when (< lines (length slines))
9701 (setq s (mapconcat
9702 'identity
9703 (reverse (nthcdr (- (length slines) lines)
9704 (reverse slines))) "\n")))))
9705 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9707 (defun org-make-link-string (link &optional description)
9708 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9709 (unless (string-match "\\S-" link)
9710 (error "Empty link"))
9711 (when (and description
9712 (stringp description)
9713 (not (string-match "\\S-" description)))
9714 (setq description nil))
9715 (when (stringp description)
9716 ;; Remove brackets from the description, they are fatal.
9717 (while (string-match "\\[" description)
9718 (setq description (replace-match "{" t t description)))
9719 (while (string-match "\\]" description)
9720 (setq description (replace-match "}" t t description))))
9721 (when (equal link description)
9722 ;; No description needed, it is identical
9723 (setq description nil))
9724 (when (and (not description)
9725 (not (string-match (org-image-file-name-regexp) link))
9726 (not (equal link (org-link-escape link))))
9727 (setq description (org-extract-attributes link)))
9728 (setq link
9729 (cond ((string-match (org-image-file-name-regexp) link) link)
9730 ((string-match org-link-types-re link)
9731 (concat (match-string 1 link)
9732 (org-link-escape (substring link (match-end 1)))))
9733 (t (org-link-escape link))))
9734 (concat "[[" link "]"
9735 (if description (concat "[" description "]") "")
9736 "]"))
9738 (defconst org-link-escape-chars
9739 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9740 "List of characters that should be escaped in link.
9741 This is the list that is used for internal purposes.")
9743 (defconst org-link-escape-chars-browser
9744 '(?\ ?\")
9745 "List of escapes for characters that are problematic in links.
9746 This is the list that is used before handing over to the browser.")
9748 (defun org-link-escape (text &optional table merge)
9749 "Return percent escaped representation of TEXT.
9750 TEXT is a string with the text to escape.
9751 Optional argument TABLE is a list with characters that should be
9752 escaped. When nil, `org-link-escape-chars' is used.
9753 If optional argument MERGE is set, merge TABLE into
9754 `org-link-escape-chars'."
9755 (cond
9756 ((and table merge)
9757 (mapc (lambda (defchr)
9758 (unless (member defchr table)
9759 (setq table (cons defchr table)))) org-link-escape-chars))
9760 ((null table)
9761 (setq table org-link-escape-chars)))
9762 (mapconcat
9763 (lambda (char)
9764 (if (or (member char table)
9765 (and (or (< char 32) (= char 37) (> char 126))
9766 org-url-hexify-p))
9767 (mapconcat (lambda (sequence-element)
9768 (format "%%%.2X" sequence-element))
9769 (or (encode-coding-char char 'utf-8)
9770 (error "Unable to percent escape character: %s"
9771 (char-to-string char))) "")
9772 (char-to-string char))) text ""))
9774 (defun org-link-unescape (str)
9775 "Unhex hexified Unicode strings as returned from the JavaScript function
9776 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9777 (unless (and (null str) (string= "" str))
9778 (let ((pos 0) (case-fold-search t) unhexed)
9779 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9780 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9781 (setq str (replace-match unhexed t t str))
9782 (setq pos (+ pos (length unhexed))))))
9783 str)
9785 (defun org-link-unescape-compound (hex)
9786 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9787 Note: this function also decodes single byte encodings like
9788 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9789 (save-match-data
9790 (let* ((bytes (cdr (split-string hex "%")))
9791 (ret "")
9792 (eat 0)
9793 (sum 0))
9794 (while bytes
9795 (let* ((val (string-to-number (pop bytes) 16))
9796 (shift-xor
9797 (if (= 0 eat)
9798 (cond
9799 ((>= val 252) (cons 6 252))
9800 ((>= val 248) (cons 5 248))
9801 ((>= val 240) (cons 4 240))
9802 ((>= val 224) (cons 3 224))
9803 ((>= val 192) (cons 2 192))
9804 (t (cons 0 0)))
9805 (cons 6 128))))
9806 (if (>= val 192) (setq eat (car shift-xor)))
9807 (setq val (logxor val (cdr shift-xor)))
9808 (setq sum (+ (lsh sum (car shift-xor)) val))
9809 (if (> eat 0) (setq eat (- eat 1)))
9810 (cond
9811 ((= 0 eat) ;multi byte
9812 (setq ret (concat ret (org-char-to-string sum)))
9813 (setq sum 0))
9814 ((not bytes) ; single byte(s)
9815 (setq ret (org-link-unescape-single-byte-sequence hex))))
9816 )) ;; end (while bytes
9817 ret )))
9819 (defun org-link-unescape-single-byte-sequence (hex)
9820 "Unhexify hex-encoded single byte character sequences."
9821 (mapconcat (lambda (byte)
9822 (char-to-string (string-to-number byte 16)))
9823 (cdr (split-string hex "%")) ""))
9825 (defun org-xor (a b)
9826 "Exclusive or."
9827 (if a (not b) b))
9829 (defun org-fixup-message-id-for-http (s)
9830 "Replace special characters in a message id, so it can be used in an http query."
9831 (when (string-match "%" s)
9832 (setq s (mapconcat (lambda (c)
9833 (if (eq c ?%)
9834 "%25"
9835 (char-to-string c)))
9836 s "")))
9837 (while (string-match "<" s)
9838 (setq s (replace-match "%3C" t t s)))
9839 (while (string-match ">" s)
9840 (setq s (replace-match "%3E" t t s)))
9841 (while (string-match "@" s)
9842 (setq s (replace-match "%40" t t s)))
9845 (defun org-link-prettify (link)
9846 "Return a human-readable representation of LINK.
9847 The car of LINK must be a raw link the cdr of LINK must be either
9848 a link description or nil."
9849 (let ((desc (or (cadr link) "<no description>")))
9850 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9851 "<" (car link) ">")))
9853 ;;;###autoload
9854 (defun org-insert-link-global ()
9855 "Insert a link like Org-mode does.
9856 This command can be called in any mode to insert a link in Org-mode syntax."
9857 (interactive)
9858 (org-load-modules-maybe)
9859 (org-run-like-in-org-mode 'org-insert-link))
9861 (defun org-insert-all-links (&optional keep)
9862 "Insert all links in `org-stored-links'."
9863 (interactive "P")
9864 (let ((links (copy-sequence org-stored-links)) l)
9865 (while (setq l (if keep (pop links) (pop org-stored-links)))
9866 (insert "- ")
9867 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9868 (insert "\n"))))
9870 (defun org-link-fontify-links-to-this-file ()
9871 "Fontify links to the current file in `org-stored-links'."
9872 (let ((f (buffer-file-name)) a b)
9873 (setq a (mapcar (lambda(l)
9874 (let ((ll (car l)))
9875 (when (and (string-match "^file:\\(.+\\)::" ll)
9876 (equal f (expand-file-name (match-string 1 ll))))
9877 ll)))
9878 org-stored-links))
9879 (when (featurep 'org-id)
9880 (setq b (mapcar (lambda(l)
9881 (let ((ll (car l)))
9882 (when (and (string-match "^id:\\(.+\\)$" ll)
9883 (equal f (expand-file-name
9884 (or (org-id-find-id-file
9885 (match-string 1 ll)) ""))))
9886 ll)))
9887 org-stored-links)))
9888 (mapcar (lambda(l)
9889 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9890 (delq nil (append a b)))))
9892 (defvar org-link-links-in-this-file nil)
9893 (defun org-insert-link (&optional complete-file link-location default-description)
9894 "Insert a link. At the prompt, enter the link.
9896 Completion can be used to insert any of the link protocol prefixes like
9897 http or ftp in use.
9899 The history can be used to select a link previously stored with
9900 `org-store-link'. When the empty string is entered (i.e. if you just
9901 press RET at the prompt), the link defaults to the most recently
9902 stored link. As SPC triggers completion in the minibuffer, you need to
9903 use M-SPC or C-q SPC to force the insertion of a space character.
9905 You will also be prompted for a description, and if one is given, it will
9906 be displayed in the buffer instead of the link.
9908 If there is already a link at point, this command will allow you to edit link
9909 and description parts.
9911 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9912 be selected using completion. The path to the file will be relative to the
9913 current directory if the file is in the current directory or a subdirectory.
9914 Otherwise, the link will be the absolute path as completed in the minibuffer
9915 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9916 option `org-link-file-path-type'.
9918 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9919 the current directory or below.
9921 With three \\[universal-argument] prefixes, negate the meaning of
9922 `org-keep-stored-link-after-insertion'.
9924 If `org-make-link-description-function' is non-nil, this function will be
9925 called with the link target, and the result will be the default
9926 link description.
9928 If the LINK-LOCATION parameter is non-nil, this value will be
9929 used as the link location instead of reading one interactively.
9931 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9932 be used as the default description."
9933 (interactive "P")
9934 (let* ((wcf (current-window-configuration))
9935 (origbuf (current-buffer))
9936 (region (if (org-region-active-p)
9937 (buffer-substring (region-beginning) (region-end))))
9938 (remove (and region (list (region-beginning) (region-end))))
9939 (desc region)
9940 tmphist ; byte-compile incorrectly complains about this
9941 (link link-location)
9942 (abbrevs org-link-abbrev-alist-local)
9943 entry file all-prefixes auto-desc)
9944 (cond
9945 (link-location) ; specified by arg, just use it.
9946 ((org-in-regexp org-bracket-link-regexp 1)
9947 ;; We do have a link at point, and we are going to edit it.
9948 (setq remove (list (match-beginning 0) (match-end 0)))
9949 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9950 (setq link (read-string "Link: "
9951 (org-link-unescape
9952 (org-match-string-no-properties 1)))))
9953 ((or (org-in-regexp org-angle-link-re)
9954 (org-in-regexp org-plain-link-re))
9955 ;; Convert to bracket link
9956 (setq remove (list (match-beginning 0) (match-end 0))
9957 link (read-string "Link: "
9958 (org-remove-angle-brackets (match-string 0)))))
9959 ((member complete-file '((4) (16)))
9960 ;; Completing read for file names.
9961 (setq link (org-file-complete-link complete-file)))
9963 ;; Read link, with completion for stored links.
9964 (org-link-fontify-links-to-this-file)
9965 (org-switch-to-buffer-other-window "*Org Links*")
9966 (with-current-buffer "*Org Links*"
9967 (erase-buffer)
9968 (insert "Insert a link.
9969 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9970 (when org-stored-links
9971 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9972 (insert (mapconcat 'org-link-prettify
9973 (reverse org-stored-links) "\n")))
9974 (goto-char (point-min)))
9975 (let ((cw (selected-window)))
9976 (select-window (get-buffer-window "*Org Links*" 'visible))
9977 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9978 (unless (pos-visible-in-window-p (point-max))
9979 (org-fit-window-to-buffer))
9980 (and (window-live-p cw) (select-window cw)))
9981 ;; Fake a link history, containing the stored links.
9982 (setq tmphist (append (mapcar 'car org-stored-links)
9983 org-insert-link-history))
9984 (setq all-prefixes (append (mapcar 'car abbrevs)
9985 (mapcar 'car org-link-abbrev-alist)
9986 org-link-types))
9987 (unwind-protect
9988 (progn
9989 (setq link
9990 (org-completing-read
9991 "Link: "
9992 (append
9993 (mapcar (lambda (x) (concat x ":"))
9994 all-prefixes)
9995 (mapcar 'car org-stored-links))
9996 nil nil nil
9997 'tmphist
9998 (caar org-stored-links)))
9999 (if (not (string-match "\\S-" link))
10000 (user-error "No link selected"))
10001 (mapc (lambda(l)
10002 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
10003 org-stored-links)
10004 (if (or (member link all-prefixes)
10005 (and (equal ":" (substring link -1))
10006 (member (substring link 0 -1) all-prefixes)
10007 (setq link (substring link 0 -1))))
10008 (setq link (with-current-buffer origbuf
10009 (org-link-try-special-completion link)))))
10010 (set-window-configuration wcf)
10011 (kill-buffer "*Org Links*"))
10012 (setq entry (assoc link org-stored-links))
10013 (or entry (push link org-insert-link-history))
10014 (setq desc (or desc (nth 1 entry)))))
10016 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10017 (not org-keep-stored-link-after-insertion))
10018 (setq org-stored-links (delq (assoc link org-stored-links)
10019 org-stored-links)))
10021 (if (and (string-match org-plain-link-re link)
10022 (not (string-match org-ts-regexp link)))
10023 ;; URL-like link, normalize the use of angular brackets.
10024 (setq link (org-remove-angle-brackets link)))
10026 ;; Check if we are linking to the current file with a search
10027 ;; option If yes, simplify the link by using only the search
10028 ;; option.
10029 (when (and buffer-file-name
10030 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10031 (let* ((path (match-string 1 link))
10032 (case-fold-search nil)
10033 (search (match-string 2 link)))
10034 (save-match-data
10035 (if (equal (file-truename buffer-file-name) (file-truename path))
10036 ;; We are linking to this same file, with a search option
10037 (setq link search)))))
10039 ;; Check if we can/should use a relative path. If yes, simplify the link
10040 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10041 (let* ((type (match-string 1 link))
10042 (path (match-string 2 link))
10043 (origpath path)
10044 (case-fold-search nil))
10045 (cond
10046 ((or (eq org-link-file-path-type 'absolute)
10047 (equal complete-file '(16)))
10048 (setq path (abbreviate-file-name (expand-file-name path))))
10049 ((eq org-link-file-path-type 'noabbrev)
10050 (setq path (expand-file-name path)))
10051 ((eq org-link-file-path-type 'relative)
10052 (setq path (file-relative-name path)))
10054 (save-match-data
10055 (if (string-match (concat "^" (regexp-quote
10056 (expand-file-name
10057 (file-name-as-directory
10058 default-directory))))
10059 (expand-file-name path))
10060 ;; We are linking a file with relative path name.
10061 (setq path (substring (expand-file-name path)
10062 (match-end 0)))
10063 (setq path (abbreviate-file-name (expand-file-name path)))))))
10064 (setq link (concat type path))
10065 (if (equal desc origpath)
10066 (setq desc path))))
10068 (if org-make-link-description-function
10069 (setq desc
10070 (or (condition-case nil
10071 (funcall org-make-link-description-function link desc)
10072 (error (progn (message "Can't get link description from `%s'"
10073 (symbol-name org-make-link-description-function))
10074 (sit-for 2) nil)))
10075 (read-string "Description: " default-description)))
10076 (if default-description (setq desc default-description)
10077 (setq desc (or (and auto-desc desc)
10078 (read-string "Description: " desc)))))
10080 (unless (string-match "\\S-" desc) (setq desc nil))
10081 (if remove (apply 'delete-region remove))
10082 (insert (org-make-link-string link desc))))
10084 (defun org-link-try-special-completion (type)
10085 "If there is completion support for link type TYPE, offer it."
10086 (let ((fun (intern (concat "org-" type "-complete-link"))))
10087 (if (functionp fun)
10088 (funcall fun)
10089 (read-string "Link (no completion support): " (concat type ":")))))
10091 (defun org-file-complete-link (&optional arg)
10092 "Create a file link using completion."
10093 (let (file link)
10094 (setq file (org-iread-file-name "File: "))
10095 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10096 (pwd1 (file-name-as-directory (abbreviate-file-name
10097 (expand-file-name ".")))))
10098 (cond
10099 ((equal arg '(16))
10100 (setq link (concat
10101 "file:"
10102 (abbreviate-file-name (expand-file-name file)))))
10103 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10104 (setq link (concat "file:" (match-string 1 file))))
10105 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10106 (expand-file-name file))
10107 (setq link (concat
10108 "file:" (match-string 1 (expand-file-name file)))))
10109 (t (setq link (concat "file:" file)))))
10110 link))
10112 (defun org-iread-file-name (&rest args)
10113 "Read-file-name using `ido-mode' speedup if available.
10114 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10115 See `read-file-name' for a description of parameters."
10116 (org-without-partial-completion
10117 (if (and org-completion-use-ido
10118 (fboundp 'ido-read-file-name)
10119 (boundp 'ido-mode) ido-mode
10120 (listp (second args)))
10121 (let ((ido-enter-matching-directory nil))
10122 (apply 'ido-read-file-name args))
10123 (apply 'read-file-name args))))
10125 (defun org-completing-read (&rest args)
10126 "Completing-read with SPACE being a normal character."
10127 (let ((enable-recursive-minibuffers t)
10128 (minibuffer-local-completion-map
10129 (copy-keymap minibuffer-local-completion-map)))
10130 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10131 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10132 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10133 (apply 'org-icompleting-read args)))
10135 (defun org-completing-read-no-i (&rest args)
10136 (let (org-completion-use-ido org-completion-use-iswitchb)
10137 (apply 'org-completing-read args)))
10139 (defun org-iswitchb-completing-read (prompt choices &rest args)
10140 "Use iswitch as a completing-read replacement to choose from choices.
10141 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10142 from."
10143 (let* ((iswitchb-use-virtual-buffers nil)
10144 (iswitchb-make-buflist-hook
10145 (lambda ()
10146 (setq iswitchb-temp-buflist choices))))
10147 (iswitchb-read-buffer prompt)))
10149 (defun org-icompleting-read (&rest args)
10150 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10151 (org-without-partial-completion
10152 (if (and org-completion-use-ido
10153 (fboundp 'ido-completing-read)
10154 (boundp 'ido-mode) ido-mode
10155 (listp (second args)))
10156 (let ((ido-enter-matching-directory nil))
10157 (apply 'ido-completing-read (concat (car args))
10158 (if (consp (car (nth 1 args)))
10159 (mapcar 'car (nth 1 args))
10160 (nth 1 args))
10161 (cddr args)))
10162 (if (and org-completion-use-iswitchb
10163 (boundp 'iswitchb-mode) iswitchb-mode
10164 (listp (second args)))
10165 (apply 'org-iswitchb-completing-read (concat (car args))
10166 (if (consp (car (nth 1 args)))
10167 (mapcar 'car (nth 1 args))
10168 (nth 1 args))
10169 (cddr args))
10170 (apply 'completing-read args)))))
10172 (defun org-extract-attributes (s)
10173 "Extract the attributes cookie from a string and set as text property."
10174 (let (a attr (start 0) key value)
10175 (save-match-data
10176 (when (string-match "{{\\([^}]+\\)}}$" s)
10177 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10178 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10179 (setq key (match-string 1 a) value (match-string 2 a)
10180 start (match-end 0)
10181 attr (plist-put attr (intern key) value))))
10182 (org-add-props s nil 'org-attr attr))
10185 ;;; Opening/following a link
10187 (defvar org-link-search-failed nil)
10189 (defvar org-open-link-functions nil
10190 "Hook for functions finding a plain text link.
10191 These functions must take a single argument, the link content.
10192 They will be called for links that look like [[link text][description]]
10193 when LINK TEXT does not have a protocol like \"http:\" and does not look
10194 like a filename (e.g. \"./blue.png\").
10196 These functions will be called *before* Org attempts to resolve the
10197 link by doing text searches in the current buffer - so if you want a
10198 link \"[[target]]\" to still find \"<<target>>\", your function should
10199 handle this as a special case.
10201 When the function does handle the link, it must return a non-nil value.
10202 If it decides that it is not responsible for this link, it must return
10203 nil to indicate that that Org-mode can continue with other options
10204 like exact and fuzzy text search.")
10206 (defun org-next-link (&optional search-backward)
10207 "Move forward to the next link.
10208 If the link is in hidden text, expose it."
10209 (interactive "P")
10210 (when (and org-link-search-failed (eq this-command last-command))
10211 (goto-char (point-min))
10212 (message "Link search wrapped back to beginning of buffer"))
10213 (setq org-link-search-failed nil)
10214 (let* ((pos (point))
10215 (ct (org-context))
10216 (a (assoc :link ct))
10217 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10218 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10219 ((looking-at org-any-link-re)
10220 ;; Don't stay stuck at link without an org-link face
10221 (forward-char (if search-backward -1 1))))
10222 (if (funcall srch-fun org-any-link-re nil t)
10223 (progn
10224 (goto-char (match-beginning 0))
10225 (if (outline-invisible-p) (org-show-context)))
10226 (goto-char pos)
10227 (setq org-link-search-failed t)
10228 (message "No further link found"))))
10230 (defun org-previous-link ()
10231 "Move backward to the previous link.
10232 If the link is in hidden text, expose it."
10233 (interactive)
10234 (funcall 'org-next-link t))
10236 (defun org-translate-link (s)
10237 "Translate a link string if a translation function has been defined."
10238 (if (and org-link-translation-function
10239 (fboundp org-link-translation-function)
10240 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10241 (progn
10242 (setq s (funcall org-link-translation-function
10243 (match-string 1 s) (match-string 2 s)))
10244 (concat (car s) ":" (cdr s)))
10247 (defun org-translate-link-from-planner (type path)
10248 "Translate a link from Emacs Planner syntax so that Org can follow it.
10249 This is still an experimental function, your mileage may vary."
10250 (cond
10251 ((member type '("http" "https" "news" "ftp"))
10252 ;; standard Internet links are the same.
10253 nil)
10254 ((and (equal type "irc") (string-match "^//" path))
10255 ;; Planner has two / at the beginning of an irc link, we have 1.
10256 ;; We should have zero, actually....
10257 (setq path (substring path 1)))
10258 ((and (equal type "lisp") (string-match "^/" path))
10259 ;; Planner has a slash, we do not.
10260 (setq type "elisp" path (substring path 1)))
10261 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10262 ;; A typical message link. Planner has the id after the final slash,
10263 ;; we separate it with a hash mark
10264 (setq path (concat (match-string 1 path) "#"
10265 (org-remove-angle-brackets (match-string 2 path))))))
10266 (cons type path))
10268 (defun org-find-file-at-mouse (ev)
10269 "Open file link or URL at mouse."
10270 (interactive "e")
10271 (mouse-set-point ev)
10272 (org-open-at-point 'in-emacs))
10274 (defun org-open-at-mouse (ev)
10275 "Open file link or URL at mouse.
10276 See the docstring of `org-open-file' for details."
10277 (interactive "e")
10278 (mouse-set-point ev)
10279 (if (eq major-mode 'org-agenda-mode)
10280 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10281 (org-open-at-point))
10283 (defvar org-window-config-before-follow-link nil
10284 "The window configuration before following a link.
10285 This is saved in case the need arises to restore it.")
10287 (defvar org-open-link-marker (make-marker)
10288 "Marker pointing to the location where `org-open-at-point' was called.")
10290 ;;;###autoload
10291 (defun org-open-at-point-global ()
10292 "Follow a link like Org-mode does.
10293 This command can be called in any mode to follow a link that has
10294 Org-mode syntax."
10295 (interactive)
10296 (org-run-like-in-org-mode 'org-open-at-point))
10298 ;;;###autoload
10299 (defun org-open-link-from-string (s &optional arg reference-buffer)
10300 "Open a link in the string S, as if it was in Org-mode."
10301 (interactive "sLink: \nP")
10302 (let ((reference-buffer (or reference-buffer (current-buffer))))
10303 (with-temp-buffer
10304 (let ((org-inhibit-startup (not reference-buffer)))
10305 (org-mode)
10306 (insert s)
10307 (goto-char (point-min))
10308 (when reference-buffer
10309 (setq org-link-abbrev-alist-local
10310 (with-current-buffer reference-buffer
10311 org-link-abbrev-alist-local)))
10312 (org-open-at-point arg reference-buffer)))))
10314 (defvar org-open-at-point-functions nil
10315 "Hook that is run when following a link at point.
10317 Functions in this hook must return t if they identify and follow
10318 a link at point. If they don't find anything interesting at point,
10319 they must return nil.")
10321 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10322 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10323 (defun org-open-at-point (&optional arg reference-buffer)
10324 "Open link at or after point.
10325 If there is no link at point, this function will search forward up to
10326 the end of the current line.
10327 Normally, files will be opened by an appropriate application. If the
10328 optional prefix argument ARG is non-nil, Emacs will visit the file.
10329 With a double prefix argument, try to open outside of Emacs, in the
10330 application the system uses for this file type."
10331 (interactive "P")
10332 ;; if in a code block, then open the block's results
10333 (unless (call-interactively #'org-babel-open-src-block-result)
10334 (org-load-modules-maybe)
10335 (move-marker org-open-link-marker (point))
10336 (setq org-window-config-before-follow-link (current-window-configuration))
10337 (org-remove-occur-highlights nil nil t)
10338 (cond
10339 ((and (org-at-heading-p)
10340 (not (org-at-timestamp-p t))
10341 (not (org-in-regexp
10342 (concat org-plain-link-re "\\|"
10343 org-bracket-link-regexp "\\|"
10344 org-angle-link-re "\\|"
10345 "[ \t]:[^ \t\n]+:[ \t]*$")))
10346 (not (get-text-property (point) 'org-linked-text)))
10347 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10348 (lk0 (car lkall))
10349 (lk (if (stringp lk0) (list lk0) lk0))
10350 (lkend (cdr lkall)))
10351 (mapcar (lambda(l)
10352 (search-forward l nil lkend)
10353 (goto-char (match-beginning 0))
10354 (org-open-at-point))
10355 lk))
10356 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10357 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10358 ((and (org-at-timestamp-p t)
10359 (not (org-in-regexp org-bracket-link-regexp)))
10360 (org-follow-timestamp-link))
10361 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10362 (not (org-in-regexp org-any-link-re)))
10363 (org-footnote-action))
10365 (let (type path link line search (pos (point)))
10366 (catch 'match
10367 (save-excursion
10368 (or (org-in-regexp org-plain-link-re)
10369 (skip-chars-forward "^]\n\r"))
10370 (when (org-in-regexp org-bracket-link-regexp 1)
10371 (setq link (org-extract-attributes
10372 (org-link-unescape (org-match-string-no-properties 1))))
10373 (while (string-match " *\n *" link)
10374 (setq link (replace-match " " t t link)))
10375 (setq link (org-link-expand-abbrev link))
10376 (cond
10377 ((or (file-name-absolute-p link)
10378 (string-match "^\\.\\.?/" link))
10379 (setq type "file" path link))
10380 ((string-match org-link-re-with-space3 link)
10381 (setq type (match-string 1 link) path (match-string 2 link)))
10382 ((string-match "^help:+\\(.+\\)" link)
10383 (setq type "help" path (match-string 1 link)))
10384 (t (setq type "thisfile" path link)))
10385 (throw 'match t)))
10387 (when (get-text-property (point) 'org-linked-text)
10388 (setq type "thisfile"
10389 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10390 (1+ (point)) (point))
10391 path (buffer-substring
10392 (or (previous-single-property-change pos 'org-linked-text)
10393 (point-min))
10394 (or (next-single-property-change pos 'org-linked-text)
10395 (point-max)))
10396 ;; Ensure we will search for a <<<radio>>> link, not
10397 ;; a simple reference like <<ref>>
10398 path (concat "<" path))
10399 (throw 'match t))
10401 (save-excursion
10402 (when (or (org-in-regexp org-angle-link-re)
10403 (let ((match (org-in-regexp org-plain-link-re)))
10404 ;; Check a plain link is not within a bracket link
10405 (and match
10406 (save-excursion
10407 (save-match-data
10408 (progn
10409 (goto-char (car match))
10410 (not (org-in-regexp org-bracket-link-regexp)))))))
10411 (let ((line_ending (save-excursion (end-of-line) (point))))
10412 ;; We are in a line before a plain or bracket link
10413 (or (re-search-forward org-plain-link-re line_ending t)
10414 (re-search-forward org-bracket-link-regexp line_ending t))))
10415 (setq type (match-string 1)
10416 path (org-link-unescape (match-string 2)))
10417 (throw 'match t)))
10418 (save-excursion
10419 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10420 (setq type "tags"
10421 path (match-string 1))
10422 (while (string-match ":" path)
10423 (setq path (replace-match "+" t t path)))
10424 (throw 'match t)))
10425 (when (org-in-regexp "<\\([^><\n]+\\)>")
10426 (setq type "tree-match"
10427 path (match-string 1))
10428 (throw 'match t)))
10429 (unless path
10430 (user-error "No link found"))
10432 ;; switch back to reference buffer
10433 ;; needed when if called in a temporary buffer through
10434 ;; org-open-link-from-string
10435 (with-current-buffer (or reference-buffer (current-buffer))
10437 ;; Remove any trailing spaces in path
10438 (if (string-match " +\\'" path)
10439 (setq path (replace-match "" t t path)))
10440 (if (and org-link-translation-function
10441 (fboundp org-link-translation-function))
10442 ;; Check if we need to translate the link
10443 (let ((tmp (funcall org-link-translation-function type path)))
10444 (setq type (car tmp) path (cdr tmp))))
10446 (cond
10448 ((assoc type org-link-protocols)
10449 (funcall (nth 1 (assoc type org-link-protocols)) path))
10451 ((equal type "help")
10452 (let ((f-or-v (intern path)))
10453 (cond ((fboundp f-or-v)
10454 (describe-function f-or-v))
10455 ((boundp f-or-v)
10456 (describe-variable f-or-v))
10457 (t (error "Not a known function or variable")))))
10459 ((equal type "mailto")
10460 (let ((cmd (car org-link-mailto-program))
10461 (args (cdr org-link-mailto-program)) args1
10462 (address path) (subject "") a)
10463 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10464 (setq address (match-string 1 path)
10465 subject (org-link-escape (match-string 2 path))))
10466 (while args
10467 (cond
10468 ((not (stringp (car args))) (push (pop args) args1))
10469 (t (setq a (pop args))
10470 (if (string-match "%a" a)
10471 (setq a (replace-match address t t a)))
10472 (if (string-match "%s" a)
10473 (setq a (replace-match subject t t a)))
10474 (push a args1))))
10475 (apply cmd (nreverse args1))))
10477 ((member type '("http" "https" "ftp" "news"))
10478 (browse-url
10479 (concat type ":"
10480 (if (org-string-match-p
10481 (concat "[[:nonascii:]"
10482 org-link-escape-chars-browser "]")
10483 path)
10484 (org-link-escape path org-link-escape-chars-browser)
10485 path))))
10487 ((string= type "doi")
10488 (browse-url
10489 (concat org-doi-server-url
10490 (if (org-string-match-p
10491 (concat "[[:nonascii:]"
10492 org-link-escape-chars-browser "]")
10493 path)
10494 (org-link-escape path org-link-escape-chars-browser)
10495 path))))
10497 ((member type '("message"))
10498 (browse-url (concat type ":" path)))
10500 ((string= type "tags")
10501 (org-tags-view arg path))
10503 ((string= type "tree-match")
10504 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10506 ((string= type "file")
10507 (if (string-match "::\\([0-9]+\\)\\'" path)
10508 (setq line (string-to-number (match-string 1 path))
10509 path (substring path 0 (match-beginning 0)))
10510 (if (string-match "::\\(.+\\)\\'" path)
10511 (setq search (match-string 1 path)
10512 path (substring path 0 (match-beginning 0)))))
10513 (if (string-match "[*?{]" (file-name-nondirectory path))
10514 (dired path)
10515 (org-open-file path arg line search)))
10517 ((string= type "shell")
10518 (let ((buf (generate-new-buffer "*Org Shell Output"))
10519 (cmd path))
10520 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10521 (string-match org-confirm-shell-link-not-regexp cmd))
10522 (not org-confirm-shell-link-function)
10523 (funcall org-confirm-shell-link-function
10524 (format "Execute \"%s\" in shell? "
10525 (org-add-props cmd nil
10526 'face 'org-warning))))
10527 (progn
10528 (message "Executing %s" cmd)
10529 (shell-command cmd buf)
10530 (if (featurep 'midnight)
10531 (setq clean-buffer-list-kill-buffer-names
10532 (cons buf clean-buffer-list-kill-buffer-names))))
10533 (error "Abort"))))
10535 ((string= type "elisp")
10536 (let ((cmd path))
10537 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10538 (string-match org-confirm-elisp-link-not-regexp cmd))
10539 (not org-confirm-elisp-link-function)
10540 (funcall org-confirm-elisp-link-function
10541 (format "Execute \"%s\" as elisp? "
10542 (org-add-props cmd nil
10543 'face 'org-warning))))
10544 (message "%s => %s" cmd
10545 (if (equal (string-to-char cmd) ?\()
10546 (eval (read cmd))
10547 (call-interactively (read cmd))))
10548 (error "Abort"))))
10550 ((and (string= type "thisfile")
10551 (or (run-hook-with-args-until-success
10552 'org-open-link-functions path)
10553 (and link
10554 (string-match "^id:" link)
10555 (or (featurep 'org-id) (require 'org-id))
10556 (progn
10557 (funcall (nth 1 (assoc "id" org-link-protocols))
10558 (substring path 3))
10559 t)))))
10561 ((string= type "thisfile")
10562 (if arg
10563 (switch-to-buffer-other-window
10564 (org-get-buffer-for-internal-link (current-buffer)))
10565 (org-mark-ring-push))
10566 (let ((cmd `(org-link-search
10567 ,path
10568 ,(cond ((equal arg '(4)) ''occur)
10569 ((equal arg '(16)) ''org-occur))
10570 ,pos)))
10571 (condition-case nil (let ((org-link-search-inhibit-query t))
10572 (eval cmd))
10573 (error (progn (widen) (eval cmd))))))
10575 (t (browse-url-at-point)))))))
10576 (move-marker org-open-link-marker nil)
10577 (run-hook-with-args 'org-follow-link-hook)))
10579 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10580 "Offer links in the current entry and return the selected link.
10581 If there is only one link, return it.
10582 If NTH is an integer, return the NTH link found.
10583 If ZERO is a string, check also this string for a link, and if
10584 there is one, return it."
10585 (with-current-buffer buffer
10586 (save-excursion
10587 (save-restriction
10588 (widen)
10589 (goto-char marker)
10590 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10591 "\\(" org-angle-link-re "\\)\\|"
10592 "\\(" org-plain-link-re "\\)"))
10593 (cnt ?0)
10594 (in-emacs (if (integerp nth) nil nth))
10595 have-zero end links link c)
10596 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10597 (push (match-string 0 zero) links)
10598 (setq cnt (1- cnt) have-zero t))
10599 (save-excursion
10600 (org-back-to-heading t)
10601 (setq end (save-excursion (outline-next-heading) (point)))
10602 (while (re-search-forward re end t)
10603 (push (match-string 0) links))
10604 (setq links (org-uniquify (reverse links))))
10605 (cond
10606 ((null links)
10607 (message "No links"))
10608 ((equal (length links) 1)
10609 (setq link (car links)))
10610 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10611 (setq link (nth (if have-zero nth (1- nth)) links)))
10612 (t ; we have to select a link
10613 (save-excursion
10614 (save-window-excursion
10615 (delete-other-windows)
10616 (with-output-to-temp-buffer "*Select Link*"
10617 (mapc (lambda (l)
10618 (if (not (string-match org-bracket-link-regexp l))
10619 (princ (format "[%c] %s\n" (incf cnt)
10620 (org-remove-angle-brackets l)))
10621 (if (match-end 3)
10622 (princ (format "[%c] %s (%s)\n" (incf cnt)
10623 (match-string 3 l) (match-string 1 l)))
10624 (princ (format "[%c] %s\n" (incf cnt)
10625 (match-string 1 l))))))
10626 links))
10627 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10628 (message "Select link to open, RET to open all:")
10629 (setq c (read-char-exclusive))
10630 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10631 (when (equal c ?q) (error "Abort"))
10632 (if (equal c ?\C-m)
10633 (setq link links)
10634 (setq nth (- c ?0))
10635 (if have-zero (setq nth (1+ nth)))
10636 (unless (and (integerp nth) (>= (length links) nth))
10637 (user-error "Invalid link selection"))
10638 (setq link (nth (1- nth) links)))))
10639 (cons link end))))))
10641 ;; Add special file links that specify the way of opening
10643 (org-add-link-type "file+sys" 'org-open-file-with-system)
10644 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10645 (defun org-open-file-with-system (path)
10646 "Open file at PATH using the system way of opening it."
10647 (org-open-file path 'system))
10648 (defun org-open-file-with-emacs (path)
10649 "Open file at PATH in Emacs."
10650 (org-open-file path 'emacs))
10653 ;;; File search
10655 (defvar org-create-file-search-functions nil
10656 "List of functions to construct the right search string for a file link.
10657 These functions are called in turn with point at the location to
10658 which the link should point.
10660 A function in the hook should first test if it would like to
10661 handle this file type, for example by checking the `major-mode'
10662 or the file extension. If it decides not to handle this file, it
10663 should just return nil to give other functions a chance. If it
10664 does handle the file, it must return the search string to be used
10665 when following the link. The search string will be part of the
10666 file link, given after a double colon, and `org-open-at-point'
10667 will automatically search for it. If special measures must be
10668 taken to make the search successful, another function should be
10669 added to the companion hook `org-execute-file-search-functions',
10670 which see.
10672 A function in this hook may also use `setq' to set the variable
10673 `description' to provide a suggestion for the descriptive text to
10674 be used for this link when it gets inserted into an Org-mode
10675 buffer with \\[org-insert-link].")
10677 (defvar org-execute-file-search-functions nil
10678 "List of functions to execute a file search triggered by a link.
10680 Functions added to this hook must accept a single argument, the
10681 search string that was part of the file link, the part after the
10682 double colon. The function must first check if it would like to
10683 handle this search, for example by checking the `major-mode' or
10684 the file extension. If it decides not to handle this search, it
10685 should just return nil to give other functions a chance. If it
10686 does handle the search, it must return a non-nil value to keep
10687 other functions from trying.
10689 Each function can access the current prefix argument through the
10690 variable `current-prefix-arg'. Note that a single prefix is used
10691 to force opening a link in Emacs, so it may be good to only use a
10692 numeric or double prefix to guide the search function.
10694 In case this is needed, a function in this hook can also restore
10695 the window configuration before `org-open-at-point' was called using:
10697 (set-window-configuration org-window-config-before-follow-link)")
10699 (defun org-link-search (s &optional type avoid-pos stealth)
10700 "Search for a link search option.
10701 If S is surrounded by forward slashes, it is interpreted as a
10702 regular expression. In org-mode files, this will create an `org-occur'
10703 sparse tree. In ordinary files, `occur' will be used to list matches.
10704 If the current buffer is in `dired-mode', grep will be used to search
10705 in all files. If AVOID-POS is given, ignore matches near that position.
10707 When optional argument STEALTH is non-nil, do not modify
10708 visibility around point, thus ignoring
10709 `org-show-hierarchy-above', `org-show-following-heading' and
10710 `org-show-siblings' variables."
10711 (let ((case-fold-search t)
10712 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10713 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10714 (append '(("") (" ") ("\t") ("\n"))
10715 org-emphasis-alist)
10716 "\\|") "\\)"))
10717 (pos (point))
10718 (pre nil) (post nil)
10719 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10720 (cond
10721 ;; First check if there are any special search functions
10722 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10723 ;; Now try the builtin stuff
10724 ((and (equal (string-to-char s0) ?#)
10725 (> (length s0) 1)
10726 (save-excursion
10727 (goto-char (point-min))
10728 (and
10729 (re-search-forward
10730 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10731 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10732 (setq type 'dedicated
10733 pos (match-beginning 0))))
10734 ;; There is an exact target for this
10735 (goto-char pos)
10736 (org-back-to-heading t)))
10737 ((save-excursion
10738 (goto-char (point-min))
10739 (and
10740 (re-search-forward
10741 (concat "<<" (regexp-quote s0) ">>") nil t)
10742 (setq type 'dedicated
10743 pos (match-beginning 0))))
10744 ;; There is an exact target for this
10745 (goto-char pos))
10746 ((save-excursion
10747 (goto-char (point-min))
10748 (and
10749 (re-search-forward
10750 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10751 (setq type 'dedicated pos (match-beginning 0))))
10752 ;; Found an element with a matching #+name affiliated keyword.
10753 (goto-char pos))
10754 ((and (string-match "^(\\(.*\\))$" s0)
10755 (save-excursion
10756 (goto-char (point-min))
10757 (and
10758 (re-search-forward
10759 (concat "[^[]" (regexp-quote
10760 (format org-coderef-label-format
10761 (match-string 1 s0))))
10762 nil t)
10763 (setq type 'dedicated
10764 pos (1+ (match-beginning 0))))))
10765 ;; There is a coderef target for this
10766 (goto-char pos))
10767 ((string-match "^/\\(.*\\)/$" s)
10768 ;; A regular expression
10769 (cond
10770 ((derived-mode-p 'org-mode)
10771 (org-occur (match-string 1 s)))
10772 (t (org-do-occur (match-string 1 s)))))
10773 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10774 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10775 (goto-char (point-min))
10776 (cond
10777 ((let (case-fold-search)
10778 (re-search-forward (format org-complex-heading-regexp-format
10779 (regexp-quote s))
10780 nil t))
10781 ;; OK, found a match
10782 (setq type 'dedicated)
10783 (goto-char (match-beginning 0)))
10784 ((and (not org-link-search-inhibit-query)
10785 (eq org-link-search-must-match-exact-headline 'query-to-create)
10786 (y-or-n-p "No match - create this as a new heading? "))
10787 (goto-char (point-max))
10788 (or (bolp) (newline))
10789 (insert "* " s "\n")
10790 (beginning-of-line 0))
10792 (goto-char pos)
10793 (error "No match"))))
10795 ;; A normal search string
10796 (when (equal (string-to-char s) ?*)
10797 ;; Anchor on headlines, post may include tags.
10798 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10799 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10800 s (substring s 1)))
10801 (remove-text-properties
10802 0 (length s)
10803 '(face nil mouse-face nil keymap nil fontified nil) s)
10804 ;; Make a series of regular expressions to find a match
10805 (setq words (org-split-string s "[ \n\r\t]+")
10807 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10808 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10809 "\\)" markers)
10810 re2a_ (concat "\\(" (mapconcat 'downcase words
10811 "[ \t\r\n]+") "\\)[ \t\r\n]")
10812 re2a (concat "[ \t\r\n]" re2a_)
10813 re4_ (concat "\\(" (mapconcat 'downcase words
10814 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10815 re4 (concat "[^a-zA-Z_]" re4_)
10817 re1 (concat pre re2 post)
10818 re3 (concat pre (if pre re4_ re4) post)
10819 re5 (concat pre ".*" re4)
10820 re2 (concat pre re2)
10821 re2a (concat pre (if pre re2a_ re2a))
10822 re4 (concat pre (if pre re4_ re4))
10823 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10824 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10825 re5 "\\)"))
10826 (cond
10827 ((eq type 'org-occur) (org-occur reall))
10828 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10829 (t (goto-char (point-min))
10830 (setq type 'fuzzy)
10831 (if (or (and (org-search-not-self 1 re0 nil t)
10832 (setq type 'dedicated))
10833 (org-search-not-self 1 re1 nil t)
10834 (org-search-not-self 1 re2 nil t)
10835 (org-search-not-self 1 re2a nil t)
10836 (org-search-not-self 1 re3 nil t)
10837 (org-search-not-self 1 re4 nil t)
10838 (org-search-not-self 1 re5 nil t))
10839 (goto-char (match-beginning 1))
10840 (goto-char pos)
10841 (error "No match"))))))
10842 (and (derived-mode-p 'org-mode)
10843 (not stealth)
10844 (org-show-context 'link-search))
10845 type))
10847 (defun org-search-not-self (group &rest args)
10848 "Execute `re-search-forward', but only accept matches that do not
10849 enclose the position of `org-open-link-marker'."
10850 (let ((m org-open-link-marker))
10851 (catch 'exit
10852 (while (apply 're-search-forward args)
10853 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10854 (goto-char (match-end group))
10855 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10856 (> (match-beginning 0) (marker-position m))
10857 (< (match-end 0) (marker-position m)))
10858 (save-match-data
10859 (or (not (org-in-regexp
10860 org-bracket-link-analytic-regexp 1))
10861 (not (match-end 4)) ; no description
10862 (and (<= (match-beginning 4) (point))
10863 (>= (match-end 4) (point))))))
10864 (throw 'exit (point))))))))
10866 (defun org-get-buffer-for-internal-link (buffer)
10867 "Return a buffer to be used for displaying the link target of internal links."
10868 (cond
10869 ((not org-display-internal-link-with-indirect-buffer)
10870 buffer)
10871 ((string-match "(Clone)$" (buffer-name buffer))
10872 (message "Buffer is already a clone, not making another one")
10873 ;; we also do not modify visibility in this case
10874 buffer)
10875 (t ; make a new indirect buffer for displaying the link
10876 (let* ((bn (buffer-name buffer))
10877 (ibn (concat bn "(Clone)"))
10878 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10879 (with-current-buffer ib (org-overview))
10880 ib))))
10882 (defun org-do-occur (regexp &optional cleanup)
10883 "Call the Emacs command `occur'.
10884 If CLEANUP is non-nil, remove the printout of the regular expression
10885 in the *Occur* buffer. This is useful if the regex is long and not useful
10886 to read."
10887 (occur regexp)
10888 (when cleanup
10889 (let ((cwin (selected-window)) win beg end)
10890 (when (setq win (get-buffer-window "*Occur*"))
10891 (select-window win))
10892 (goto-char (point-min))
10893 (when (re-search-forward "match[a-z]+" nil t)
10894 (setq beg (match-end 0))
10895 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10896 (setq end (1- (match-beginning 0)))))
10897 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10898 (goto-char (point-min))
10899 (select-window cwin))))
10901 ;;; The mark ring for links jumps
10903 (defvar org-mark-ring nil
10904 "Mark ring for positions before jumps in Org-mode.")
10905 (defvar org-mark-ring-last-goto nil
10906 "Last position in the mark ring used to go back.")
10907 ;; Fill and close the ring
10908 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10909 (loop for i from 1 to org-mark-ring-length do
10910 (push (make-marker) org-mark-ring))
10911 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10912 org-mark-ring)
10914 (defun org-mark-ring-push (&optional pos buffer)
10915 "Put the current position or POS into the mark ring and rotate it."
10916 (interactive)
10917 (setq pos (or pos (point)))
10918 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10919 (move-marker (car org-mark-ring)
10920 (or pos (point))
10921 (or buffer (current-buffer)))
10922 (message "%s"
10923 (substitute-command-keys
10924 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10926 (defun org-mark-ring-goto (&optional n)
10927 "Jump to the previous position in the mark ring.
10928 With prefix arg N, jump back that many stored positions. When
10929 called several times in succession, walk through the entire ring.
10930 Org-mode commands jumping to a different position in the current file,
10931 or to another Org-mode file, automatically push the old position
10932 onto the ring."
10933 (interactive "p")
10934 (let (p m)
10935 (if (eq last-command this-command)
10936 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10937 (setq p org-mark-ring))
10938 (setq org-mark-ring-last-goto p)
10939 (setq m (car p))
10940 (org-pop-to-buffer-same-window (marker-buffer m))
10941 (goto-char m)
10942 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10944 (defun org-remove-angle-brackets (s)
10945 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10946 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10948 (defun org-add-angle-brackets (s)
10949 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10950 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10952 (defun org-remove-double-quotes (s)
10953 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10954 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10957 ;;; Following specific links
10959 (defun org-follow-timestamp-link ()
10960 "Open an agenda view for the time-stamp date/range at point."
10961 (cond
10962 ((org-at-date-range-p t)
10963 (let ((org-agenda-start-on-weekday)
10964 (t1 (match-string 1))
10965 (t2 (match-string 2)) tt1 tt2)
10966 (setq tt1 (time-to-days (org-time-string-to-time t1))
10967 tt2 (time-to-days (org-time-string-to-time t2)))
10968 (let ((org-agenda-buffer-tmp-name
10969 (format "*Org Agenda(a:%s)"
10970 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10971 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10972 ((org-at-timestamp-p t)
10973 (let ((org-agenda-buffer-tmp-name
10974 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10975 (org-agenda-list nil (time-to-days (org-time-string-to-time
10976 (substring (match-string 1) 0 10)))
10977 1)))
10978 (t (error "This should not happen"))))
10981 ;;; Following file links
10982 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10983 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10984 (declare-function mailcap-mime-info
10985 "mailcap" (string &optional request no-decode))
10986 (defvar org-wait nil)
10987 (defun org-open-file (path &optional in-emacs line search)
10988 "Open the file at PATH.
10989 First, this expands any special file name abbreviations. Then the
10990 configuration variable `org-file-apps' is checked if it contains an
10991 entry for this file type, and if yes, the corresponding command is launched.
10993 If no application is found, Emacs simply visits the file.
10995 With optional prefix argument IN-EMACS, Emacs will visit the file.
10996 With a double \\[universal-argument] \\[universal-argument] \
10997 prefix arg, Org tries to avoid opening in Emacs
10998 and to use an external application to visit the file.
11000 Optional LINE specifies a line to go to, optional SEARCH a string
11001 to search for. If LINE or SEARCH is given, the file will be
11002 opened in Emacs, unless an entry from org-file-apps that makes
11003 use of groups in a regexp matches.
11005 If you want to change the way frames are used when following a
11006 link, please customize `org-link-frame-setup'.
11008 If the file does not exist, an error is thrown."
11009 (let* ((file (if (equal path "")
11010 buffer-file-name
11011 (substitute-in-file-name (expand-file-name path))))
11012 (file-apps (append org-file-apps (org-default-apps)))
11013 (apps (org-remove-if
11014 'org-file-apps-entry-match-against-dlink-p file-apps))
11015 (apps-dlink (org-remove-if-not
11016 'org-file-apps-entry-match-against-dlink-p file-apps))
11017 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11018 (dirp (if remp nil (file-directory-p file)))
11019 (file (if (and dirp org-open-directory-means-index-dot-org)
11020 (concat (file-name-as-directory file) "index.org")
11021 file))
11022 (a-m-a-p (assq 'auto-mode apps))
11023 (dfile (downcase file))
11024 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11025 (link (cond ((and (eq line nil)
11026 (eq search nil))
11027 file)
11028 (line
11029 (concat file "::" (number-to-string line)))
11030 (search
11031 (concat file "::" search))))
11032 (dlink (downcase link))
11033 (old-buffer (current-buffer))
11034 (old-pos (point))
11035 (old-mode major-mode)
11036 ext cmd link-match-data)
11037 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11038 (setq ext (match-string 1 dfile))
11039 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11040 (setq ext (match-string 1 dfile))))
11041 (cond
11042 ((member in-emacs '((16) system))
11043 (setq cmd (cdr (assoc 'system apps))))
11044 (in-emacs (setq cmd 'emacs))
11046 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11047 (and dirp (cdr (assoc 'directory apps)))
11048 ; first, try matching against apps-dlink
11049 ; if we get a match here, store the match data for later
11050 (let ((match (assoc-default dlink apps-dlink
11051 'string-match)))
11052 (if match
11053 (progn (setq link-match-data (match-data))
11054 match)
11055 (progn (setq in-emacs (or in-emacs line search))
11056 nil))) ; if we have no match in apps-dlink,
11057 ; always open the file in emacs if line or search
11058 ; is given (for backwards compatibility)
11059 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11060 'string-match)
11061 (cdr (assoc ext apps))
11062 (cdr (assoc t apps))))))
11063 (when (eq cmd 'system)
11064 (setq cmd (cdr (assoc 'system apps))))
11065 (when (eq cmd 'default)
11066 (setq cmd (cdr (assoc t apps))))
11067 (when (eq cmd 'mailcap)
11068 (require 'mailcap)
11069 (mailcap-parse-mailcaps)
11070 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11071 (command (mailcap-mime-info mime-type)))
11072 (if (stringp command)
11073 (setq cmd command)
11074 (setq cmd 'emacs))))
11075 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11076 (not (file-exists-p file))
11077 (not org-open-non-existing-files))
11078 (user-error "No such file: %s" file))
11079 (cond
11080 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11081 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11082 (while (string-match "['\"]%s['\"]" cmd)
11083 (setq cmd (replace-match "%s" t t cmd)))
11084 (while (string-match "%s" cmd)
11085 (setq cmd (replace-match
11086 (save-match-data
11087 (shell-quote-argument
11088 (convert-standard-filename file)))
11089 t t cmd)))
11091 ;; Replace "%1", "%2" etc. in command with group matches from regex
11092 (save-match-data
11093 (let ((match-index 1)
11094 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11095 (set-match-data link-match-data)
11096 (while (<= match-index number-of-groups)
11097 (let ((regex (concat "%" (number-to-string match-index)))
11098 (replace-with (match-string match-index dlink)))
11099 (while (string-match regex cmd)
11100 (setq cmd (replace-match replace-with t t cmd))))
11101 (setq match-index (+ match-index 1)))))
11103 (save-window-excursion
11104 (message "Running %s...done" cmd)
11105 (start-process-shell-command cmd nil cmd)
11106 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11107 ((or (stringp cmd)
11108 (eq cmd 'emacs))
11109 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11110 (widen)
11111 (if line (org-goto-line line)
11112 (if search (org-link-search search))))
11113 ((consp cmd)
11114 (let ((file (convert-standard-filename file)))
11115 (save-match-data
11116 (set-match-data link-match-data)
11117 (eval cmd))))
11118 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11119 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11120 (or (not (equal old-buffer (current-buffer)))
11121 (not (equal old-pos (point))))
11122 (org-mark-ring-push old-pos old-buffer))))
11124 (defun org-file-apps-entry-match-against-dlink-p (entry)
11125 "This function returns non-nil if `entry' uses a regular
11126 expression which should be matched against the whole link by
11127 org-open-file.
11129 It assumes that is the case when the entry uses a regular
11130 expression which has at least one grouping construct and the
11131 action is either a lisp form or a command string containing
11132 '%1', i.e. using at least one subexpression match as a
11133 parameter."
11134 (let ((selector (car entry))
11135 (action (cdr entry)))
11136 (if (stringp selector)
11137 (and (> (regexp-opt-depth selector) 0)
11138 (or (and (stringp action)
11139 (string-match "%[0-9]" action))
11140 (consp action)))
11141 nil)))
11143 (defun org-default-apps ()
11144 "Return the default applications for this operating system."
11145 (cond
11146 ((eq system-type 'darwin)
11147 org-file-apps-defaults-macosx)
11148 ((eq system-type 'windows-nt)
11149 org-file-apps-defaults-windowsnt)
11150 (t org-file-apps-defaults-gnu)))
11152 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11153 "Convert extensions to regular expressions in the cars of LIST.
11154 Also, weed out any non-string entries, because the return value is used
11155 only for regexp matching.
11156 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11157 point to the symbol `emacs', indicating that the file should
11158 be opened in Emacs."
11159 (append
11160 (delq nil
11161 (mapcar (lambda (x)
11162 (if (not (stringp (car x)))
11164 (if (string-match "\\W" (car x))
11166 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11167 list))
11168 (if add-auto-mode
11169 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11171 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11172 (defun org-file-remote-p (file)
11173 "Test whether FILE specifies a location on a remote system.
11174 Return non-nil if the location is indeed remote.
11176 For example, the filename \"/user@host:/foo\" specifies a location
11177 on the system \"/user@host:\"."
11178 (cond ((fboundp 'file-remote-p)
11179 (file-remote-p file))
11180 ((fboundp 'tramp-handle-file-remote-p)
11181 (tramp-handle-file-remote-p file))
11182 ((and (boundp 'ange-ftp-name-format)
11183 (string-match (car ange-ftp-name-format) file))
11184 t)))
11187 ;;;; Refiling
11189 (defun org-get-org-file ()
11190 "Read a filename, with default directory `org-directory'."
11191 (let ((default (or org-default-notes-file remember-data-file)))
11192 (read-file-name (format "File name [%s]: " default)
11193 (file-name-as-directory org-directory)
11194 default)))
11196 (defun org-notes-order-reversed-p ()
11197 "Check if the current file should receive notes in reversed order."
11198 (cond
11199 ((not org-reverse-note-order) nil)
11200 ((eq t org-reverse-note-order) t)
11201 ((not (listp org-reverse-note-order)) nil)
11202 (t (catch 'exit
11203 (let ((all org-reverse-note-order)
11204 entry)
11205 (while (setq entry (pop all))
11206 (if (string-match (car entry) buffer-file-name)
11207 (throw 'exit (cdr entry))))
11208 nil)))))
11210 (defvar org-refile-target-table nil
11211 "The list of refile targets, created by `org-refile'.")
11213 (defvar org-agenda-new-buffers nil
11214 "Buffers created to visit agenda files.")
11216 (defvar org-refile-cache nil
11217 "Cache for refile targets.")
11219 (defvar org-refile-markers nil
11220 "All the markers used for caching refile locations.")
11222 (defun org-refile-marker (pos)
11223 "Get a new refile marker, but only if caching is in use."
11224 (if (not org-refile-use-cache)
11226 (let ((m (make-marker)))
11227 (move-marker m pos)
11228 (push m org-refile-markers)
11229 m)))
11231 (defun org-refile-cache-clear ()
11232 "Clear the refile cache and disable all the markers."
11233 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11234 (setq org-refile-markers nil)
11235 (setq org-refile-cache nil)
11236 (message "Refile cache has been cleared"))
11238 (defun org-refile-cache-check-set (set)
11239 "Check if all the markers in the cache still have live buffers."
11240 (let (marker)
11241 (catch 'exit
11242 (while (and set (setq marker (nth 3 (pop set))))
11243 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11244 (when (and marker (null (marker-buffer marker)))
11245 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11246 (sit-for 3)
11247 (throw 'exit nil)))
11248 t)))
11250 (defun org-refile-cache-put (set &rest identifiers)
11251 "Push the refile targets SET into the cache, under IDENTIFIERS."
11252 (let* ((key (sha1 (prin1-to-string identifiers)))
11253 (entry (assoc key org-refile-cache)))
11254 (if entry
11255 (setcdr entry set)
11256 (push (cons key set) org-refile-cache))))
11258 (defun org-refile-cache-get (&rest identifiers)
11259 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11260 (cond
11261 ((not org-refile-cache) nil)
11262 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11264 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11265 org-refile-cache))))
11266 (and set (org-refile-cache-check-set set) set)))))
11268 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11269 "Produce a table with refile targets."
11270 (let ((case-fold-search nil)
11271 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11272 (entries (or org-refile-targets '((nil . (:level . 1)))))
11273 targets tgs txt re files f desc descre fast-path-p level pos0)
11274 (message "Getting targets...")
11275 (with-current-buffer (or default-buffer (current-buffer))
11276 (while (setq entry (pop entries))
11277 (setq files (car entry) desc (cdr entry))
11278 (setq fast-path-p nil)
11279 (cond
11280 ((null files) (setq files (list (current-buffer))))
11281 ((eq files 'org-agenda-files)
11282 (setq files (org-agenda-files 'unrestricted)))
11283 ((and (symbolp files) (fboundp files))
11284 (setq files (funcall files)))
11285 ((and (symbolp files) (boundp files))
11286 (setq files (symbol-value files))))
11287 (if (stringp files) (setq files (list files)))
11288 (cond
11289 ((eq (car desc) :tag)
11290 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11291 ((eq (car desc) :todo)
11292 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11293 ((eq (car desc) :regexp)
11294 (setq descre (cdr desc)))
11295 ((eq (car desc) :level)
11296 (setq descre (concat "^\\*\\{" (number-to-string
11297 (if org-odd-levels-only
11298 (1- (* 2 (cdr desc)))
11299 (cdr desc)))
11300 "\\}[ \t]")))
11301 ((eq (car desc) :maxlevel)
11302 (setq fast-path-p t)
11303 (setq descre (concat "^\\*\\{1," (number-to-string
11304 (if org-odd-levels-only
11305 (1- (* 2 (cdr desc)))
11306 (cdr desc)))
11307 "\\}[ \t]")))
11308 (t (error "Bad refiling target description %s" desc)))
11309 (while (setq f (pop files))
11310 (with-current-buffer
11311 (if (bufferp f) f (org-get-agenda-file-buffer f))
11313 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11314 (progn
11315 (if (bufferp f) (setq f (buffer-file-name
11316 (buffer-base-buffer f))))
11317 (setq f (and f (expand-file-name f)))
11318 (if (eq org-refile-use-outline-path 'file)
11319 (push (list (file-name-nondirectory f) f nil nil) tgs))
11320 (save-excursion
11321 (save-restriction
11322 (widen)
11323 (goto-char (point-min))
11324 (while (re-search-forward descre nil t)
11325 (goto-char (setq pos0 (point-at-bol)))
11326 (catch 'next
11327 (when org-refile-target-verify-function
11328 (save-match-data
11329 (or (funcall org-refile-target-verify-function)
11330 (throw 'next t))))
11331 (when (and (looking-at org-complex-heading-regexp)
11332 (not (member (match-string 4) excluded-entries))
11333 (match-string 4))
11334 (setq level (org-reduced-level
11335 (- (match-end 1) (match-beginning 1)))
11336 txt (org-link-display-format (match-string 4))
11337 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11338 re (format org-complex-heading-regexp-format
11339 (regexp-quote (match-string 4))))
11340 (when org-refile-use-outline-path
11341 (setq txt (mapconcat
11342 'org-protect-slash
11343 (append
11344 (if (eq org-refile-use-outline-path
11345 'file)
11346 (list (file-name-nondirectory
11347 (buffer-file-name
11348 (buffer-base-buffer))))
11349 (if (eq org-refile-use-outline-path
11350 'full-file-path)
11351 (list (buffer-file-name
11352 (buffer-base-buffer)))))
11353 (org-get-outline-path fast-path-p
11354 level txt)
11355 (list txt))
11356 "/")))
11357 (push (list txt f re (org-refile-marker (point)))
11358 tgs)))
11359 (when (= (point) pos0)
11360 ;; verification function has not moved point
11361 (goto-char (point-at-eol))))))))
11362 (when org-refile-use-cache
11363 (org-refile-cache-put tgs (buffer-file-name) descre))
11364 (setq targets (append tgs targets))))))
11365 (message "Getting targets...done")
11366 (nreverse targets)))
11368 (defun org-protect-slash (s)
11369 (while (string-match "/" s)
11370 (setq s (replace-match "\\" t t s)))
11373 (defvar org-olpa (make-vector 20 nil))
11375 (defun org-get-outline-path (&optional fastp level heading)
11376 "Return the outline path to the current entry, as a list.
11378 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11379 routine which makes outline path derivations for an entire file,
11380 avoiding backtracing. Refile target collection makes use of that."
11381 (if fastp
11382 (progn
11383 (if (> level 19)
11384 (error "Outline path failure, more than 19 levels"))
11385 (loop for i from level upto 19 do
11386 (aset org-olpa i nil))
11387 (prog1
11388 (delq nil (append org-olpa nil))
11389 (aset org-olpa level heading)))
11390 (let (rtn case-fold-search)
11391 (save-excursion
11392 (save-restriction
11393 (widen)
11394 (while (org-up-heading-safe)
11395 (when (looking-at org-complex-heading-regexp)
11396 (push (org-trim
11397 (replace-regexp-in-string
11398 ;; Remove statistical/checkboxes cookies
11399 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11400 (org-match-string-no-properties 4)))
11401 rtn)))
11402 rtn)))))
11404 (defun org-format-outline-path (path &optional width prefix separator)
11405 "Format the outline path PATH for display.
11406 WIDTH is the maximum number of characters that is available.
11407 PREFIX is a prefix to be included in the returned string,
11408 such as the file name.
11409 SEPARATOR is inserted between the different parts of the path,
11410 the default is \"/\"."
11411 (setq width (or width 79))
11412 (if prefix (setq width (- width (length prefix))))
11413 (if (not path)
11414 (or prefix "")
11415 (let* ((nsteps (length path))
11416 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11417 (maxwidth (if (<= total-width width)
11418 10000 ;; everything fits
11419 ;; we need to shorten the level headings
11420 (/ (- width nsteps) nsteps)))
11421 (org-odd-levels-only nil)
11422 (n 0)
11423 (total (1+ (length prefix))))
11424 (setq maxwidth (max maxwidth 10))
11425 (concat prefix
11426 (if prefix (or separator "/"))
11427 (mapconcat
11428 (lambda (h)
11429 (setq n (1+ n))
11430 (if (and (= n nsteps) (< maxwidth 10000))
11431 (setq maxwidth (- total-width total)))
11432 (if (< (length h) maxwidth)
11433 (progn (setq total (+ total (length h) 1)) h)
11434 (setq h (substring h 0 (- maxwidth 2))
11435 total (+ total maxwidth 1))
11436 (if (string-match "[ \t]+\\'" h)
11437 (setq h (substring h 0 (match-beginning 0))))
11438 (setq h (concat h "..")))
11439 (org-add-props h nil 'face
11440 (nth (% (1- n) org-n-level-faces)
11441 org-level-faces))
11443 path (or separator "/"))))))
11445 (defun org-display-outline-path (&optional file current separator just-return-string)
11446 "Display the current outline path in the echo area.
11448 If FILE is non-nil, prepend the output with the file name.
11449 If CURRENT is non-nil, append the current heading to the output.
11450 SEPARATOR is passed through to `org-format-outline-path'. It separates
11451 the different parts of the path and defaults to \"/\".
11452 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11453 (interactive "P")
11454 (let* (case-fold-search
11455 (bfn (buffer-file-name (buffer-base-buffer)))
11456 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11457 res)
11458 (if current (setq path (append path
11459 (save-excursion
11460 (org-back-to-heading t)
11461 (if (looking-at org-complex-heading-regexp)
11462 (list (match-string 4)))))))
11463 (setq res
11464 (org-format-outline-path
11465 path
11466 (1- (frame-width))
11467 (and file bfn (concat (file-name-nondirectory bfn) separator))
11468 separator))
11469 (if just-return-string
11470 (org-no-properties res)
11471 (org-unlogged-message "%s" res))))
11473 (defvar org-refile-history nil
11474 "History for refiling operations.")
11476 (defvar org-after-refile-insert-hook nil
11477 "Hook run after `org-refile' has inserted its stuff at the new location.
11478 Note that this is still *before* the stuff will be removed from
11479 the *old* location.")
11481 (defvar org-capture-last-stored-marker)
11482 (defvar org-refile-keep nil
11483 "Non-nil means `org-refile' will copy instead of refile.")
11485 (defun org-copy ()
11486 "Like `org-refile', but copy."
11487 (interactive)
11488 (let ((org-refile-keep t))
11489 (funcall 'org-refile nil nil nil "Copy")))
11491 (defun org-refile (&optional goto default-buffer rfloc msg)
11492 "Move the entry or entries at point to another heading.
11493 The list of target headings is compiled using the information in
11494 `org-refile-targets', which see.
11496 At the target location, the entry is filed as a subitem of the target
11497 heading. Depending on `org-reverse-note-order', the new subitem will
11498 either be the first or the last subitem.
11500 If there is an active region, all entries in that region will be moved.
11501 However, the region must fulfill the requirement that the first heading
11502 is the first one sets the top-level of the moved text - at most siblings
11503 below it are allowed.
11505 With prefix arg GOTO, the command will only visit the target location
11506 and not actually move anything.
11508 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11509 go to the location where the last refiling operation has put the subtree.
11511 With a numeric prefix argument of `2', refile to the running clock.
11513 With a numeric prefix argument of `3', emulate `org-refile-keep'
11514 being set to `t' and copy to the target location, don't move it.
11515 Beware that keeping refiled entries may result in duplicated ID
11516 properties.
11518 RFLOC can be a refile location obtained in a different way.
11520 MSG is a string to replace \"Refile\" in the default prompt with
11521 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11523 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11525 If you are using target caching (see `org-refile-use-cache'),
11526 you have to clear the target cache in order to find new targets.
11527 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11528 prefix argument (`C-u C-u C-u C-c C-w')."
11530 (interactive "P")
11531 (if (member goto '(0 (64)))
11532 (org-refile-cache-clear)
11533 (let* ((actionmsg (cond (msg msg)
11534 ((equal goto 3) "Refile (and keep)")
11535 (t "Refile")))
11536 (cbuf (current-buffer))
11537 (regionp (org-region-active-p))
11538 (region-start (and regionp (region-beginning)))
11539 (region-end (and regionp (region-end)))
11540 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11541 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11542 pos it nbuf file re level reversed)
11543 (setq last-command nil)
11544 (when regionp
11545 (goto-char region-start)
11546 (or (bolp) (goto-char (point-at-bol)))
11547 (setq region-start (point))
11548 (unless (or (org-kill-is-subtree-p
11549 (buffer-substring region-start region-end))
11550 (prog1 org-refile-active-region-within-subtree
11551 (let ((s (point-at-eol)))
11552 (org-toggle-heading)
11553 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11554 (user-error "The region is not a (sequence of) subtree(s)")))
11555 (if (equal goto '(16))
11556 (org-refile-goto-last-stored)
11557 (when (or
11558 (and (equal goto 2)
11559 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11560 (prog1
11561 (setq it (list (or org-clock-heading "running clock")
11562 (buffer-file-name
11563 (marker-buffer org-clock-hd-marker))
11565 (marker-position org-clock-hd-marker)))
11566 (setq goto nil)))
11567 (setq it (or rfloc
11568 (let (heading-text)
11569 (save-excursion
11570 (unless (or goto (listp goto))
11571 (org-back-to-heading t)
11572 (setq heading-text
11573 (nth 4 (org-heading-components))))
11575 (org-refile-get-location
11576 (cond ((or goto (listp goto)) "Goto")
11577 (regionp (concat actionmsg " region to"))
11578 (t (concat actionmsg " subtree \""
11579 heading-text "\" to")))
11580 default-buffer
11581 (and (not (equal '(4) goto))
11582 org-refile-allow-creating-parent-nodes)
11583 goto))))))
11584 (setq file (nth 1 it)
11585 re (nth 2 it)
11586 pos (nth 3 it))
11587 (if (and (not goto)
11589 (equal (buffer-file-name) file)
11590 (if regionp
11591 (and (>= pos region-start)
11592 (<= pos region-end))
11593 (and (>= pos (point))
11594 (< pos (save-excursion
11595 (org-end-of-subtree t t))))))
11596 (error "Cannot refile to position inside the tree or region"))
11598 (setq nbuf (or (find-buffer-visiting file)
11599 (find-file-noselect file)))
11600 (if (and goto (not (equal goto 3)))
11601 (progn
11602 (org-pop-to-buffer-same-window nbuf)
11603 (goto-char pos)
11604 (org-show-context 'org-goto))
11605 (if regionp
11606 (progn
11607 (org-kill-new (buffer-substring region-start region-end))
11608 (org-save-markers-in-region region-start region-end))
11609 (org-copy-subtree 1 nil t))
11610 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11611 (find-file-noselect file)))
11612 (setq reversed (org-notes-order-reversed-p))
11613 (save-excursion
11614 (save-restriction
11615 (widen)
11616 (if pos
11617 (progn
11618 (goto-char pos)
11619 (looking-at org-outline-regexp)
11620 (setq level (org-get-valid-level (funcall outline-level) 1))
11621 (goto-char
11622 (if reversed
11623 (or (outline-next-heading) (point-max))
11624 (or (save-excursion (org-get-next-sibling))
11625 (org-end-of-subtree t t)
11626 (point-max)))))
11627 (setq level 1)
11628 (if (not reversed)
11629 (goto-char (point-max))
11630 (goto-char (point-min))
11631 (or (outline-next-heading) (goto-char (point-max)))))
11632 (if (not (bolp)) (newline))
11633 (org-paste-subtree level)
11634 (when org-log-refile
11635 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11636 (unless (eq org-log-refile 'note)
11637 (save-excursion (org-add-log-note))))
11638 (and org-auto-align-tags
11639 (let ((org-loop-over-headlines-in-active-region nil))
11640 (org-set-tags nil t)))
11641 (let ((bookmark-name (plist-get org-bookmark-names-plist
11642 :last-refile)))
11643 (when bookmark-name
11644 (with-demoted-errors
11645 (bookmark-set bookmark-name))))
11646 ;; If we are refiling for capture, make sure that the
11647 ;; last-capture pointers point here
11648 (when (org-bound-and-true-p org-refile-for-capture)
11649 (let ((bookmark-name (plist-get org-bookmark-names-plist
11650 :last-capture-marker)))
11651 (when bookmark-name
11652 (with-demoted-errors
11653 (bookmark-set bookmark-name))))
11654 (move-marker org-capture-last-stored-marker (point)))
11655 (if (fboundp 'deactivate-mark) (deactivate-mark))
11656 (run-hooks 'org-after-refile-insert-hook))))
11657 (unless org-refile-keep
11658 (if regionp
11659 (delete-region (point) (+ (point) (- region-end region-start)))
11660 (delete-region
11661 (and (org-back-to-heading t) (point))
11662 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11663 (when (featurep 'org-inlinetask)
11664 (org-inlinetask-remove-END-maybe))
11665 (setq org-markers-to-move nil)
11666 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11668 (defun org-refile-goto-last-stored ()
11669 "Go to the location where the last refile was stored."
11670 (interactive)
11671 (bookmark-jump "org-refile-last-stored")
11672 (message "This is the location of the last refile"))
11674 (defun org-refile--get-location (refloc tbl)
11675 "When user refile to REFLOC, find the associated target in TBL.
11676 Also check `org-refile-target-table'."
11677 (car (delq
11679 (mapcar
11680 (lambda (r) (or (assoc r tbl)
11681 (assoc r org-refile-target-table)))
11682 (list (replace-regexp-in-string "/$" "" refloc)
11683 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11685 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11686 no-exclude)
11687 "Prompt the user for a refile location, using PROMPT.
11688 PROMPT should not be suffixed with a colon and a space, because
11689 this function appends the default value from
11690 `org-refile-history' automatically, if that is not empty.
11691 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11692 this is used for the GOTO interface."
11693 (let ((org-refile-targets org-refile-targets)
11694 (org-refile-use-outline-path org-refile-use-outline-path)
11695 excluded-entries)
11696 (when (and (derived-mode-p 'org-mode)
11697 (not org-refile-use-cache)
11698 (not no-exclude))
11699 (org-map-tree
11700 (lambda()
11701 (setq excluded-entries
11702 (append excluded-entries (list (org-get-heading t t)))))))
11703 (setq org-refile-target-table
11704 (org-refile-get-targets default-buffer excluded-entries)))
11705 (unless org-refile-target-table
11706 (user-error "No refile targets"))
11707 (let* ((cbuf (current-buffer))
11708 (partial-completion-mode nil)
11709 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11710 (cfunc (if (and org-refile-use-outline-path
11711 org-outline-path-complete-in-steps)
11712 'org-olpath-completing-read
11713 'org-icompleting-read))
11714 (extra (if org-refile-use-outline-path "/" ""))
11715 (cbnex (concat (buffer-name) extra))
11716 (filename (and cfn (expand-file-name cfn)))
11717 (tbl (mapcar
11718 (lambda (x)
11719 (if (and (not (member org-refile-use-outline-path
11720 '(file full-file-path)))
11721 (not (equal filename (nth 1 x))))
11722 (cons (concat (car x) extra " ("
11723 (file-name-nondirectory (nth 1 x)) ")")
11724 (cdr x))
11725 (cons (concat (car x) extra) (cdr x))))
11726 org-refile-target-table))
11727 (completion-ignore-case t)
11728 cdef
11729 (prompt (concat prompt
11730 (or (and (car org-refile-history)
11731 (concat " (default " (car org-refile-history) ")"))
11732 (and (assoc cbnex tbl) (setq cdef cbnex)
11733 (concat " (default " cbnex ")"))) ": "))
11734 pa answ parent-target child parent old-hist)
11735 (setq old-hist org-refile-history)
11736 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11737 nil 'org-refile-history (or cdef (car org-refile-history))))
11738 (if (setq pa (org-refile--get-location answ tbl))
11739 (progn
11740 (org-refile-check-position pa)
11741 (when (or (not org-refile-history)
11742 (not (eq old-hist org-refile-history))
11743 (not (equal (car pa) (car org-refile-history))))
11744 (setq org-refile-history
11745 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11746 org-refile-history
11747 (cdr org-refile-history))))
11748 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11749 (pop org-refile-history)))
11751 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11752 (progn
11753 (setq parent (match-string 1 answ)
11754 child (match-string 2 answ))
11755 (setq parent-target (org-refile--get-location parent tbl))
11756 (when (and parent-target
11757 (or (eq new-nodes t)
11758 (and (eq new-nodes 'confirm)
11759 (y-or-n-p (format "Create new node \"%s\"? "
11760 child)))))
11761 (org-refile-new-child parent-target child)))
11762 (user-error "Invalid target location")))))
11764 (declare-function org-string-nw-p "org-macs" (s))
11765 (defun org-refile-check-position (refile-pointer)
11766 "Check if the refile pointer matches the headline to which it points."
11767 (let* ((file (nth 1 refile-pointer))
11768 (re (nth 2 refile-pointer))
11769 (pos (nth 3 refile-pointer))
11770 buffer)
11771 (if (and (not (markerp pos)) (not file))
11772 (user-error "Please save the buffer to a file before refiling")
11773 (when (org-string-nw-p re)
11774 (setq buffer (if (markerp pos)
11775 (marker-buffer pos)
11776 (or (find-buffer-visiting file)
11777 (find-file-noselect file))))
11778 (with-current-buffer buffer
11779 (save-excursion
11780 (save-restriction
11781 (widen)
11782 (goto-char pos)
11783 (beginning-of-line 1)
11784 (unless (org-looking-at-p re)
11785 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11787 (defun org-refile-new-child (parent-target child)
11788 "Use refile target PARENT-TARGET to add new CHILD below it."
11789 (unless parent-target
11790 (error "Cannot find parent for new node"))
11791 (let ((file (nth 1 parent-target))
11792 (pos (nth 3 parent-target))
11793 level)
11794 (with-current-buffer (or (find-buffer-visiting file)
11795 (find-file-noselect file))
11796 (save-excursion
11797 (save-restriction
11798 (widen)
11799 (if pos
11800 (goto-char pos)
11801 (goto-char (point-max))
11802 (if (not (bolp)) (newline)))
11803 (when (looking-at org-outline-regexp)
11804 (setq level (funcall outline-level))
11805 (org-end-of-subtree t t))
11806 (org-back-over-empty-lines)
11807 (insert "\n" (make-string
11808 (if pos (org-get-valid-level level 1) 1) ?*)
11809 " " child "\n")
11810 (beginning-of-line 0)
11811 (list (concat (car parent-target) "/" child) file "" (point)))))))
11813 (defun org-olpath-completing-read (prompt collection &rest args)
11814 "Read an outline path like a file name."
11815 (let ((thetable collection)
11816 (org-completion-use-ido nil) ; does not work with ido.
11817 (org-completion-use-iswitchb nil)) ; or iswitchb
11818 (apply
11819 'org-icompleting-read prompt
11820 (lambda (string predicate &optional flag)
11821 (let (rtn r f (l (length string)))
11822 (cond
11823 ((eq flag nil)
11824 ;; try completion
11825 (try-completion string thetable))
11826 ((eq flag t)
11827 ;; all-completions
11828 (setq rtn (all-completions string thetable predicate))
11829 (mapcar
11830 (lambda (x)
11831 (setq r (substring x l))
11832 (if (string-match " ([^)]*)$" x)
11833 (setq f (match-string 0 x))
11834 (setq f ""))
11835 (if (string-match "/" r)
11836 (concat string (substring r 0 (match-end 0)) f)
11838 rtn))
11839 ((eq flag 'lambda)
11840 ;; exact match?
11841 (assoc string thetable)))))
11842 args)))
11844 ;;;; Dynamic blocks
11846 (defun org-find-dblock (name)
11847 "Find the first dynamic block with name NAME in the buffer.
11848 If not found, stay at current position and return nil."
11849 (let ((case-fold-search t) pos)
11850 (save-excursion
11851 (goto-char (point-min))
11852 (setq pos (and (re-search-forward
11853 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11854 (match-beginning 0))))
11855 (if pos (goto-char pos))
11856 pos))
11858 (defconst org-dblock-start-re
11859 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11860 "Matches the start line of a dynamic block, with parameters.")
11862 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11863 "Matches the end of a dynamic block.")
11865 (defun org-create-dblock (plist)
11866 "Create a dynamic block section, with parameters taken from PLIST.
11867 PLIST must contain a :name entry which is used as name of the block."
11868 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11869 (end-of-line 1)
11870 (newline))
11871 (let ((col (current-column))
11872 (name (plist-get plist :name)))
11873 (insert "#+BEGIN: " name)
11874 (while plist
11875 (if (eq (car plist) :name)
11876 (setq plist (cddr plist))
11877 (insert " " (prin1-to-string (pop plist)))))
11878 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11879 (beginning-of-line -2)))
11881 (defun org-prepare-dblock ()
11882 "Prepare dynamic block for refresh.
11883 This empties the block, puts the cursor at the insert position and returns
11884 the property list including an extra property :name with the block name."
11885 (unless (looking-at org-dblock-start-re)
11886 (user-error "Not at a dynamic block"))
11887 (let* ((begdel (1+ (match-end 0)))
11888 (name (org-no-properties (match-string 1)))
11889 (params (append (list :name name)
11890 (read (concat "(" (match-string 3) ")")))))
11891 (save-excursion
11892 (beginning-of-line 1)
11893 (skip-chars-forward " \t")
11894 (setq params (plist-put params :indentation-column (current-column))))
11895 (unless (re-search-forward org-dblock-end-re nil t)
11896 (error "Dynamic block not terminated"))
11897 (setq params
11898 (append params
11899 (list :content (buffer-substring
11900 begdel (match-beginning 0)))))
11901 (delete-region begdel (match-beginning 0))
11902 (goto-char begdel)
11903 (open-line 1)
11904 params))
11906 (defun org-map-dblocks (&optional command)
11907 "Apply COMMAND to all dynamic blocks in the current buffer.
11908 If COMMAND is not given, use `org-update-dblock'."
11909 (let ((cmd (or command 'org-update-dblock)))
11910 (save-excursion
11911 (goto-char (point-min))
11912 (while (re-search-forward org-dblock-start-re nil t)
11913 (goto-char (match-beginning 0))
11914 (save-excursion
11915 (condition-case nil
11916 (funcall cmd)
11917 (error (message "Error during update of dynamic block"))))
11918 (unless (re-search-forward org-dblock-end-re nil t)
11919 (error "Dynamic block not terminated"))))))
11921 (defun org-dblock-update (&optional arg)
11922 "User command for updating dynamic blocks.
11923 Update the dynamic block at point. With prefix ARG, update all dynamic
11924 blocks in the buffer."
11925 (interactive "P")
11926 (if arg
11927 (org-update-all-dblocks)
11928 (or (looking-at org-dblock-start-re)
11929 (org-beginning-of-dblock))
11930 (org-update-dblock)))
11932 (defun org-update-dblock ()
11933 "Update the dynamic block at point.
11934 This means to empty the block, parse for parameters and then call
11935 the correct writing function."
11936 (interactive)
11937 (save-excursion
11938 (let* ((win (selected-window))
11939 (pos (point))
11940 (line (org-current-line))
11941 (params (org-prepare-dblock))
11942 (name (plist-get params :name))
11943 (indent (plist-get params :indentation-column))
11944 (cmd (intern (concat "org-dblock-write:" name))))
11945 (message "Updating dynamic block `%s' at line %d..." name line)
11946 (funcall cmd params)
11947 (message "Updating dynamic block `%s' at line %d...done" name line)
11948 (goto-char pos)
11949 (when (and indent (> indent 0))
11950 (setq indent (make-string indent ?\ ))
11951 (save-excursion
11952 (select-window win)
11953 (org-beginning-of-dblock)
11954 (forward-line 1)
11955 (while (not (looking-at org-dblock-end-re))
11956 (insert indent)
11957 (beginning-of-line 2))
11958 (when (looking-at org-dblock-end-re)
11959 (and (looking-at "[ \t]+")
11960 (replace-match ""))
11961 (insert indent)))))))
11963 (defun org-beginning-of-dblock ()
11964 "Find the beginning of the dynamic block at point.
11965 Error if there is no such block at point."
11966 (let ((pos (point))
11967 beg)
11968 (end-of-line 1)
11969 (if (and (re-search-backward org-dblock-start-re nil t)
11970 (setq beg (match-beginning 0))
11971 (re-search-forward org-dblock-end-re nil t)
11972 (> (match-end 0) pos))
11973 (goto-char beg)
11974 (goto-char pos)
11975 (error "Not in a dynamic block"))))
11977 (defun org-update-all-dblocks ()
11978 "Update all dynamic blocks in the buffer.
11979 This function can be used in a hook."
11980 (interactive)
11981 (when (derived-mode-p 'org-mode)
11982 (org-map-dblocks 'org-update-dblock)))
11985 ;;;; Completion
11987 (declare-function org-export-backend-name "org-export" (cl-x))
11988 (declare-function org-export-backend-options "org-export" (cl-x))
11989 (defun org-get-export-keywords ()
11990 "Return a list of all currently understood export keywords.
11991 Export keywords include options, block names, attributes and
11992 keywords relative to each registered export back-end."
11993 (let (keywords)
11994 (dolist (backend
11995 (org-bound-and-true-p org-export--registered-backends)
11996 (delq nil keywords))
11997 ;; Back-end name (for keywords, like #+LATEX:)
11998 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11999 (dolist (option-entry (org-export-backend-options backend))
12000 ;; Back-end options.
12001 (push (nth 1 option-entry) keywords)))))
12003 (defconst org-options-keywords
12004 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12005 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12006 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12007 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12008 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12010 (defcustom org-structure-template-alist
12011 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12012 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12013 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12014 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12015 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12016 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12017 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12018 "<literal style=\"latex\">\n?\n</literal>")
12019 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12020 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12021 "<literal style=\"html\">\n?\n</literal>")
12022 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12023 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12024 ("A" "#+ASCII: " "")
12025 ("i" "#+INDEX: ?" "#+INDEX: ?")
12026 ("I" "#+INCLUDE: %file ?"
12027 "<include file=%file markup=\"?\">"))
12028 "Structure completion elements.
12029 This is a list of abbreviation keys and values. The value gets inserted
12030 if you type `<' followed by the key and then press the completion key,
12031 usually `M-TAB'. %file will be replaced by a file name after prompting
12032 for the file using completion. The cursor will be placed at the position
12033 of the `?` in the template.
12034 There are two templates for each key, the first uses the original Org syntax,
12035 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12036 the default when the /org-mtags.el/ module has been loaded. See also the
12037 variable `org-mtags-prefer-muse-templates'."
12038 :group 'org-completion
12039 :type '(repeat
12040 (list
12041 (string :tag "Key")
12042 (string :tag "Template")
12043 (string :tag "Muse Template"))))
12045 (defun org-try-structure-completion ()
12046 "Try to complete a structure template before point.
12047 This looks for strings like \"<e\" on an otherwise empty line and
12048 expands them."
12049 (let ((l (buffer-substring (point-at-bol) (point)))
12051 (when (and (looking-at "[ \t]*$")
12052 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12053 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12054 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12055 (match-beginning 1)) a)
12056 t)))
12058 (defun org-complete-expand-structure-template (start cell)
12059 "Expand a structure template."
12060 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12061 (rpl (nth (if musep 2 1) cell))
12062 (ind ""))
12063 (delete-region start (point))
12064 (when (string-match "\\`#\\+" rpl)
12065 (cond
12066 ((bolp))
12067 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12068 (setq ind (buffer-substring (point-at-bol) (point))))
12069 (t (newline))))
12070 (setq start (point))
12071 (if (string-match "%file" rpl)
12072 (setq rpl (replace-match
12073 (concat
12074 "\""
12075 (save-match-data
12076 (abbreviate-file-name (read-file-name "Include file: ")))
12077 "\"")
12078 t t rpl)))
12079 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12080 (concat "\n" ind)))
12081 (insert rpl)
12082 (if (re-search-backward "\\?" start t) (delete-char 1))))
12084 ;;;; TODO, DEADLINE, Comments
12086 (defun org-toggle-comment ()
12087 "Change the COMMENT state of an entry."
12088 (interactive)
12089 (save-excursion
12090 (org-back-to-heading)
12091 (let (case-fold-search)
12092 (cond
12093 ((looking-at (format org-heading-keyword-regexp-format
12094 org-comment-string))
12095 (goto-char (match-end 1))
12096 (looking-at (concat " +" org-comment-string))
12097 (replace-match "" t t)
12098 (when (eolp) (insert " ")))
12099 ((looking-at org-outline-regexp)
12100 (goto-char (match-end 0))
12101 (insert org-comment-string " "))))))
12103 (defvar org-last-todo-state-is-todo nil
12104 "This is non-nil when the last TODO state change led to a TODO state.
12105 If the last change removed the TODO tag or switched to DONE, then
12106 this is nil.")
12108 (defvar org-setting-tags nil) ; dynamically skipped
12110 (defvar org-todo-setup-filter-hook nil
12111 "Hook for functions that pre-filter todo specs.
12112 Each function takes a todo spec and returns either nil or the spec
12113 transformed into canonical form." )
12115 (defvar org-todo-get-default-hook nil
12116 "Hook for functions that get a default item for todo.
12117 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12118 nil or a string to be used for the todo mark." )
12120 (defvar org-agenda-headline-snapshot-before-repeat)
12122 (defun org-current-effective-time ()
12123 "Return current time adjusted for `org-extend-today-until' variable."
12124 (let* ((ct (org-current-time))
12125 (dct (decode-time ct))
12126 (ct1
12127 (cond
12128 (org-use-last-clock-out-time-as-effective-time
12129 (or (org-clock-get-last-clock-out-time) ct))
12130 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12131 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12132 (t ct))))
12133 ct1))
12135 (defun org-todo-yesterday (&optional arg)
12136 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12137 (interactive "P")
12138 (if (eq major-mode 'org-agenda-mode)
12139 (apply 'org-agenda-todo-yesterday arg)
12140 (let* ((hour (third (decode-time
12141 (org-current-time))))
12142 (org-extend-today-until (1+ hour)))
12143 (org-todo arg))))
12145 (defvar org-block-entry-blocking ""
12146 "First entry preventing the TODO state change.")
12148 (defun org-todo (&optional arg)
12149 "Change the TODO state of an item.
12150 The state of an item is given by a keyword at the start of the heading,
12151 like
12152 *** TODO Write paper
12153 *** DONE Call mom
12155 The different keywords are specified in the variable `org-todo-keywords'.
12156 By default the available states are \"TODO\" and \"DONE\".
12157 So for this example: when the item starts with TODO, it is changed to DONE.
12158 When it starts with DONE, the DONE is removed. And when neither TODO nor
12159 DONE are present, add TODO at the beginning of the heading.
12161 With \\[universal-argument] prefix arg, use completion to determine the new \
12162 state.
12163 With numeric prefix arg, switch to that state.
12164 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12165 keywords (nextset).
12166 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12167 With a numeric prefix arg of 0, inhibit note taking for the change.
12169 For calling through lisp, arg is also interpreted in the following way:
12170 'none -> empty state
12171 \"\"(empty string) -> switch to empty state
12172 'done -> switch to DONE
12173 'nextset -> switch to the next set of keywords
12174 'previousset -> switch to the previous set of keywords
12175 \"WAITING\" -> switch to the specified keyword, but only if it
12176 really is a member of `org-todo-keywords'."
12177 (interactive "P")
12178 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12179 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12180 'region-start-level 'region))
12181 org-loop-over-headlines-in-active-region)
12182 (org-map-entries
12183 `(org-todo ,arg)
12184 org-loop-over-headlines-in-active-region
12185 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12186 (if (equal arg '(16)) (setq arg 'nextset))
12187 (let ((org-blocker-hook org-blocker-hook)
12188 commentp
12189 case-fold-search)
12190 (when (equal arg '(64))
12191 (setq arg nil org-blocker-hook nil))
12192 (when (and org-blocker-hook
12193 (or org-inhibit-blocking
12194 (org-entry-get nil "NOBLOCKING")))
12195 (setq org-blocker-hook nil))
12196 (save-excursion
12197 (catch 'exit
12198 (org-back-to-heading t)
12199 (when (looking-at (concat "^\\*+ " org-comment-string))
12200 (org-toggle-comment)
12201 (setq commentp t))
12202 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12203 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12204 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12205 (let* ((match-data (match-data))
12206 (startpos (point-at-bol))
12207 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12208 (org-log-done org-log-done)
12209 (org-log-repeat org-log-repeat)
12210 (org-todo-log-states org-todo-log-states)
12211 (org-inhibit-logging
12212 (if (equal arg 0)
12213 (progn (setq arg nil) 'note) org-inhibit-logging))
12214 (this (match-string 1))
12215 (hl-pos (match-beginning 0))
12216 (head (org-get-todo-sequence-head this))
12217 (ass (assoc head org-todo-kwd-alist))
12218 (interpret (nth 1 ass))
12219 (done-word (nth 3 ass))
12220 (final-done-word (nth 4 ass))
12221 (org-last-state (or this ""))
12222 (completion-ignore-case t)
12223 (member (member this org-todo-keywords-1))
12224 (tail (cdr member))
12225 (org-state (cond
12226 ((and org-todo-key-trigger
12227 (or (and (equal arg '(4))
12228 (eq org-use-fast-todo-selection 'prefix))
12229 (and (not arg) org-use-fast-todo-selection
12230 (not (eq org-use-fast-todo-selection
12231 'prefix)))))
12232 ;; Use fast selection
12233 (org-fast-todo-selection))
12234 ((and (equal arg '(4))
12235 (or (not org-use-fast-todo-selection)
12236 (not org-todo-key-trigger)))
12237 ;; Read a state with completion
12238 (org-icompleting-read
12239 "State: " (mapcar 'list org-todo-keywords-1)
12240 nil t))
12241 ((eq arg 'right)
12242 (if this
12243 (if tail (car tail) nil)
12244 (car org-todo-keywords-1)))
12245 ((eq arg 'left)
12246 (if (equal member org-todo-keywords-1)
12248 (if this
12249 (nth (- (length org-todo-keywords-1)
12250 (length tail) 2)
12251 org-todo-keywords-1)
12252 (org-last org-todo-keywords-1))))
12253 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12254 (setq arg nil))) ; hack to fall back to cycling
12255 (arg
12256 ;; user or caller requests a specific state
12257 (cond
12258 ((equal arg "") nil)
12259 ((eq arg 'none) nil)
12260 ((eq arg 'done) (or done-word (car org-done-keywords)))
12261 ((eq arg 'nextset)
12262 (or (car (cdr (member head org-todo-heads)))
12263 (car org-todo-heads)))
12264 ((eq arg 'previousset)
12265 (let ((org-todo-heads (reverse org-todo-heads)))
12266 (or (car (cdr (member head org-todo-heads)))
12267 (car org-todo-heads))))
12268 ((car (member arg org-todo-keywords-1)))
12269 ((stringp arg)
12270 (user-error "State `%s' not valid in this file" arg))
12271 ((nth (1- (prefix-numeric-value arg))
12272 org-todo-keywords-1))))
12273 ((null member) (or head (car org-todo-keywords-1)))
12274 ((equal this final-done-word) nil) ;; -> make empty
12275 ((null tail) nil) ;; -> first entry
12276 ((memq interpret '(type priority))
12277 (if (eq this-command last-command)
12278 (car tail)
12279 (if (> (length tail) 0)
12280 (or done-word (car org-done-keywords))
12281 nil)))
12283 (car tail))))
12284 (org-state (or
12285 (run-hook-with-args-until-success
12286 'org-todo-get-default-hook org-state org-last-state)
12287 org-state))
12288 (next (if org-state (concat " " org-state " ") " "))
12289 (change-plist (list :type 'todo-state-change :from this :to org-state
12290 :position startpos))
12291 dolog now-done-p)
12292 (when org-blocker-hook
12293 (setq org-last-todo-state-is-todo
12294 (not (member this org-done-keywords)))
12295 (unless (save-excursion
12296 (save-match-data
12297 (org-with-wide-buffer
12298 (run-hook-with-args-until-failure
12299 'org-blocker-hook change-plist))))
12300 (if (org-called-interactively-p 'interactive)
12301 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12302 this org-state org-block-entry-blocking)
12303 ;; fail silently
12304 (message "TODO state change from %s to %s blocked (by \"%s\")"
12305 this org-state org-block-entry-blocking)
12306 (throw 'exit nil))))
12307 (store-match-data match-data)
12308 (replace-match next t t)
12309 (unless (pos-visible-in-window-p hl-pos)
12310 (message "TODO state changed to %s" (org-trim next)))
12311 (unless head
12312 (setq head (org-get-todo-sequence-head org-state)
12313 ass (assoc head org-todo-kwd-alist)
12314 interpret (nth 1 ass)
12315 done-word (nth 3 ass)
12316 final-done-word (nth 4 ass)))
12317 (when (memq arg '(nextset previousset))
12318 (message "Keyword-Set %d/%d: %s"
12319 (- (length org-todo-sets) -1
12320 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12321 (length org-todo-sets)
12322 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12323 (setq org-last-todo-state-is-todo
12324 (not (member org-state org-done-keywords)))
12325 (setq now-done-p (and (member org-state org-done-keywords)
12326 (not (member this org-done-keywords))))
12327 (and logging (org-local-logging logging))
12328 (when (and (or org-todo-log-states org-log-done)
12329 (not (eq org-inhibit-logging t))
12330 (not (memq arg '(nextset previousset))))
12331 ;; we need to look at recording a time and note
12332 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12333 (nth 2 (assoc this org-todo-log-states))))
12334 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12335 (setq dolog 'time))
12336 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12337 (and org-state
12338 (member org-state org-not-done-keywords)
12339 (not (member this org-not-done-keywords))))
12340 ;; This is now a todo state and was not one before
12341 ;; If there was a CLOSED time stamp, get rid of it.
12342 (org-add-planning-info nil nil 'closed))
12343 (when (and now-done-p org-log-done)
12344 ;; It is now done, and it was not done before
12345 (org-add-planning-info 'closed (org-current-effective-time))
12346 (if (and (not dolog) (eq 'note org-log-done))
12347 (org-add-log-setup 'done org-state this 'findpos 'note)))
12348 (when (and org-state dolog)
12349 ;; This is a non-nil state, and we need to log it
12350 (org-add-log-setup 'state org-state this 'findpos dolog)))
12351 ;; Fixup tag positioning
12352 (org-todo-trigger-tag-changes org-state)
12353 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12354 (when org-provide-todo-statistics
12355 (org-update-parent-todo-statistics))
12356 (run-hooks 'org-after-todo-state-change-hook)
12357 (if (and arg (not (member org-state org-done-keywords)))
12358 (setq head (org-get-todo-sequence-head org-state)))
12359 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12360 ;; Do we need to trigger a repeat?
12361 (when now-done-p
12362 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12363 ;; This is for the agenda, take a snapshot of the headline.
12364 (save-match-data
12365 (setq org-agenda-headline-snapshot-before-repeat
12366 (org-get-heading))))
12367 (org-auto-repeat-maybe org-state))
12368 ;; Fixup cursor location if close to the keyword
12369 (if (and (outline-on-heading-p)
12370 (not (bolp))
12371 (save-excursion (beginning-of-line 1)
12372 (looking-at org-todo-line-regexp))
12373 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12374 (progn
12375 (goto-char (or (match-end 2) (match-end 1)))
12376 (and (looking-at " ") (just-one-space))))
12377 (when org-trigger-hook
12378 (save-excursion
12379 (run-hook-with-args 'org-trigger-hook change-plist)))
12380 (when commentp (org-toggle-comment))))))))
12382 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12383 "Block turning an entry into a TODO, using the hierarchy.
12384 This checks whether the current task should be blocked from state
12385 changes. Such blocking occurs when:
12387 1. The task has children which are not all in a completed state.
12389 2. A task has a parent with the property :ORDERED:, and there
12390 are siblings prior to the current task with incomplete
12391 status.
12393 3. The parent of the task is blocked because it has siblings that should
12394 be done first, or is child of a block grandparent TODO entry."
12396 (if (not org-enforce-todo-dependencies)
12397 t ; if locally turned off don't block
12398 (catch 'dont-block
12399 ;; If this is not a todo state change, or if this entry is already DONE,
12400 ;; do not block
12401 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12402 (member (plist-get change-plist :from)
12403 (cons 'done org-done-keywords))
12404 (member (plist-get change-plist :to)
12405 (cons 'todo org-not-done-keywords))
12406 (not (plist-get change-plist :to)))
12407 (throw 'dont-block t))
12408 ;; If this task has children, and any are undone, it's blocked
12409 (save-excursion
12410 (org-back-to-heading t)
12411 (let ((this-level (funcall outline-level)))
12412 (outline-next-heading)
12413 (let ((child-level (funcall outline-level)))
12414 (while (and (not (eobp))
12415 (> child-level this-level))
12416 ;; this todo has children, check whether they are all
12417 ;; completed
12418 (if (and (not (org-entry-is-done-p))
12419 (org-entry-is-todo-p))
12420 (progn (setq org-block-entry-blocking (org-get-heading))
12421 (throw 'dont-block nil)))
12422 (outline-next-heading)
12423 (setq child-level (funcall outline-level))))))
12424 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12425 ;; any previous siblings are undone, it's blocked
12426 (save-excursion
12427 (org-back-to-heading t)
12428 (let* ((pos (point))
12429 (parent-pos (and (org-up-heading-safe) (point))))
12430 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12431 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12432 (forward-line 1)
12433 (re-search-forward org-not-done-heading-regexp pos t))
12434 (setq org-block-entry-blocking (match-string 0))
12435 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12436 ;; Search further up the hierarchy, to see if an ancestor is blocked
12437 (while t
12438 (goto-char parent-pos)
12439 (if (not (looking-at org-not-done-heading-regexp))
12440 (throw 'dont-block t)) ; do not block, parent is not a TODO
12441 (setq pos (point))
12442 (setq parent-pos (and (org-up-heading-safe) (point)))
12443 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12444 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12445 (forward-line 1)
12446 (re-search-forward org-not-done-heading-regexp pos t)
12447 (setq org-block-entry-blocking (org-get-heading)))
12448 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12450 (defcustom org-track-ordered-property-with-tag nil
12451 "Should the ORDERED property also be shown as a tag?
12452 The ORDERED property decides if an entry should require subtasks to be
12453 completed in sequence. Since a property is not very visible, setting
12454 this option means that toggling the ORDERED property with the command
12455 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12456 not relevant for the behavior, but it makes things more visible.
12458 Note that toggling the tag with tags commands will not change the property
12459 and therefore not influence behavior!
12461 This can be t, meaning the tag ORDERED should be used, It can also be a
12462 string to select a different tag for this task."
12463 :group 'org-todo
12464 :type '(choice
12465 (const :tag "No tracking" nil)
12466 (const :tag "Track with ORDERED tag" t)
12467 (string :tag "Use other tag")))
12469 (defun org-toggle-ordered-property ()
12470 "Toggle the ORDERED property of the current entry.
12471 For better visibility, you can track the value of this property with a tag.
12472 See variable `org-track-ordered-property-with-tag'."
12473 (interactive)
12474 (let* ((t1 org-track-ordered-property-with-tag)
12475 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12476 (save-excursion
12477 (org-back-to-heading)
12478 (if (org-entry-get nil "ORDERED")
12479 (progn
12480 (org-delete-property "ORDERED" "PROPERTIES")
12481 (and tag (org-toggle-tag tag 'off))
12482 (message "Subtasks can be completed in arbitrary order"))
12483 (org-entry-put nil "ORDERED" "t")
12484 (and tag (org-toggle-tag tag 'on))
12485 (message "Subtasks must be completed in sequence")))))
12487 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12488 (defun org-block-todo-from-checkboxes (change-plist)
12489 "Block turning an entry into a TODO, using checkboxes.
12490 This checks whether the current task should be blocked from state
12491 changes because there are unchecked boxes in this entry."
12492 (if (not org-enforce-todo-checkbox-dependencies)
12493 t ; if locally turned off don't block
12494 (catch 'dont-block
12495 ;; If this is not a todo state change, or if this entry is already DONE,
12496 ;; do not block
12497 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12498 (member (plist-get change-plist :from)
12499 (cons 'done org-done-keywords))
12500 (member (plist-get change-plist :to)
12501 (cons 'todo org-not-done-keywords))
12502 (not (plist-get change-plist :to)))
12503 (throw 'dont-block t))
12504 ;; If this task has checkboxes that are not checked, it's blocked
12505 (save-excursion
12506 (org-back-to-heading t)
12507 (let ((beg (point)) end)
12508 (outline-next-heading)
12509 (setq end (point))
12510 (goto-char beg)
12511 (if (org-list-search-forward
12512 (concat (org-item-beginning-re)
12513 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12514 "\\[[- ]\\]")
12515 end t)
12516 (progn
12517 (if (boundp 'org-blocked-by-checkboxes)
12518 (setq org-blocked-by-checkboxes t))
12519 (throw 'dont-block nil)))))
12520 t))) ; do not block
12522 (defun org-entry-blocked-p ()
12523 "Is the current entry blocked?"
12524 (org-with-silent-modifications
12525 (if (org-entry-get nil "NOBLOCKING")
12526 nil ;; Never block this entry
12527 (not (run-hook-with-args-until-failure
12528 'org-blocker-hook
12529 (list :type 'todo-state-change
12530 :position (point)
12531 :from 'todo
12532 :to 'done))))))
12534 (defun org-update-statistics-cookies (all)
12535 "Update the statistics cookie, either from TODO or from checkboxes.
12536 This should be called with the cursor in a line with a statistics cookie."
12537 (interactive "P")
12538 (if all
12539 (progn
12540 (org-update-checkbox-count 'all)
12541 (org-map-entries 'org-update-parent-todo-statistics))
12542 (if (not (org-at-heading-p))
12543 (org-update-checkbox-count)
12544 (let ((pos (point-marker))
12545 end l1 l2)
12546 (ignore-errors (org-back-to-heading t))
12547 (if (not (org-at-heading-p))
12548 (org-update-checkbox-count)
12549 (setq l1 (org-outline-level))
12550 (setq end (save-excursion
12551 (outline-next-heading)
12552 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12553 (point)))
12554 (if (and (save-excursion
12555 (re-search-forward
12556 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12557 (not (save-excursion (re-search-forward
12558 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12559 (org-update-checkbox-count)
12560 (if (and l2 (> l2 l1))
12561 (progn
12562 (goto-char end)
12563 (org-update-parent-todo-statistics))
12564 (goto-char pos)
12565 (beginning-of-line 1)
12566 (while (re-search-forward
12567 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12568 (point-at-eol) t)
12569 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12570 (goto-char pos)
12571 (move-marker pos nil)))))
12573 (defvar org-entry-property-inherited-from) ;; defined below
12574 (defun org-update-parent-todo-statistics ()
12575 "Update any statistics cookie in the parent of the current headline.
12576 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12577 the entire subtree and this will travel up the hierarchy and update
12578 statistics everywhere."
12579 (let* ((prop (save-excursion (org-up-heading-safe)
12580 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12581 (recursive (or (not org-hierarchical-todo-statistics)
12582 (and prop (string-match "\\<recursive\\>" prop))))
12583 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12585 (first t)
12586 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12587 level ltoggle l1 new ndel
12588 (cnt-all 0) (cnt-done 0) is-percent kwd
12589 checkbox-beg ov ovs ove cookie-present)
12590 (catch 'exit
12591 (save-excursion
12592 (beginning-of-line 1)
12593 (setq ltoggle (funcall outline-level))
12594 ;; Three situations are to consider:
12596 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12597 ;; to the top-level ancestor on the headline;
12599 ;; 2. If parent has "recursive" property, repeat up to the
12600 ;; headline setting that property, taking inheritance into
12601 ;; account;
12603 ;; 3. Else, move up to direct parent and proceed only once.
12604 (while (and (setq level (org-up-heading-safe))
12605 (or recursive first)
12606 (>= (point) lim))
12607 (setq first nil cookie-present nil)
12608 (unless (and level
12609 (not (string-match
12610 "\\<checkbox\\>"
12611 (downcase (or (org-entry-get nil "COOKIE_DATA")
12612 "")))))
12613 (throw 'exit nil))
12614 (while (re-search-forward box-re (point-at-eol) t)
12615 (setq cnt-all 0 cnt-done 0 cookie-present t)
12616 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12617 (save-match-data
12618 (unless (outline-next-heading) (throw 'exit nil))
12619 (while (and (looking-at org-complex-heading-regexp)
12620 (> (setq l1 (length (match-string 1))) level))
12621 (setq kwd (and (or recursive (= l1 ltoggle))
12622 (match-string 2)))
12623 (if (or (eq org-provide-todo-statistics 'all-headlines)
12624 (and (listp org-provide-todo-statistics)
12625 (or (member kwd org-provide-todo-statistics)
12626 (member kwd org-done-keywords))))
12627 (setq cnt-all (1+ cnt-all))
12628 (if (eq org-provide-todo-statistics t)
12629 (and kwd (setq cnt-all (1+ cnt-all)))))
12630 (and (member kwd org-done-keywords)
12631 (setq cnt-done (1+ cnt-done)))
12632 (outline-next-heading)))
12633 (setq new
12634 (if is-percent
12635 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12636 (format "[%d/%d]" cnt-done cnt-all))
12637 ndel (- (match-end 0) checkbox-beg))
12638 ;; handle overlays when updating cookie from column view
12639 (when (setq ov (car (overlays-at checkbox-beg)))
12640 (setq ovs (overlay-start ov) ove (overlay-end ov))
12641 (delete-overlay ov))
12642 (goto-char checkbox-beg)
12643 (insert new)
12644 (delete-region (point) (+ (point) ndel))
12645 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12646 (when ov (move-overlay ov ovs ove)))
12647 (when cookie-present
12648 (run-hook-with-args 'org-after-todo-statistics-hook
12649 cnt-done (- cnt-all cnt-done))))))
12650 (run-hooks 'org-todo-statistics-hook)))
12652 (defvar org-after-todo-statistics-hook nil
12653 "Hook that is called after a TODO statistics cookie has been updated.
12654 Each function is called with two arguments: the number of not-done entries
12655 and the number of done entries.
12657 For example, the following function, when added to this hook, will switch
12658 an entry to DONE when all children are done, and back to TODO when new
12659 entries are set to a TODO status. Note that this hook is only called
12660 when there is a statistics cookie in the headline!
12662 (defun org-summary-todo (n-done n-not-done)
12663 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12664 (let (org-log-done org-log-states) ; turn off logging
12665 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12668 (defvar org-todo-statistics-hook nil
12669 "Hook that is run whenever Org thinks TODO statistics should be updated.
12670 This hook runs even if there is no statistics cookie present, in which case
12671 `org-after-todo-statistics-hook' would not run.")
12673 (defun org-todo-trigger-tag-changes (state)
12674 "Apply the changes defined in `org-todo-state-tags-triggers'."
12675 (let ((l org-todo-state-tags-triggers)
12676 changes)
12677 (when (or (not state) (equal state ""))
12678 (setq changes (append changes (cdr (assoc "" l)))))
12679 (when (and (stringp state) (> (length state) 0))
12680 (setq changes (append changes (cdr (assoc state l)))))
12681 (when (member state org-not-done-keywords)
12682 (setq changes (append changes (cdr (assoc 'todo l)))))
12683 (when (member state org-done-keywords)
12684 (setq changes (append changes (cdr (assoc 'done l)))))
12685 (dolist (c changes)
12686 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12688 (defun org-local-logging (value)
12689 "Get logging settings from a property VALUE."
12690 (let* (words w a)
12691 ;; directly set the variables, they are already local.
12692 (setq org-log-done nil
12693 org-log-repeat nil
12694 org-todo-log-states nil)
12695 (setq words (org-split-string value))
12696 (while (setq w (pop words))
12697 (cond
12698 ((setq a (assoc w org-startup-options))
12699 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12700 (set (nth 1 a) (nth 2 a))))
12701 ((setq a (org-extract-log-state-settings w))
12702 (and (member (car a) org-todo-keywords-1)
12703 (push a org-todo-log-states)))))))
12705 (defun org-get-todo-sequence-head (kwd)
12706 "Return the head of the TODO sequence to which KWD belongs.
12707 If KWD is not set, check if there is a text property remembering the
12708 right sequence."
12709 (let (p)
12710 (cond
12711 ((not kwd)
12712 (or (get-text-property (point-at-bol) 'org-todo-head)
12713 (progn
12714 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12715 nil (point-at-eol)))
12716 (get-text-property p 'org-todo-head))))
12717 ((not (member kwd org-todo-keywords-1))
12718 (car org-todo-keywords-1))
12719 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12721 (defun org-fast-todo-selection ()
12722 "Fast TODO keyword selection with single keys.
12723 Returns the new TODO keyword, or nil if no state change should occur."
12724 (let* ((fulltable org-todo-key-alist)
12725 (done-keywords org-done-keywords) ;; needed for the faces.
12726 (maxlen (apply 'max (mapcar
12727 (lambda (x)
12728 (if (stringp (car x)) (string-width (car x)) 0))
12729 fulltable)))
12730 (expert nil)
12731 (fwidth (+ maxlen 3 1 3))
12732 (ncol (/ (- (window-width) 4) fwidth))
12733 tg cnt e c tbl
12734 groups ingroup)
12735 (save-excursion
12736 (save-window-excursion
12737 (if expert
12738 (set-buffer (get-buffer-create " *Org todo*"))
12739 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12740 (erase-buffer)
12741 (org-set-local 'org-done-keywords done-keywords)
12742 (setq tbl fulltable cnt 0)
12743 (while (setq e (pop tbl))
12744 (cond
12745 ((equal e '(:startgroup))
12746 (push '() groups) (setq ingroup t)
12747 (when (not (= cnt 0))
12748 (setq cnt 0)
12749 (insert "\n"))
12750 (insert "{ "))
12751 ((equal e '(:endgroup))
12752 (setq ingroup nil cnt 0)
12753 (insert "}\n"))
12754 ((equal e '(:newline))
12755 (when (not (= cnt 0))
12756 (setq cnt 0)
12757 (insert "\n")
12758 (setq e (car tbl))
12759 (while (equal (car tbl) '(:newline))
12760 (insert "\n")
12761 (setq tbl (cdr tbl)))))
12763 (setq tg (car e) c (cdr e))
12764 (if ingroup (push tg (car groups)))
12765 (setq tg (org-add-props tg nil 'face
12766 (org-get-todo-face tg)))
12767 (if (and (= cnt 0) (not ingroup)) (insert " "))
12768 (insert "[" c "] " tg (make-string
12769 (- fwidth 4 (length tg)) ?\ ))
12770 (when (= (setq cnt (1+ cnt)) ncol)
12771 (insert "\n")
12772 (if ingroup (insert " "))
12773 (setq cnt 0)))))
12774 (insert "\n")
12775 (goto-char (point-min))
12776 (if (not expert) (org-fit-window-to-buffer))
12777 (message "[a-z..]:Set [SPC]:clear")
12778 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12779 (cond
12780 ((or (= c ?\C-g)
12781 (and (= c ?q) (not (rassoc c fulltable))))
12782 (setq quit-flag t))
12783 ((= c ?\ ) nil)
12784 ((setq e (rassoc c fulltable) tg (car e))
12786 (t (setq quit-flag t)))))))
12788 (defun org-entry-is-todo-p ()
12789 (member (org-get-todo-state) org-not-done-keywords))
12791 (defun org-entry-is-done-p ()
12792 (member (org-get-todo-state) org-done-keywords))
12794 (defun org-get-todo-state ()
12795 "Return the TODO keyword of the current subtree."
12796 (save-excursion
12797 (org-back-to-heading t)
12798 (and (looking-at org-todo-line-regexp)
12799 (match-end 2)
12800 (match-string 2))))
12802 (defun org-at-date-range-p (&optional inactive-ok)
12803 "Is the cursor inside a date range?"
12804 (interactive)
12805 (save-excursion
12806 (catch 'exit
12807 (let ((pos (point)))
12808 (skip-chars-backward "^[<\r\n")
12809 (skip-chars-backward "<[")
12810 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12811 (>= (match-end 0) pos)
12812 (throw 'exit t))
12813 (skip-chars-backward "^<[\r\n")
12814 (skip-chars-backward "<[")
12815 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12816 (>= (match-end 0) pos)
12817 (throw 'exit t)))
12818 nil)))
12820 (defun org-get-repeat (&optional tagline)
12821 "Check if there is a deadline/schedule with repeater in this entry."
12822 (save-match-data
12823 (save-excursion
12824 (org-back-to-heading t)
12825 (and (re-search-forward (if tagline
12826 (concat tagline "\\s-*" org-repeat-re)
12827 org-repeat-re)
12828 (org-entry-end-position) t)
12829 (match-string-no-properties 1)))))
12831 (defvar org-last-changed-timestamp)
12832 (defvar org-last-inserted-timestamp)
12833 (defvar org-log-post-message)
12834 (defvar org-log-note-purpose)
12835 (defvar org-log-note-how)
12836 (defvar org-log-note-extra)
12837 (defun org-auto-repeat-maybe (done-word)
12838 "Check if the current headline contains a repeated deadline/schedule.
12839 If yes, set TODO state back to what it was and change the base date
12840 of repeating deadline/scheduled time stamps to new date.
12841 This function is run automatically after each state change to a DONE state."
12842 ;; last-state is dynamically scoped into this function
12843 (let* ((repeat (org-get-repeat))
12844 (aa (assoc org-last-state org-todo-kwd-alist))
12845 (interpret (nth 1 aa))
12846 (head (nth 2 aa))
12847 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12848 (msg "Entry repeats: ")
12849 (org-log-done nil)
12850 (org-todo-log-states nil)
12851 re type n what ts time to-state)
12852 (when repeat
12853 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12854 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12855 org-todo-repeat-to-state))
12856 (unless (and to-state (member to-state org-todo-keywords-1))
12857 (setq to-state (if (eq interpret 'type) org-last-state head)))
12858 (org-todo to-state)
12859 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12860 (org-entry-put nil "LAST_REPEAT" (format-time-string
12861 (org-time-stamp-format t t))))
12862 (when org-log-repeat
12863 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12864 (memq 'org-add-log-note post-command-hook))
12865 ;; OK, we are already setup for some record
12866 (if (eq org-log-repeat 'note)
12867 ;; make sure we take a note, not only a time stamp
12868 (setq org-log-note-how 'note))
12869 ;; Set up for taking a record
12870 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12871 org-last-state
12872 'findpos org-log-repeat)))
12873 (org-back-to-heading t)
12874 (org-add-planning-info nil nil 'closed)
12875 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12876 org-deadline-time-regexp "\\)\\|\\("
12877 org-ts-regexp "\\)"))
12878 (while (re-search-forward
12879 re (save-excursion (outline-next-heading) (point)) t)
12880 (setq type (if (match-end 1) org-scheduled-string
12881 (if (match-end 3) org-deadline-string "Plain:"))
12882 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12883 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12884 (setq n (string-to-number (match-string 2 ts))
12885 what (match-string 3 ts))
12886 (if (equal what "w") (setq n (* n 7) what "d"))
12887 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12888 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12889 ;; Preparation, see if we need to modify the start date for the change
12890 (when (match-end 1)
12891 (setq time (save-match-data (org-time-string-to-time ts)))
12892 (cond
12893 ((equal (match-string 1 ts) ".")
12894 ;; Shift starting date to today
12895 (org-timestamp-change
12896 (- (org-today) (time-to-days time))
12897 'day))
12898 ((equal (match-string 1 ts) "+")
12899 (let ((nshiftmax 10) (nshift 0))
12900 (while (or (= nshift 0)
12901 (<= (time-to-days time)
12902 (time-to-days (current-time))))
12903 (when (= (incf nshift) nshiftmax)
12904 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12905 (error "Abort")))
12906 (org-timestamp-change n (cdr (assoc what whata)))
12907 (org-at-timestamp-p t)
12908 (setq ts (match-string 1))
12909 (setq time (save-match-data (org-time-string-to-time ts)))))
12910 (org-timestamp-change (- n) (cdr (assoc what whata)))
12911 ;; rematch, so that we have everything in place for the real shift
12912 (org-at-timestamp-p t)
12913 (setq ts (match-string 1))
12914 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12915 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12916 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12917 (setq org-log-post-message msg)
12918 (message "%s" msg))))
12920 (defun org-show-todo-tree (arg)
12921 "Make a compact tree which shows all headlines marked with TODO.
12922 The tree will show the lines where the regexp matches, and all higher
12923 headlines above the match.
12924 With a \\[universal-argument] prefix, prompt for a regexp to match.
12925 With a numeric prefix N, construct a sparse tree for the Nth element
12926 of `org-todo-keywords-1'."
12927 (interactive "P")
12928 (let ((case-fold-search nil)
12929 (kwd-re
12930 (cond ((null arg) org-not-done-regexp)
12931 ((equal arg '(4))
12932 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12933 (mapcar 'list org-todo-keywords-1))))
12934 (concat "\\("
12935 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12936 "\\)\\>")))
12937 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12938 (regexp-quote (nth (1- (prefix-numeric-value arg))
12939 org-todo-keywords-1)))
12940 (t (user-error "Invalid prefix argument: %s" arg)))))
12941 (message "%d TODO entries found"
12942 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12944 (defun org-deadline (arg &optional time)
12945 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12946 With one universal prefix argument, remove any deadline from the item.
12947 With two universal prefix arguments, prompt for a warning delay.
12948 With argument TIME, set the deadline at the corresponding date. TIME
12949 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12950 (interactive "P")
12951 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12952 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12953 'region-start-level 'region))
12954 org-loop-over-headlines-in-active-region)
12955 (org-map-entries
12956 `(org-deadline ',arg ,time)
12957 org-loop-over-headlines-in-active-region
12958 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12959 (let* ((old-date (org-entry-get nil "DEADLINE"))
12960 (old-date-time (if old-date (org-time-string-to-time old-date)))
12961 (repeater (and old-date
12962 (string-match
12963 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12964 old-date)
12965 (match-string 1 old-date))))
12966 (cond
12967 ((equal arg '(4))
12968 (when (and old-date org-log-redeadline)
12969 (org-add-log-setup 'deldeadline nil old-date 'findpos
12970 org-log-redeadline))
12971 (org-remove-timestamp-with-keyword org-deadline-string)
12972 (message "Item no longer has a deadline."))
12973 ((equal arg '(16))
12974 (save-excursion
12975 (org-back-to-heading t)
12976 (if (re-search-forward
12977 org-deadline-time-regexp
12978 (save-excursion (outline-next-heading) (point)) t)
12979 (let* ((rpl0 (match-string 1))
12980 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12981 (replace-match
12982 (concat org-deadline-string
12983 " <" rpl
12984 (format " -%dd"
12985 (abs
12986 (- (time-to-days
12987 (save-match-data
12988 (org-read-date nil t nil "Warn starting from" old-date-time)))
12989 (time-to-days old-date-time))))
12990 ">") t t))
12991 (user-error "No deadline information to update"))))
12993 (org-add-planning-info 'deadline time 'closed)
12994 (when (and old-date org-log-redeadline
12995 (not (equal old-date
12996 (substring org-last-inserted-timestamp 1 -1))))
12997 (org-add-log-setup 'redeadline nil old-date 'findpos
12998 org-log-redeadline))
12999 (when repeater
13000 (save-excursion
13001 (org-back-to-heading t)
13002 (when (re-search-forward (concat org-deadline-string " "
13003 org-last-inserted-timestamp)
13004 (save-excursion
13005 (outline-next-heading) (point)) t)
13006 (goto-char (1- (match-end 0)))
13007 (insert " " repeater)
13008 (setq org-last-inserted-timestamp
13009 (concat (substring org-last-inserted-timestamp 0 -1)
13010 " " repeater
13011 (substring org-last-inserted-timestamp -1))))))
13012 (message "Deadline on %s" org-last-inserted-timestamp))))))
13014 (defun org-schedule (arg &optional time)
13015 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13016 With one universal prefix argument, remove any scheduling date from the item.
13017 With two universal prefix arguments, prompt for a delay cookie.
13018 With argument TIME, scheduled at the corresponding date. TIME can
13019 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13020 (interactive "P")
13021 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13022 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13023 'region-start-level 'region))
13024 org-loop-over-headlines-in-active-region)
13025 (org-map-entries
13026 `(org-schedule ',arg ,time)
13027 org-loop-over-headlines-in-active-region
13028 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13029 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13030 (old-date-time (if old-date (org-time-string-to-time old-date)))
13031 (repeater (and old-date
13032 (string-match
13033 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13034 old-date)
13035 (match-string 1 old-date))))
13036 (cond
13037 ((equal arg '(4))
13038 (progn
13039 (when (and old-date org-log-reschedule)
13040 (org-add-log-setup 'delschedule nil old-date 'findpos
13041 org-log-reschedule))
13042 (org-remove-timestamp-with-keyword org-scheduled-string)
13043 (message "Item is no longer scheduled.")))
13044 ((equal arg '(16))
13045 (save-excursion
13046 (org-back-to-heading t)
13047 (if (re-search-forward
13048 org-scheduled-time-regexp
13049 (save-excursion (outline-next-heading) (point)) t)
13050 (let* ((rpl0 (match-string 1))
13051 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13052 (replace-match
13053 (concat org-scheduled-string
13054 " <" rpl
13055 (format " -%dd"
13056 (abs
13057 (- (time-to-days
13058 (save-match-data
13059 (org-read-date nil t nil "Delay until" old-date-time)))
13060 (time-to-days old-date-time))))
13061 ">") t t))
13062 (user-error "No scheduled information to update"))))
13064 (org-add-planning-info 'scheduled time 'closed)
13065 (when (and old-date org-log-reschedule
13066 (not (equal old-date
13067 (substring org-last-inserted-timestamp 1 -1))))
13068 (org-add-log-setup 'reschedule nil old-date 'findpos
13069 org-log-reschedule))
13070 (when repeater
13071 (save-excursion
13072 (org-back-to-heading t)
13073 (when (re-search-forward (concat org-scheduled-string " "
13074 org-last-inserted-timestamp)
13075 (save-excursion
13076 (outline-next-heading) (point)) t)
13077 (goto-char (1- (match-end 0)))
13078 (insert " " repeater)
13079 (setq org-last-inserted-timestamp
13080 (concat (substring org-last-inserted-timestamp 0 -1)
13081 " " repeater
13082 (substring org-last-inserted-timestamp -1))))))
13083 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13085 (defun org-get-scheduled-time (pom &optional inherit)
13086 "Get the scheduled time as a time tuple, of a format suitable
13087 for calling org-schedule with, or if there is no scheduling,
13088 returns nil."
13089 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13090 (when time
13091 (apply 'encode-time (org-parse-time-string time)))))
13093 (defun org-get-deadline-time (pom &optional inherit)
13094 "Get the deadline as a time tuple, of a format suitable for
13095 calling org-deadline with, or if there is no scheduling, returns
13096 nil."
13097 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13098 (when time
13099 (apply 'encode-time (org-parse-time-string time)))))
13101 (defun org-remove-timestamp-with-keyword (keyword)
13102 "Remove all time stamps with KEYWORD in the current entry."
13103 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13104 beg)
13105 (save-excursion
13106 (org-back-to-heading t)
13107 (setq beg (point))
13108 (outline-next-heading)
13109 (while (re-search-backward re beg t)
13110 (replace-match "")
13111 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13112 (equal (char-before) ?\ ))
13113 (backward-delete-char 1)
13114 (if (string-match "^[ \t]*$" (buffer-substring
13115 (point-at-bol) (point-at-eol)))
13116 (delete-region (point-at-bol)
13117 (min (point-max) (1+ (point-at-eol))))))))))
13119 (defvar org-time-was-given) ; dynamically scoped parameter
13120 (defvar org-end-time-was-given) ; dynamically scoped parameter
13122 (defun org-add-planning-info (what &optional time &rest remove)
13123 "Insert new timestamp with keyword in the line directly after the headline.
13124 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13125 If non is given, the user is prompted for a date.
13126 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13127 be removed."
13128 (interactive)
13129 (let (org-time-was-given org-end-time-was-given ts
13130 end default-time default-input)
13132 (catch 'exit
13133 (when (and (memq what '(scheduled deadline))
13134 (or (not time)
13135 (and (stringp time)
13136 (string-match "^[-+]+[0-9]" time))))
13137 ;; Try to get a default date/time from existing timestamp
13138 (save-excursion
13139 (org-back-to-heading t)
13140 (setq end (save-excursion (outline-next-heading) (point)))
13141 (when (re-search-forward (if (eq what 'scheduled)
13142 org-scheduled-time-regexp
13143 org-deadline-time-regexp)
13144 end t)
13145 (setq ts (match-string 1)
13146 default-time
13147 (apply 'encode-time (org-parse-time-string ts))
13148 default-input (and ts (org-get-compact-tod ts))))))
13149 (when what
13150 (setq time
13151 (if (stringp time)
13152 ;; This is a string (relative or absolute), set proper date
13153 (apply 'encode-time
13154 (org-read-date-analyze
13155 time default-time (decode-time default-time)))
13156 ;; If necessary, get the time from the user
13157 (or time (org-read-date nil 'to-time nil nil
13158 default-time default-input)))))
13160 (when (and org-insert-labeled-timestamps-at-point
13161 (member what '(scheduled deadline)))
13162 (insert
13163 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13164 (org-insert-time-stamp time org-time-was-given
13165 nil nil nil (list org-end-time-was-given))
13166 (setq what nil))
13167 (save-excursion
13168 (save-restriction
13169 (let (col list elt ts buffer-invisibility-spec)
13170 (org-back-to-heading t)
13171 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13172 (goto-char (match-end 1))
13173 (setq col (current-column))
13174 (goto-char (match-end 0))
13175 (if (eobp) (insert "\n") (forward-char 1))
13176 (when (and (not what)
13177 (not (looking-at
13178 (concat "[ \t]*"
13179 org-keyword-time-not-clock-regexp))))
13180 ;; Nothing to add, nothing to remove...... :-)
13181 (throw 'exit nil))
13182 (if (and (not (looking-at org-outline-regexp))
13183 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13184 "[^\r\n]*"))
13185 (not (equal (match-string 1) org-clock-string)))
13186 (narrow-to-region (match-beginning 0) (match-end 0))
13187 (insert-before-markers "\n")
13188 (backward-char 1)
13189 (narrow-to-region (point) (point))
13190 (and org-adapt-indentation (org-indent-to-column col)))
13191 ;; Check if we have to remove something.
13192 (setq list (cons what remove))
13193 (while list
13194 (setq elt (pop list))
13195 (when (or (and (eq elt 'scheduled)
13196 (re-search-forward org-scheduled-time-regexp nil t))
13197 (and (eq elt 'deadline)
13198 (re-search-forward org-deadline-time-regexp nil t))
13199 (and (eq elt 'closed)
13200 (re-search-forward org-closed-time-regexp nil t)))
13201 (replace-match "")
13202 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13203 (and (looking-at "[ \t]+") (replace-match ""))
13204 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13205 (when what
13206 (insert
13207 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13208 (cond ((eq what 'scheduled) org-scheduled-string)
13209 ((eq what 'deadline) org-deadline-string)
13210 ((eq what 'closed) org-closed-string))
13211 " ")
13212 (setq ts (org-insert-time-stamp
13213 time
13214 (or org-time-was-given
13215 (and (eq what 'closed) org-log-done-with-time))
13216 (eq what 'closed)
13217 nil nil (list org-end-time-was-given)))
13218 (insert
13219 (if (not (or (bolp) (eq (char-before) ?\ )
13220 (memq (char-after) '(32 10))
13221 (eobp))) " " ""))
13222 (end-of-line 1))
13223 (goto-char (point-min))
13224 (widen)
13225 (if (and (looking-at "[ \t]*\n")
13226 (equal (char-before) ?\n))
13227 (delete-region (1- (point)) (point-at-eol)))
13228 ts))))))
13230 (defvar org-log-note-marker (make-marker))
13231 (defvar org-log-note-purpose nil)
13232 (defvar org-log-note-state nil)
13233 (defvar org-log-note-previous-state nil)
13234 (defvar org-log-note-how nil)
13235 (defvar org-log-note-extra nil)
13236 (defvar org-log-note-window-configuration nil)
13237 (defvar org-log-note-return-to (make-marker))
13238 (defvar org-log-note-effective-time nil
13239 "Remembered current time so that dynamically scoped
13240 `org-extend-today-until' affects tha timestamps in state change
13241 log")
13243 (defvar org-log-post-message nil
13244 "Message to be displayed after a log note has been stored.
13245 The auto-repeater uses this.")
13247 (defun org-add-note ()
13248 "Add a note to the current entry.
13249 This is done in the same way as adding a state change note."
13250 (interactive)
13251 (org-add-log-setup 'note nil nil 'findpos nil))
13253 (defvar org-property-end-re)
13254 (defun org-add-log-setup (&optional purpose state prev-state
13255 findpos how extra)
13256 "Set up the post command hook to take a note.
13257 If this is about to TODO state change, the new state is expected in STATE.
13258 When FINDPOS is non-nil, find the correct position for the note in
13259 the current entry. If not, assume that it can be inserted at point.
13260 HOW is an indicator what kind of note should be created.
13261 EXTRA is additional text that will be inserted into the notes buffer."
13262 (let* ((org-log-into-drawer (org-log-into-drawer))
13263 (drawer (cond ((stringp org-log-into-drawer)
13264 org-log-into-drawer)
13265 (org-log-into-drawer "LOGBOOK"))))
13266 (save-restriction
13267 (save-excursion
13268 (when findpos
13269 (org-back-to-heading t)
13270 (narrow-to-region (point) (save-excursion
13271 (outline-next-heading) (point)))
13272 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13273 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13274 "[^\r\n]*\\)?"))
13275 (goto-char (match-end 0))
13276 (cond
13277 (drawer
13278 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13279 nil t)
13280 (progn
13281 (goto-char (match-end 0))
13282 (or org-log-states-order-reversed
13283 (and (re-search-forward org-property-end-re nil t)
13284 (goto-char (1- (match-beginning 0))))))
13285 (insert "\n:" drawer ":\n:END:")
13286 (beginning-of-line 0)
13287 (org-indent-line)
13288 (beginning-of-line 2)
13289 (org-indent-line)
13290 (end-of-line 0)))
13291 ((and org-log-state-notes-insert-after-drawers
13292 (save-excursion
13293 (forward-line) (looking-at org-drawer-regexp)))
13294 (forward-line)
13295 (while (looking-at org-drawer-regexp)
13296 (goto-char (match-end 0))
13297 (re-search-forward org-property-end-re (point-max) t)
13298 (forward-line))
13299 (forward-line -1)))
13300 (unless org-log-states-order-reversed
13301 (and (= (char-after) ?\n) (forward-char 1))
13302 (org-skip-over-state-notes)
13303 (skip-chars-backward " \t\n\r")))
13304 (move-marker org-log-note-marker (point))
13305 (setq org-log-note-purpose purpose
13306 org-log-note-state state
13307 org-log-note-previous-state prev-state
13308 org-log-note-how how
13309 org-log-note-extra extra
13310 org-log-note-effective-time (org-current-effective-time))
13311 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13313 (defun org-skip-over-state-notes ()
13314 "Skip past the list of State notes in an entry."
13315 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13316 (when (ignore-errors (goto-char (org-in-item-p)))
13317 (let* ((struct (org-list-struct))
13318 (prevs (org-list-prevs-alist struct)))
13319 (while (looking-at "[ \t]*- State")
13320 (goto-char (or (org-list-get-next-item (point) struct prevs)
13321 (org-list-get-item-end (point) struct)))))))
13323 (defun org-add-log-note (&optional purpose)
13324 "Pop up a window for taking a note, and add this note later at point."
13325 (remove-hook 'post-command-hook 'org-add-log-note)
13326 (setq org-log-note-window-configuration (current-window-configuration))
13327 (delete-other-windows)
13328 (move-marker org-log-note-return-to (point))
13329 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13330 (goto-char org-log-note-marker)
13331 (org-switch-to-buffer-other-window "*Org Note*")
13332 (erase-buffer)
13333 (if (memq org-log-note-how '(time state))
13334 (let (current-prefix-arg) (org-store-log-note))
13335 (let ((org-inhibit-startup t)) (org-mode))
13336 (insert (format "# Insert note for %s.
13337 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13338 (cond
13339 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13340 ((eq org-log-note-purpose 'done) "closed todo item")
13341 ((eq org-log-note-purpose 'state)
13342 (format "state change from \"%s\" to \"%s\""
13343 (or org-log-note-previous-state "")
13344 (or org-log-note-state "")))
13345 ((eq org-log-note-purpose 'reschedule)
13346 "rescheduling")
13347 ((eq org-log-note-purpose 'delschedule)
13348 "no longer scheduled")
13349 ((eq org-log-note-purpose 'redeadline)
13350 "changing deadline")
13351 ((eq org-log-note-purpose 'deldeadline)
13352 "removing deadline")
13353 ((eq org-log-note-purpose 'refile)
13354 "refiling")
13355 ((eq org-log-note-purpose 'note)
13356 "this entry")
13357 (t (error "This should not happen")))))
13358 (if org-log-note-extra (insert org-log-note-extra))
13359 (org-set-local 'org-finish-function 'org-store-log-note)
13360 (run-hooks 'org-log-buffer-setup-hook)))
13362 (defvar org-note-abort nil) ; dynamically scoped
13363 (defun org-store-log-note ()
13364 "Finish taking a log note, and insert it to where it belongs."
13365 (let ((txt (buffer-string)))
13366 (kill-buffer (current-buffer))
13367 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13368 lines ind bul)
13369 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13370 (setq txt (replace-match "" t t txt)))
13371 (if (string-match "\\s-+\\'" txt)
13372 (setq txt (replace-match "" t t txt)))
13373 (setq lines (org-split-string txt "\n"))
13374 (when (and note (string-match "\\S-" note))
13375 (setq note
13376 (org-replace-escapes
13377 note
13378 (list (cons "%u" (user-login-name))
13379 (cons "%U" user-full-name)
13380 (cons "%t" (format-time-string
13381 (org-time-stamp-format 'long 'inactive)
13382 org-log-note-effective-time))
13383 (cons "%T" (format-time-string
13384 (org-time-stamp-format 'long nil)
13385 org-log-note-effective-time))
13386 (cons "%d" (format-time-string
13387 (org-time-stamp-format nil 'inactive)
13388 org-log-note-effective-time))
13389 (cons "%D" (format-time-string
13390 (org-time-stamp-format nil nil)
13391 org-log-note-effective-time))
13392 (cons "%s" (if org-log-note-state
13393 (concat "\"" org-log-note-state "\"")
13394 ""))
13395 (cons "%S" (if org-log-note-previous-state
13396 (concat "\"" org-log-note-previous-state "\"")
13397 "\"\"")))))
13398 (if lines (setq note (concat note " \\\\")))
13399 (push note lines))
13400 (when (or current-prefix-arg org-note-abort)
13401 (when org-log-into-drawer
13402 (org-remove-empty-drawer-at
13403 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13404 org-log-note-marker))
13405 (setq lines nil))
13406 (when lines
13407 (with-current-buffer (marker-buffer org-log-note-marker)
13408 (save-excursion
13409 (goto-char org-log-note-marker)
13410 (move-marker org-log-note-marker nil)
13411 (end-of-line 1)
13412 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13413 (setq ind (save-excursion
13414 (if (ignore-errors (goto-char (org-in-item-p)))
13415 (let ((struct (org-list-struct)))
13416 (org-list-get-ind
13417 (org-list-get-top-point struct) struct))
13418 (skip-chars-backward " \r\t\n")
13419 (cond
13420 ((and (org-at-heading-p)
13421 org-adapt-indentation)
13422 (1+ (org-current-level)))
13423 ((org-at-heading-p) 0)
13424 (t (org-get-indentation))))))
13425 (setq bul (org-list-bullet-string "-"))
13426 (org-indent-line-to ind)
13427 (insert bul (pop lines))
13428 (let ((ind-body (+ (length bul) ind)))
13429 (while lines
13430 (insert "\n")
13431 (org-indent-line-to ind-body)
13432 (insert (pop lines))))
13433 (message "Note stored")
13434 (org-back-to-heading t)
13435 (org-cycle-hide-drawers 'children))
13436 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13437 ;; from within `org-add-log-note' because `buffer-undo-list'
13438 ;; is then modified outside of `org-with-remote-undo'.
13439 (when (eq this-command 'org-agenda-todo)
13440 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13441 ;; Don't add undo information when called from `org-agenda-todo'
13442 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13443 (set-window-configuration org-log-note-window-configuration)
13444 (with-current-buffer (marker-buffer org-log-note-return-to)
13445 (goto-char org-log-note-return-to))
13446 (move-marker org-log-note-return-to nil)
13447 (and org-log-post-message (message "%s" org-log-post-message))))
13449 (defun org-remove-empty-drawer-at (drawer pos)
13450 "Remove an empty drawer DRAWER at position POS.
13451 POS may also be a marker."
13452 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13453 (save-excursion
13454 (save-restriction
13455 (widen)
13456 (goto-char pos)
13457 (if (org-in-regexp
13458 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13459 (replace-match ""))))))
13461 (defvar org-ts-type nil)
13462 (defun org-sparse-tree (&optional arg type)
13463 "Create a sparse tree, prompt for the details.
13464 This command can create sparse trees. You first need to select the type
13465 of match used to create the tree:
13467 t Show all TODO entries.
13468 T Show entries with a specific TODO keyword.
13469 m Show entries selected by a tags/property match.
13470 p Enter a property name and its value (both with completion on existing
13471 names/values) and show entries with that property.
13472 r Show entries matching a regular expression (`/' can be used as well).
13473 b Show deadlines and scheduled items before a date.
13474 a Show deadlines and scheduled items after a date.
13475 d Show deadlines due within `org-deadline-warning-days'.
13476 D Show deadlines and scheduled items between a date range."
13477 (interactive "P")
13478 (let (ans kwd value ts-type)
13479 (setq type (or type org-sparse-tree-default-date-type))
13480 (setq org-ts-type type)
13481 (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"
13482 (cond ((eq type 'all) "all timestamps")
13483 ((eq type 'scheduled) "only scheduled")
13484 ((eq type 'deadline) "only deadline")
13485 ((eq type 'active) "only active timestamps")
13486 ((eq type 'inactive) "only inactive timestamps")
13487 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13488 ((eq type 'closed) "with a closed time-stamp")
13489 (t "scheduled/deadline")))
13490 (setq ans (read-char-exclusive))
13491 (cond
13492 ((equal ans ?c)
13493 (org-sparse-tree
13494 arg (cadr (member type '(scheduled-or-deadline
13495 all scheduled deadline active inactive closed)))))
13496 ((equal ans ?d)
13497 (call-interactively 'org-check-deadlines))
13498 ((equal ans ?b)
13499 (call-interactively 'org-check-before-date))
13500 ((equal ans ?a)
13501 (call-interactively 'org-check-after-date))
13502 ((equal ans ?D)
13503 (call-interactively 'org-check-dates-range))
13504 ((equal ans ?t)
13505 (call-interactively 'org-show-todo-tree))
13506 ((equal ans ?T)
13507 (org-show-todo-tree '(4)))
13508 ((member ans '(?T ?m))
13509 (call-interactively 'org-match-sparse-tree))
13510 ((member ans '(?p ?P))
13511 (setq kwd (org-icompleting-read "Property: "
13512 (mapcar 'list (org-buffer-property-keys))))
13513 (setq value (org-icompleting-read "Value: "
13514 (mapcar 'list (org-property-values kwd))))
13515 (unless (string-match "\\`{.*}\\'" value)
13516 (setq value (concat "\"" value "\"")))
13517 (org-match-sparse-tree arg (concat kwd "=" value)))
13518 ((member ans '(?r ?R ?/))
13519 (call-interactively 'org-occur))
13520 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13522 (defvar org-occur-highlights nil
13523 "List of overlays used for occur matches.")
13524 (make-variable-buffer-local 'org-occur-highlights)
13525 (defvar org-occur-parameters nil
13526 "Parameters of the active org-occur calls.
13527 This is a list, each call to org-occur pushes as cons cell,
13528 containing the regular expression and the callback, onto the list.
13529 The list can contain several entries if `org-occur' has been called
13530 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13531 will only contain one set of parameters. When the highlights are
13532 removed (for example with `C-c C-c', or with the next edit (depending
13533 on `org-remove-highlights-with-change'), this variable is emptied
13534 as well.")
13535 (make-variable-buffer-local 'org-occur-parameters)
13537 (defun org-occur (regexp &optional keep-previous callback)
13538 "Make a compact tree which shows all matches of REGEXP.
13539 The tree will show the lines where the regexp matches, and all higher
13540 headlines above the match. It will also show the heading after the match,
13541 to make sure editing the matching entry is easy.
13542 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13543 call to `org-occur' will be kept, to allow stacking of calls to this
13544 command.
13545 If CALLBACK is non-nil, it is a function which is called to confirm
13546 that the match should indeed be shown."
13547 (interactive "sRegexp: \nP")
13548 (when (equal regexp "")
13549 (user-error "Regexp cannot be empty"))
13550 (unless keep-previous
13551 (org-remove-occur-highlights nil nil t))
13552 (push (cons regexp callback) org-occur-parameters)
13553 (let ((cnt 0))
13554 (save-excursion
13555 (goto-char (point-min))
13556 (if (or (not keep-previous) ; do not want to keep
13557 (not org-occur-highlights)) ; no previous matches
13558 ;; hide everything
13559 (org-overview))
13560 (while (re-search-forward regexp nil t)
13561 (when (or (not callback)
13562 (save-match-data (funcall callback)))
13563 (setq cnt (1+ cnt))
13564 (when org-highlight-sparse-tree-matches
13565 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13566 (org-show-context 'occur-tree))))
13567 (when org-remove-highlights-with-change
13568 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13569 nil 'local))
13570 (unless org-sparse-tree-open-archived-trees
13571 (org-hide-archived-subtrees (point-min) (point-max)))
13572 (run-hooks 'org-occur-hook)
13573 (if (org-called-interactively-p 'interactive)
13574 (message "%d match(es) for regexp %s" cnt regexp))
13575 cnt))
13577 (defun org-occur-next-match (&optional n reset)
13578 "Function for `next-error-function' to find sparse tree matches.
13579 N is the number of matches to move, when negative move backwards.
13580 RESET is entirely ignored - this function always goes back to the
13581 starting point when no match is found."
13582 (let* ((limit (if (< n 0) (point-min) (point-max)))
13583 (search-func (if (< n 0)
13584 'previous-single-char-property-change
13585 'next-single-char-property-change))
13586 (n (abs n))
13587 (pos (point))
13589 (catch 'exit
13590 (while (setq p1 (funcall search-func (point) 'org-type))
13591 (when (equal p1 limit)
13592 (goto-char pos)
13593 (error "No more matches"))
13594 (when (equal (get-char-property p1 'org-type) 'org-occur)
13595 (setq n (1- n))
13596 (when (= n 0)
13597 (goto-char p1)
13598 (throw 'exit (point))))
13599 (goto-char p1))
13600 (goto-char p1)
13601 (error "No more matches"))))
13603 (defun org-show-context (&optional key)
13604 "Make sure point and context are visible.
13605 How much context is shown depends upon the variables
13606 `org-show-hierarchy-above', `org-show-following-heading',
13607 `org-show-entry-below' and `org-show-siblings'."
13608 (let ((heading-p (org-at-heading-p t))
13609 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13610 (following-p (org-get-alist-option org-show-following-heading key))
13611 (entry-p (org-get-alist-option org-show-entry-below key))
13612 (siblings-p (org-get-alist-option org-show-siblings key)))
13613 ;; Show heading or entry text
13614 (if (and heading-p (not entry-p))
13615 (org-flag-heading nil) ; only show the heading
13616 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13617 (org-show-hidden-entry))) ; show entire entry
13618 (when following-p
13619 ;; Show next sibling, or heading below text
13620 (save-excursion
13621 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13622 (org-flag-heading nil))))
13623 (when siblings-p (org-show-siblings))
13624 (when hierarchy-p
13625 ;; show all higher headings, possibly with siblings
13626 (save-excursion
13627 (while (and (condition-case nil
13628 (progn (org-up-heading-all 1) t)
13629 (error nil))
13630 (not (bobp)))
13631 (org-flag-heading nil)
13632 (when siblings-p (org-show-siblings)))))
13633 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13635 (defvar org-reveal-start-hook nil
13636 "Hook run before revealing a location.")
13638 (defun org-reveal (&optional siblings)
13639 "Show current entry, hierarchy above it, and the following headline.
13640 This can be used to show a consistent set of context around locations
13641 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13642 not t for the search context.
13644 With optional argument SIBLINGS, on each level of the hierarchy all
13645 siblings are shown. This repairs the tree structure to what it would
13646 look like when opened with hierarchical calls to `org-cycle'.
13647 With double optional argument \\[universal-argument] \\[universal-argument], \
13648 go to the parent and show the
13649 entire tree."
13650 (interactive "P")
13651 (run-hooks 'org-reveal-start-hook)
13652 (let ((org-show-hierarchy-above t)
13653 (org-show-following-heading t)
13654 (org-show-siblings (if siblings t org-show-siblings)))
13655 (org-show-context nil))
13656 (when (equal siblings '(16))
13657 (save-excursion
13658 (when (org-up-heading-safe)
13659 (org-show-subtree)
13660 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13662 (defun org-highlight-new-match (beg end)
13663 "Highlight from BEG to END and mark the highlight is an occur headline."
13664 (let ((ov (make-overlay beg end)))
13665 (overlay-put ov 'face 'secondary-selection)
13666 (overlay-put ov 'org-type 'org-occur)
13667 (push ov org-occur-highlights)))
13669 (defun org-remove-occur-highlights (&optional beg end noremove)
13670 "Remove the occur highlights from the buffer.
13671 BEG and END are ignored. If NOREMOVE is nil, remove this function
13672 from the `before-change-functions' in the current buffer."
13673 (interactive)
13674 (unless org-inhibit-highlight-removal
13675 (mapc 'delete-overlay org-occur-highlights)
13676 (setq org-occur-highlights nil)
13677 (setq org-occur-parameters nil)
13678 (unless noremove
13679 (remove-hook 'before-change-functions
13680 'org-remove-occur-highlights 'local))))
13682 ;;;; Priorities
13684 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13685 "Regular expression matching the priority indicator.")
13687 (defvar org-remove-priority-next-time nil)
13689 (defun org-priority-up ()
13690 "Increase the priority of the current item."
13691 (interactive)
13692 (org-priority 'up))
13694 (defun org-priority-down ()
13695 "Decrease the priority of the current item."
13696 (interactive)
13697 (org-priority 'down))
13699 (defun org-priority (&optional action show)
13700 "Change the priority of an item.
13701 ACTION can be `set', `up', `down', or a character."
13702 (interactive "P")
13703 (if (equal action '(4))
13704 (org-show-priority)
13705 (unless org-enable-priority-commands
13706 (user-error "Priority commands are disabled"))
13707 (setq action (or action 'set))
13708 (let (current new news have remove)
13709 (save-excursion
13710 (org-back-to-heading t)
13711 (if (looking-at org-priority-regexp)
13712 (setq current (string-to-char (match-string 2))
13713 have t))
13714 (cond
13715 ((eq action 'remove)
13716 (setq remove t new ?\ ))
13717 ((or (eq action 'set)
13718 (if (featurep 'xemacs) (characterp action) (integerp action)))
13719 (if (not (eq action 'set))
13720 (setq new action)
13721 (message "Priority %c-%c, SPC to remove: "
13722 org-highest-priority org-lowest-priority)
13723 (save-match-data
13724 (setq new (read-char-exclusive))))
13725 (if (and (= (upcase org-highest-priority) org-highest-priority)
13726 (= (upcase org-lowest-priority) org-lowest-priority))
13727 (setq new (upcase new)))
13728 (cond ((equal new ?\ ) (setq remove t))
13729 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13730 (user-error "Priority must be between `%c' and `%c'"
13731 org-highest-priority org-lowest-priority))))
13732 ((eq action 'up)
13733 (setq new (if have
13734 (1- current) ; normal cycling
13735 ;; last priority was empty
13736 (if (eq last-command this-command)
13737 org-lowest-priority ; wrap around empty to lowest
13738 ;; default
13739 (if org-priority-start-cycle-with-default
13740 org-default-priority
13741 (1- org-default-priority))))))
13742 ((eq action 'down)
13743 (setq new (if have
13744 (1+ current) ; normal cycling
13745 ;; last priority was empty
13746 (if (eq last-command this-command)
13747 org-highest-priority ; wrap around empty to highest
13748 ;; default
13749 (if org-priority-start-cycle-with-default
13750 org-default-priority
13751 (1+ org-default-priority))))))
13752 (t (user-error "Invalid action")))
13753 (if (or (< (upcase new) org-highest-priority)
13754 (> (upcase new) org-lowest-priority))
13755 (if (and (memq action '(up down))
13756 (not have) (not (eq last-command this-command)))
13757 ;; `new' is from default priority
13758 (error
13759 "The default can not be set, see `org-default-priority' why")
13760 ;; normal cycling: `new' is beyond highest/lowest priority
13761 ;; and is wrapped around to the empty priority
13762 (setq remove t)))
13763 (setq news (format "%c" new))
13764 (if have
13765 (if remove
13766 (replace-match "" t t nil 1)
13767 (replace-match news t t nil 2))
13768 (if remove
13769 (user-error "No priority cookie found in line")
13770 (let ((case-fold-search nil))
13771 (looking-at org-todo-line-regexp))
13772 (if (match-end 2)
13773 (progn
13774 (goto-char (match-end 2))
13775 (insert " [#" news "]"))
13776 (goto-char (match-beginning 3))
13777 (insert "[#" news "] "))))
13778 (org-preserve-lc (org-set-tags nil 'align)))
13779 (if remove
13780 (message "Priority removed")
13781 (message "Priority of current item set to %s" news)))))
13783 (defun org-show-priority ()
13784 "Show the priority of the current item.
13785 This priority is composed of the main priority given with the [#A] cookies,
13786 and by additional input from the age of a schedules or deadline entry."
13787 (interactive)
13788 (let ((pri (if (eq major-mode 'org-agenda-mode)
13789 (org-get-at-bol 'priority)
13790 (save-excursion
13791 (save-match-data
13792 (beginning-of-line)
13793 (and (looking-at org-heading-regexp)
13794 (org-get-priority (match-string 0))))))))
13795 (message "Priority is %d" (if pri pri -1000))))
13797 (defun org-get-priority (s)
13798 "Find priority cookie and return priority."
13799 (save-match-data
13800 (if (functionp org-get-priority-function)
13801 (funcall org-get-priority-function)
13802 (if (not (string-match org-priority-regexp s))
13803 (* 1000 (- org-lowest-priority org-default-priority))
13804 (* 1000 (- org-lowest-priority
13805 (string-to-char (match-string 2 s))))))))
13807 ;;;; Tags
13809 (defvar org-agenda-archives-mode)
13810 (defvar org-map-continue-from nil
13811 "Position from where mapping should continue.
13812 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13814 (defvar org-scanner-tags nil
13815 "The current tag list while the tags scanner is running.")
13816 (defvar org-trust-scanner-tags nil
13817 "Should `org-get-tags-at' use the tags for the scanner.
13818 This is for internal dynamical scoping only.
13819 When this is non-nil, the function `org-get-tags-at' will return the value
13820 of `org-scanner-tags' instead of building the list by itself. This
13821 can lead to large speed-ups when the tags scanner is used in a file with
13822 many entries, and when the list of tags is retrieved, for example to
13823 obtain a list of properties. Building the tags list for each entry in such
13824 a file becomes an N^2 operation - but with this variable set, it scales
13825 as N.")
13827 (defun org-scan-tags (action matcher todo-only &optional start-level)
13828 "Sca headline tags with inheritance and produce output ACTION.
13830 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13831 or `agenda' to produce an entry list for an agenda view. It can also be
13832 a Lisp form or a function that should be called at each matched headline, in
13833 this case the return value is a list of all return values from these calls.
13835 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13836 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13837 only lines with a not-done TODO keyword are included in the output.
13838 This should be the same variable that was scoped into
13839 and set by `org-make-tags-matcher' when it constructed MATCHER.
13841 START-LEVEL can be a string with asterisks, reducing the scope to
13842 headlines matching this string."
13843 (require 'org-agenda)
13844 (let* ((re (concat "^"
13845 (if start-level
13846 ;; Get the correct level to match
13847 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13848 org-outline-regexp)
13849 " *\\(\\<\\("
13850 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13851 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13852 (props (list 'face 'default
13853 'done-face 'org-agenda-done
13854 'undone-face 'default
13855 'mouse-face 'highlight
13856 'org-not-done-regexp org-not-done-regexp
13857 'org-todo-regexp org-todo-regexp
13858 'org-complex-heading-regexp org-complex-heading-regexp
13859 'help-echo
13860 (format "mouse-2 or RET jump to org file %s"
13861 (abbreviate-file-name
13862 (or (buffer-file-name (buffer-base-buffer))
13863 (buffer-name (buffer-base-buffer)))))))
13864 (org-map-continue-from nil)
13865 lspos tags tags-list
13866 (tags-alist (list (cons 0 org-file-tags)))
13867 (llast 0) rtn rtn1 level category i txt
13868 todo marker entry priority)
13869 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13870 (setq action (list 'lambda nil action)))
13871 (save-excursion
13872 (goto-char (point-min))
13873 (when (eq action 'sparse-tree)
13874 (org-overview)
13875 (org-remove-occur-highlights))
13876 (while (let (case-fold-search)
13877 (re-search-forward re nil t))
13878 (setq org-map-continue-from nil)
13879 (catch :skip
13880 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13881 tags (if (match-end 4) (org-match-string-no-properties 4)))
13882 (goto-char (setq lspos (match-beginning 0)))
13883 (setq level (org-reduced-level (org-outline-level))
13884 category (org-get-category))
13885 (setq i llast llast level)
13886 ;; remove tag lists from same and sublevels
13887 (while (>= i level)
13888 (when (setq entry (assoc i tags-alist))
13889 (setq tags-alist (delete entry tags-alist)))
13890 (setq i (1- i)))
13891 ;; add the next tags
13892 (when tags
13893 (setq tags (org-split-string tags ":")
13894 tags-alist
13895 (cons (cons level tags) tags-alist)))
13896 ;; compile tags for current headline
13897 (setq tags-list
13898 (if org-use-tag-inheritance
13899 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13900 tags)
13901 org-scanner-tags tags-list)
13902 (when org-use-tag-inheritance
13903 (setcdr (car tags-alist)
13904 (mapcar (lambda (x)
13905 (setq x (copy-sequence x))
13906 (org-add-prop-inherited x))
13907 (cdar tags-alist))))
13908 (when (and tags org-use-tag-inheritance
13909 (or (not (eq t org-use-tag-inheritance))
13910 org-tags-exclude-from-inheritance))
13911 ;; selective inheritance, remove uninherited ones
13912 (setcdr (car tags-alist)
13913 (org-remove-uninherited-tags (cdar tags-alist))))
13914 (when (and
13916 ;; eval matcher only when the todo condition is OK
13917 (and (or (not todo-only) (member todo org-not-done-keywords))
13918 (let ((case-fold-search t) (org-trust-scanner-tags t))
13919 (eval matcher)))
13921 ;; Call the skipper, but return t if it does not skip,
13922 ;; so that the `and' form continues evaluating
13923 (progn
13924 (unless (eq action 'sparse-tree) (org-agenda-skip))
13927 ;; Check if timestamps are deselecting this entry
13928 (or (not todo-only)
13929 (and (member todo org-not-done-keywords)
13930 (or (not org-agenda-tags-todo-honor-ignore-options)
13931 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13933 ;; select this headline
13934 (cond
13935 ((eq action 'sparse-tree)
13936 (and org-highlight-sparse-tree-matches
13937 (org-get-heading) (match-end 0)
13938 (org-highlight-new-match
13939 (match-beginning 1) (match-end 1)))
13940 (org-show-context 'tags-tree))
13941 ((eq action 'agenda)
13942 (setq txt (org-agenda-format-item
13944 (concat
13945 (if (eq org-tags-match-list-sublevels 'indented)
13946 (make-string (1- level) ?.) "")
13947 (org-get-heading))
13948 level category
13949 tags-list)
13950 priority (org-get-priority txt))
13951 (goto-char lspos)
13952 (setq marker (org-agenda-new-marker))
13953 (org-add-props txt props
13954 'org-marker marker 'org-hd-marker marker 'org-category category
13955 'todo-state todo
13956 'priority priority 'type "tagsmatch")
13957 (push txt rtn))
13958 ((functionp action)
13959 (setq org-map-continue-from nil)
13960 (save-excursion
13961 (setq rtn1 (funcall action))
13962 (push rtn1 rtn)))
13963 (t (user-error "Invalid action")))
13965 ;; if we are to skip sublevels, jump to end of subtree
13966 (unless org-tags-match-list-sublevels
13967 (org-end-of-subtree t)
13968 (backward-char 1))))
13969 ;; Get the correct position from where to continue
13970 (if org-map-continue-from
13971 (goto-char org-map-continue-from)
13972 (and (= (point) lspos) (end-of-line 1)))))
13973 (when (and (eq action 'sparse-tree)
13974 (not org-sparse-tree-open-archived-trees))
13975 (org-hide-archived-subtrees (point-min) (point-max)))
13976 (nreverse rtn)))
13978 (defun org-remove-uninherited-tags (tags)
13979 "Remove all tags that are not inherited from the list TAGS."
13980 (cond
13981 ((eq org-use-tag-inheritance t)
13982 (if org-tags-exclude-from-inheritance
13983 (org-delete-all org-tags-exclude-from-inheritance tags)
13984 tags))
13985 ((not org-use-tag-inheritance) nil)
13986 ((stringp org-use-tag-inheritance)
13987 (delq nil (mapcar
13988 (lambda (x)
13989 (if (and (string-match org-use-tag-inheritance x)
13990 (not (member x org-tags-exclude-from-inheritance)))
13991 x nil))
13992 tags)))
13993 ((listp org-use-tag-inheritance)
13994 (delq nil (mapcar
13995 (lambda (x)
13996 (if (member x org-use-tag-inheritance) x nil))
13997 tags)))))
13999 (defun org-match-sparse-tree (&optional todo-only match)
14000 "Create a sparse tree according to tags string MATCH.
14001 MATCH can contain positive and negative selection of tags, like
14002 \"+WORK+URGENT-WITHBOSS\".
14003 If optional argument TODO-ONLY is non-nil, only select lines that are
14004 also TODO lines."
14005 (interactive "P")
14006 (org-agenda-prepare-buffers (list (current-buffer)))
14007 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14009 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14011 (defvar org-cached-props nil)
14012 (defun org-cached-entry-get (pom property)
14013 (if (or (eq t org-use-property-inheritance)
14014 (and (stringp org-use-property-inheritance)
14015 (string-match org-use-property-inheritance property))
14016 (and (listp org-use-property-inheritance)
14017 (member property org-use-property-inheritance)))
14018 ;; Caching is not possible, check it directly
14019 (org-entry-get pom property 'inherit)
14020 ;; Get all properties, so that we can do complicated checks easily
14021 (cdr (assoc property (or org-cached-props
14022 (setq org-cached-props
14023 (org-entry-properties pom)))))))
14025 (defun org-global-tags-completion-table (&optional files)
14026 "Return the list of all tags in all agenda buffer/files.
14027 Optional FILES argument is a list of files which can be used
14028 instead of the agenda files."
14029 (save-excursion
14030 (org-uniquify
14031 (delq nil
14032 (apply 'append
14033 (mapcar
14034 (lambda (file)
14035 (set-buffer (find-file-noselect file))
14036 (append (org-get-buffer-tags)
14037 (mapcar (lambda (x) (if (stringp (car-safe x))
14038 (list (car-safe x)) nil))
14039 org-tag-alist)))
14040 (if (and files (car files))
14041 files
14042 (org-agenda-files))))))))
14044 (defun org-make-tags-matcher (match)
14045 "Create the TAGS/TODO matcher form for the selection string MATCH.
14047 The variable `todo-only' is scoped dynamically into this function.
14048 It will be set to t if the matcher restricts matching to TODO entries,
14049 otherwise will not be touched.
14051 Returns a cons of the selection string MATCH and the constructed
14052 lisp form implementing the matcher. The matcher is to be evaluated
14053 at an Org entry, with point on the headline, and returns t if the
14054 entry matches the selection string MATCH. The returned lisp form
14055 references two variables with information about the entry, which
14056 must be bound around the form's evaluation: todo, the TODO keyword
14057 at the entry (or nil of none); and tags-list, the list of all tags
14058 at the entry including inherited ones. Additionally, the category
14059 of the entry (if any) must be specified as the text property
14060 'org-category on the headline.
14062 See also `org-scan-tags'.
14064 (declare (special todo-only))
14065 (unless (boundp 'todo-only)
14066 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14067 (unless match
14068 ;; Get a new match request, with completion against the global
14069 ;; tags table and the local tags in current buffer
14070 (let ((org-last-tags-completion-table
14071 (org-uniquify
14072 (delq nil (append (org-get-buffer-tags)
14073 (org-global-tags-completion-table))))))
14074 (setq match (org-completing-read-no-i
14075 "Match: " 'org-tags-completion-function nil nil nil
14076 'org-tags-history))))
14078 ;; Parse the string and create a lisp form
14079 (let ((match0 match)
14080 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14081 minus tag mm
14082 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14083 orterms term orlist re-p str-p level-p level-op time-p
14084 prop-p pn pv po gv rest (start 0) (ss 0))
14085 ;; Expand group tags
14086 (setq match (org-tags-expand match))
14088 ;; Check if there is a TODO part of this match, which would be the
14089 ;; part after a "/". TO make sure that this slash is not part of
14090 ;; a property value to be matched against, we also check that there
14091 ;; is no " after that slash.
14092 ;; First, find the last slash
14093 (while (string-match "/+" match ss)
14094 (setq start (match-beginning 0) ss (match-end 0)))
14095 (if (and (string-match "/+" match start)
14096 (not (save-match-data (string-match "\"" match start))))
14097 ;; match contains also a todo-matching request
14098 (progn
14099 (setq tagsmatch (substring match 0 (match-beginning 0))
14100 todomatch (substring match (match-end 0)))
14101 (if (string-match "^!" todomatch)
14102 (setq todo-only t todomatch (substring todomatch 1)))
14103 (if (string-match "^\\s-*$" todomatch)
14104 (setq todomatch nil)))
14105 ;; only matching tags
14106 (setq tagsmatch match todomatch nil))
14108 ;; Make the tags matcher
14109 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14110 (setq tagsmatcher t)
14111 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14112 (while (setq term (pop orterms))
14113 (while (and (equal (substring term -1) "\\") orterms)
14114 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14115 (while (string-match re term)
14116 (setq rest (substring term (match-end 0))
14117 minus (and (match-end 1)
14118 (equal (match-string 1 term) "-"))
14119 tag (save-match-data (replace-regexp-in-string
14120 "\\\\-" "-"
14121 (match-string 2 term)))
14122 re-p (equal (string-to-char tag) ?{)
14123 level-p (match-end 4)
14124 prop-p (match-end 5)
14125 mm (cond
14126 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14127 (level-p
14128 (setq level-op (org-op-to-function (match-string 3 term)))
14129 `(,level-op level ,(string-to-number
14130 (match-string 4 term))))
14131 (prop-p
14132 (setq pn (match-string 5 term)
14133 po (match-string 6 term)
14134 pv (match-string 7 term)
14135 re-p (equal (string-to-char pv) ?{)
14136 str-p (equal (string-to-char pv) ?\")
14137 time-p (save-match-data
14138 (string-match "^\"[[<].*[]>]\"$" pv))
14139 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14140 (if time-p (setq pv (org-matcher-time pv)))
14141 (setq po (org-op-to-function po (if time-p 'time str-p)))
14142 (cond
14143 ((equal pn "CATEGORY")
14144 (setq gv '(get-text-property (point) 'org-category)))
14145 ((equal pn "TODO")
14146 (setq gv 'todo))
14148 (setq gv `(org-cached-entry-get nil ,pn))))
14149 (if re-p
14150 (if (eq po 'org<>)
14151 `(not (string-match ,pv (or ,gv "")))
14152 `(string-match ,pv (or ,gv "")))
14153 (if str-p
14154 `(,po (or ,gv "") ,pv)
14155 `(,po (string-to-number (or ,gv ""))
14156 ,(string-to-number pv) ))))
14157 (t `(member ,tag tags-list)))
14158 mm (if minus (list 'not mm) mm)
14159 term rest)
14160 (push mm tagsmatcher))
14161 (push (if (> (length tagsmatcher) 1)
14162 (cons 'and tagsmatcher)
14163 (car tagsmatcher))
14164 orlist)
14165 (setq tagsmatcher nil))
14166 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14167 (setq tagsmatcher
14168 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14169 ;; Make the todo matcher
14170 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14171 (setq todomatcher t)
14172 (setq orterms (org-split-string todomatch "|") orlist nil)
14173 (while (setq term (pop orterms))
14174 (while (string-match re term)
14175 (setq minus (and (match-end 1)
14176 (equal (match-string 1 term) "-"))
14177 kwd (match-string 2 term)
14178 re-p (equal (string-to-char kwd) ?{)
14179 term (substring term (match-end 0))
14180 mm (if re-p
14181 `(string-match ,(substring kwd 1 -1) todo)
14182 (list 'equal 'todo kwd))
14183 mm (if minus (list 'not mm) mm))
14184 (push mm todomatcher))
14185 (push (if (> (length todomatcher) 1)
14186 (cons 'and todomatcher)
14187 (car todomatcher))
14188 orlist)
14189 (setq todomatcher nil))
14190 (setq todomatcher (if (> (length orlist) 1)
14191 (cons 'or orlist) (car orlist))))
14193 ;; Return the string and lisp forms of the matcher
14194 (setq matcher (if todomatcher
14195 (list 'and tagsmatcher todomatcher)
14196 tagsmatcher))
14197 (when todo-only
14198 (setq matcher (list 'and '(member todo org-not-done-keywords)
14199 matcher)))
14200 (cons match0 matcher)))
14202 (defun org-tags-expand (match &optional single-as-list downcased)
14203 "Expand group tags in MATCH.
14205 This replaces every group tag in MATCH with a regexp tag search.
14206 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14207 will be replaced like this:
14209 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14210 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14211 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14213 Replacing by a regexp preserves the structure of the match.
14214 E.g., this expansion
14216 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14218 will match anything tagged with \"Lab\" and \"Home\", or tagged
14219 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14221 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14222 assumed to be a single group tag, and the function will return
14223 the list of tags in this group.
14225 When DOWNCASE is non-nil, expand downcased TAGS."
14226 (if org-group-tags
14227 (let* ((case-fold-search t)
14228 (stable org-mode-syntax-table)
14229 (tal (or org-tag-groups-alist-for-agenda
14230 org-tag-groups-alist))
14231 (tal (if downcased
14232 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14233 (tml (mapcar 'car tal))
14234 (rtnmatch match) rpl)
14235 ;; @ and _ are allowed as word-components in tags
14236 (modify-syntax-entry ?@ "w" stable)
14237 (modify-syntax-entry ?_ "w" stable)
14238 (while (and tml
14239 (with-syntax-table stable
14240 (string-match
14241 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14242 (regexp-opt tml) "\\>\\)") rtnmatch)))
14243 (let* ((dir (match-string 1 rtnmatch))
14244 (tag (match-string 2 rtnmatch))
14245 (tag (if downcased (downcase tag) tag)))
14246 (setq tml (delete tag tml))
14247 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14248 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14249 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14250 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14251 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14252 (if single-as-list
14253 (or (reverse rpl) (list rtnmatch))
14254 rtnmatch))
14255 (if single-as-list (list (if downcased (downcase match) match))
14256 match)))
14258 (defun org-op-to-function (op &optional stringp)
14259 "Turn an operator into the appropriate function."
14260 (setq op
14261 (cond
14262 ((equal op "<" ) '(< string< org-time<))
14263 ((equal op ">" ) '(> org-string> org-time>))
14264 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14265 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14266 ((member op '("=" "==")) '(= string= org-time=))
14267 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14268 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14270 (defun org<> (a b) (not (= a b)))
14271 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14272 (defun org-string>= (a b) (not (string< a b)))
14273 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14274 (defun org-string<> (a b) (not (string= a b)))
14275 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14276 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14277 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14278 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14279 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14280 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14281 (defun org-2ft (s)
14282 "Convert S to a floating point time.
14283 If S is already a number, just return it. If it is a string, parse
14284 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14285 (cond
14286 ((numberp s) s)
14287 ((stringp s)
14288 (condition-case nil
14289 (float-time (apply 'encode-time (org-parse-time-string s)))
14290 (error 0.)))
14291 (t 0.)))
14293 (defun org-time-today ()
14294 "Time in seconds today at 0:00.
14295 Returns the float number of seconds since the beginning of the
14296 epoch to the beginning of today (00:00)."
14297 (float-time (apply 'encode-time
14298 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14300 (defun org-matcher-time (s)
14301 "Interpret a time comparison value."
14302 (save-match-data
14303 (cond
14304 ((string= s "<now>") (float-time))
14305 ((string= s "<today>") (org-time-today))
14306 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14307 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14308 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14309 (+ (org-time-today)
14310 (* (string-to-number (match-string 1 s))
14311 (cdr (assoc (match-string 2 s)
14312 '(("d" . 86400.0) ("w" . 604800.0)
14313 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14314 (t (org-2ft s)))))
14316 (defun org-match-any-p (re list)
14317 "Does re match any element of list?"
14318 (setq list (mapcar (lambda (x) (string-match re x)) list))
14319 (delq nil list))
14321 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14322 (defvar org-tags-overlay (make-overlay 1 1))
14323 (org-detach-overlay org-tags-overlay)
14325 (defun org-get-local-tags-at (&optional pos)
14326 "Get a list of tags defined in the current headline."
14327 (org-get-tags-at pos 'local))
14329 (defun org-get-local-tags ()
14330 "Get a list of tags defined in the current headline."
14331 (org-get-tags-at nil 'local))
14333 (defun org-get-tags-at (&optional pos local)
14334 "Get a list of all headline tags applicable at POS.
14335 POS defaults to point. If tags are inherited, the list contains
14336 the targets in the same sequence as the headlines appear, i.e.
14337 the tags of the current headline come last.
14338 When LOCAL is non-nil, only return tags from the current headline,
14339 ignore inherited ones."
14340 (interactive)
14341 (if (and org-trust-scanner-tags
14342 (or (not pos) (equal pos (point)))
14343 (not local))
14344 org-scanner-tags
14345 (let (tags ltags lastpos parent)
14346 (save-excursion
14347 (save-restriction
14348 (widen)
14349 (goto-char (or pos (point)))
14350 (save-match-data
14351 (catch 'done
14352 (condition-case nil
14353 (progn
14354 (org-back-to-heading t)
14355 (while (not (equal lastpos (point)))
14356 (setq lastpos (point))
14357 (when (looking-at
14358 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14359 (setq ltags (org-split-string
14360 (org-match-string-no-properties 1) ":"))
14361 (when parent
14362 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14363 (setq tags (append
14364 (if parent
14365 (org-remove-uninherited-tags ltags)
14366 ltags)
14367 tags)))
14368 (or org-use-tag-inheritance (throw 'done t))
14369 (if local (throw 'done t))
14370 (or (org-up-heading-safe) (error nil))
14371 (setq parent t)))
14372 (error nil)))))
14373 (if local
14374 tags
14375 (reverse (delete-dups
14376 (reverse (append
14377 (org-remove-uninherited-tags
14378 org-file-tags) tags)))))))))
14380 (defun org-add-prop-inherited (s)
14381 (add-text-properties 0 (length s) '(inherited t) s)
14384 (defun org-toggle-tag (tag &optional onoff)
14385 "Toggle the tag TAG for the current line.
14386 If ONOFF is `on' or `off', don't toggle but set to this state."
14387 (let (res current)
14388 (save-excursion
14389 (org-back-to-heading t)
14390 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14391 (point-at-eol) t)
14392 (progn
14393 (setq current (match-string 1))
14394 (replace-match ""))
14395 (setq current ""))
14396 (setq current (nreverse (org-split-string current ":")))
14397 (cond
14398 ((eq onoff 'on)
14399 (setq res t)
14400 (or (member tag current) (push tag current)))
14401 ((eq onoff 'off)
14402 (or (not (member tag current)) (setq current (delete tag current))))
14403 (t (if (member tag current)
14404 (setq current (delete tag current))
14405 (setq res t)
14406 (push tag current))))
14407 (end-of-line 1)
14408 (if current
14409 (progn
14410 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14411 (org-set-tags nil t))
14412 (delete-horizontal-space))
14413 (run-hooks 'org-after-tags-change-hook))
14414 res))
14416 (defun org-align-tags-here (to-col)
14417 ;; Assumes that this is a headline
14418 "Align tags on the current headline to TO-COL."
14419 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14420 (beginning-of-line 1)
14421 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14422 (< pos (match-beginning 2)))
14423 (progn
14424 (setq tags-l (- (match-end 2) (match-beginning 2)))
14425 (goto-char (match-beginning 1))
14426 (insert " ")
14427 (delete-region (point) (1+ (match-beginning 2)))
14428 (setq ncol (max (current-column)
14429 (1+ col)
14430 (if (> to-col 0)
14431 to-col
14432 (- (abs to-col) tags-l))))
14433 (setq p (point))
14434 (insert (make-string (- ncol (current-column)) ?\ ))
14435 (setq ncol (current-column))
14436 (when indent-tabs-mode (tabify p (point-at-eol)))
14437 (org-move-to-column (min ncol col)))
14438 (goto-char pos))))
14440 (defun org-set-tags-command (&optional arg just-align)
14441 "Call the set-tags command for the current entry."
14442 (interactive "P")
14443 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14444 (org-set-tags arg just-align)
14445 (save-excursion
14446 (unless (and (org-region-active-p)
14447 org-loop-over-headlines-in-active-region)
14448 (org-back-to-heading t))
14449 (org-set-tags arg just-align))))
14451 (defun org-set-tags-to (data)
14452 "Set the tags of the current entry to DATA, replacing the current tags.
14453 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14454 If DATA is nil or the empty string, any tags will be removed."
14455 (interactive "sTags: ")
14456 (setq data
14457 (cond
14458 ((eq data nil) "")
14459 ((equal data "") "")
14460 ((stringp data)
14461 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14462 ":"))
14463 ((listp data)
14464 (concat ":" (mapconcat 'identity data ":") ":"))))
14465 (when data
14466 (save-excursion
14467 (org-back-to-heading t)
14468 (when (looking-at org-complex-heading-regexp)
14469 (if (match-end 5)
14470 (progn
14471 (goto-char (match-beginning 5))
14472 (insert data)
14473 (delete-region (point) (point-at-eol))
14474 (org-set-tags nil 'align))
14475 (goto-char (point-at-eol))
14476 (insert " " data)
14477 (org-set-tags nil 'align)))
14478 (beginning-of-line 1)
14479 (if (looking-at ".*?\\([ \t]+\\)$")
14480 (delete-region (match-beginning 1) (match-end 1))))))
14482 (defun org-align-all-tags ()
14483 "Align the tags i all headings."
14484 (interactive)
14485 (save-excursion
14486 (or (ignore-errors (org-back-to-heading t))
14487 (outline-next-heading))
14488 (if (org-at-heading-p)
14489 (org-set-tags t)
14490 (message "No headings"))))
14492 (defvar org-indent-indentation-per-level)
14493 (defun org-set-tags (&optional arg just-align)
14494 "Set the tags for the current headline.
14495 With prefix ARG, realign all tags in headings in the current buffer.
14496 When JUST-ALIGN is non-nil, only align tags."
14497 (interactive "P")
14498 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14499 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14500 'region-start-level 'region))
14501 org-loop-over-headlines-in-active-region)
14502 (org-map-entries
14503 ;; We don't use ARG and JUST-ALIGN here because these args
14504 ;; are not useful when looping over headlines.
14505 `(org-set-tags)
14506 org-loop-over-headlines-in-active-region
14507 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14508 (let* ((re org-outline-regexp-bol)
14509 (current (unless arg (org-get-tags-string)))
14510 (col (current-column))
14511 (org-setting-tags t)
14512 table current-tags inherited-tags ; computed below when needed
14513 tags p0 c0 c1 rpl di tc level)
14514 (if arg
14515 (save-excursion
14516 (goto-char (point-min))
14517 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14518 (while (re-search-forward re nil t)
14519 (org-set-tags nil t)
14520 (end-of-line 1)))
14521 (message "All tags realigned to column %d" org-tags-column))
14522 (if just-align
14523 (setq tags current)
14524 ;; Get a new set of tags from the user
14525 (save-excursion
14526 (setq table (append org-tag-persistent-alist
14527 (or org-tag-alist (org-get-buffer-tags))
14528 (and
14529 org-complete-tags-always-offer-all-agenda-tags
14530 (org-global-tags-completion-table
14531 (org-agenda-files))))
14532 org-last-tags-completion-table table
14533 current-tags (org-split-string current ":")
14534 inherited-tags (nreverse
14535 (nthcdr (length current-tags)
14536 (nreverse (org-get-tags-at))))
14537 tags
14538 (if (or (eq t org-use-fast-tag-selection)
14539 (and org-use-fast-tag-selection
14540 (delq nil (mapcar 'cdr table))))
14541 (org-fast-tag-selection
14542 current-tags inherited-tags table
14543 (if org-fast-tag-selection-include-todo
14544 org-todo-key-alist))
14545 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14546 (org-trim
14547 (org-icompleting-read "Tags: "
14548 'org-tags-completion-function
14549 nil nil current 'org-tags-history))))))
14550 (while (string-match "[-+&]+" tags)
14551 ;; No boolean logic, just a list
14552 (setq tags (replace-match ":" t t tags))))
14554 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14556 (if org-tags-sort-function
14557 (setq tags (mapconcat 'identity
14558 (sort (org-split-string
14559 tags (org-re "[^[:alnum:]_@#%]+"))
14560 org-tags-sort-function) ":")))
14562 (if (string-match "\\`[\t ]*\\'" tags)
14563 (setq tags "")
14564 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14565 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14567 ;; Insert new tags at the correct column
14568 (beginning-of-line 1)
14569 (setq level (or (and (looking-at org-outline-regexp)
14570 (- (match-end 0) (point) 1))
14572 (cond
14573 ((and (equal current "") (equal tags "")))
14574 ((re-search-forward
14575 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14576 (point-at-eol) t)
14577 (if (equal tags "")
14578 (setq rpl "")
14579 (goto-char (match-beginning 0))
14580 (setq c0 (current-column)
14581 ;; compute offset for the case of org-indent-mode active
14582 di (if (org-bound-and-true-p org-indent-mode)
14583 (* (1- org-indent-indentation-per-level) (1- level))
14585 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14586 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14587 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14588 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14589 (replace-match rpl t t)
14590 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14591 tags)
14592 (t (error "Tags alignment failed")))
14593 (org-move-to-column col)
14594 (unless just-align
14595 (run-hooks 'org-after-tags-change-hook))))))
14597 (defun org-change-tag-in-region (beg end tag off)
14598 "Add or remove TAG for each entry in the region.
14599 This works in the agenda, and also in an org-mode buffer."
14600 (interactive
14601 (list (region-beginning) (region-end)
14602 (let ((org-last-tags-completion-table
14603 (if (derived-mode-p 'org-mode)
14604 (org-uniquify
14605 (delq nil (append (org-get-buffer-tags)
14606 (org-global-tags-completion-table))))
14607 (org-global-tags-completion-table))))
14608 (org-icompleting-read
14609 "Tag: " 'org-tags-completion-function nil nil nil
14610 'org-tags-history))
14611 (progn
14612 (message "[s]et or [r]emove? ")
14613 (equal (read-char-exclusive) ?r))))
14614 (if (fboundp 'deactivate-mark) (deactivate-mark))
14615 (let ((agendap (equal major-mode 'org-agenda-mode))
14616 l1 l2 m buf pos newhead (cnt 0))
14617 (goto-char end)
14618 (setq l2 (1- (org-current-line)))
14619 (goto-char beg)
14620 (setq l1 (org-current-line))
14621 (loop for l from l1 to l2 do
14622 (org-goto-line l)
14623 (setq m (get-text-property (point) 'org-hd-marker))
14624 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14625 (and agendap m))
14626 (setq buf (if agendap (marker-buffer m) (current-buffer))
14627 pos (if agendap m (point)))
14628 (with-current-buffer buf
14629 (save-excursion
14630 (save-restriction
14631 (goto-char pos)
14632 (setq cnt (1+ cnt))
14633 (org-toggle-tag tag (if off 'off 'on))
14634 (setq newhead (org-get-heading)))))
14635 (and agendap (org-agenda-change-all-lines newhead m))))
14636 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14638 (defun org-tags-completion-function (string predicate &optional flag)
14639 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14640 (confirm (lambda (x) (stringp (car x)))))
14641 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14642 (setq s1 (match-string 1 string)
14643 s2 (match-string 2 string))
14644 (setq s1 "" s2 string))
14645 (cond
14646 ((eq flag nil)
14647 ;; try completion
14648 (setq rtn (try-completion s2 ctable confirm))
14649 (if (stringp rtn)
14650 (setq rtn
14651 (concat s1 s2 (substring rtn (length s2))
14652 (if (and org-add-colon-after-tag-completion
14653 (assoc rtn ctable))
14654 ":" ""))))
14655 rtn)
14656 ((eq flag t)
14657 ;; all-completions
14658 (all-completions s2 ctable confirm))
14659 ((eq flag 'lambda)
14660 ;; exact match?
14661 (assoc s2 ctable)))))
14663 (defun org-fast-tag-insert (kwd tags face &optional end)
14664 "Insert KDW, and the TAGS, the latter with face FACE.
14665 Also insert END."
14666 (insert (format "%-12s" (concat kwd ":"))
14667 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14668 (or end "")))
14670 (defun org-fast-tag-show-exit (flag)
14671 (save-excursion
14672 (org-goto-line 3)
14673 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14674 (replace-match ""))
14675 (when flag
14676 (end-of-line 1)
14677 (org-move-to-column (- (window-width) 19) t)
14678 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14680 (defun org-set-current-tags-overlay (current prefix)
14681 "Add an overlay to CURRENT tag with PREFIX."
14682 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14683 (if (featurep 'xemacs)
14684 (org-overlay-display org-tags-overlay (concat prefix s)
14685 'secondary-selection)
14686 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14687 (org-overlay-display org-tags-overlay (concat prefix s)))))
14689 (defvar org-last-tag-selection-key nil)
14690 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14691 "Fast tag selection with single keys.
14692 CURRENT is the current list of tags in the headline, INHERITED is the
14693 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14694 possibly with grouping information. TODO-TABLE is a similar table with
14695 TODO keywords, should these have keys assigned to them.
14696 If the keys are nil, a-z are automatically assigned.
14697 Returns the new tags string, or nil to not change the current settings."
14698 (let* ((fulltable (append table todo-table))
14699 (maxlen (apply 'max (mapcar
14700 (lambda (x)
14701 (if (stringp (car x)) (string-width (car x)) 0))
14702 fulltable)))
14703 (buf (current-buffer))
14704 (expert (eq org-fast-tag-selection-single-key 'expert))
14705 (buffer-tags nil)
14706 (fwidth (+ maxlen 3 1 3))
14707 (ncol (/ (- (window-width) 4) fwidth))
14708 (i-face 'org-done)
14709 (c-face 'org-todo)
14710 tg cnt e c char c1 c2 ntable tbl rtn
14711 ov-start ov-end ov-prefix
14712 (exit-after-next org-fast-tag-selection-single-key)
14713 (done-keywords org-done-keywords)
14714 groups ingroup)
14715 (save-excursion
14716 (beginning-of-line 1)
14717 (if (looking-at
14718 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14719 (setq ov-start (match-beginning 1)
14720 ov-end (match-end 1)
14721 ov-prefix "")
14722 (setq ov-start (1- (point-at-eol))
14723 ov-end (1+ ov-start))
14724 (skip-chars-forward "^\n\r")
14725 (setq ov-prefix
14726 (concat
14727 (buffer-substring (1- (point)) (point))
14728 (if (> (current-column) org-tags-column)
14730 (make-string (- org-tags-column (current-column)) ?\ ))))))
14731 (move-overlay org-tags-overlay ov-start ov-end)
14732 (save-window-excursion
14733 (if expert
14734 (set-buffer (get-buffer-create " *Org tags*"))
14735 (delete-other-windows)
14736 (split-window-vertically)
14737 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14738 (erase-buffer)
14739 (org-set-local 'org-done-keywords done-keywords)
14740 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14741 (org-fast-tag-insert "Current" current c-face "\n\n")
14742 (org-fast-tag-show-exit exit-after-next)
14743 (org-set-current-tags-overlay current ov-prefix)
14744 (setq tbl fulltable char ?a cnt 0)
14745 (while (setq e (pop tbl))
14746 (cond
14747 ((equal (car e) :startgroup)
14748 (push '() groups) (setq ingroup t)
14749 (when (not (= cnt 0))
14750 (setq cnt 0)
14751 (insert "\n"))
14752 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14753 ((equal (car e) :endgroup)
14754 (setq ingroup nil cnt 0)
14755 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14756 ((equal e '(:newline))
14757 (when (not (= cnt 0))
14758 (setq cnt 0)
14759 (insert "\n")
14760 (setq e (car tbl))
14761 (while (equal (car tbl) '(:newline))
14762 (insert "\n")
14763 (setq tbl (cdr tbl)))))
14764 ((equal e '(:grouptags)) nil)
14766 (setq tg (copy-sequence (car e)) c2 nil)
14767 (if (cdr e)
14768 (setq c (cdr e))
14769 ;; automatically assign a character.
14770 (setq c1 (string-to-char
14771 (downcase (substring
14772 tg (if (= (string-to-char tg) ?@) 1 0)))))
14773 (if (or (rassoc c1 ntable) (rassoc c1 table))
14774 (while (or (rassoc char ntable) (rassoc char table))
14775 (setq char (1+ char)))
14776 (setq c2 c1))
14777 (setq c (or c2 char)))
14778 (if ingroup (push tg (car groups)))
14779 (setq tg (org-add-props tg nil 'face
14780 (cond
14781 ((not (assoc tg table))
14782 (org-get-todo-face tg))
14783 ((member tg current) c-face)
14784 ((member tg inherited) i-face))))
14785 (if (equal (caar tbl) :grouptags)
14786 (org-add-props tg nil 'face 'org-tag-group))
14787 (if (and (= cnt 0) (not ingroup)) (insert " "))
14788 (insert "[" c "] " tg (make-string
14789 (- fwidth 4 (length tg)) ?\ ))
14790 (push (cons tg c) ntable)
14791 (when (= (setq cnt (1+ cnt)) ncol)
14792 (insert "\n")
14793 (if ingroup (insert " "))
14794 (setq cnt 0)))))
14795 (setq ntable (nreverse ntable))
14796 (insert "\n")
14797 (goto-char (point-min))
14798 (if (not expert) (org-fit-window-to-buffer))
14799 (setq rtn
14800 (catch 'exit
14801 (while t
14802 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14803 (if (not groups) "no " "")
14804 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14805 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14806 (setq org-last-tag-selection-key c)
14807 (cond
14808 ((= c ?\r) (throw 'exit t))
14809 ((= c ?!)
14810 (setq groups (not groups))
14811 (goto-char (point-min))
14812 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14813 ((= c ?\C-c)
14814 (if (not expert)
14815 (org-fast-tag-show-exit
14816 (setq exit-after-next (not exit-after-next)))
14817 (setq expert nil)
14818 (delete-other-windows)
14819 (set-window-buffer (split-window-vertically) " *Org tags*")
14820 (org-switch-to-buffer-other-window " *Org tags*")
14821 (org-fit-window-to-buffer)))
14822 ((or (= c ?\C-g)
14823 (and (= c ?q) (not (rassoc c ntable))))
14824 (org-detach-overlay org-tags-overlay)
14825 (setq quit-flag t))
14826 ((= c ?\ )
14827 (setq current nil)
14828 (if exit-after-next (setq exit-after-next 'now)))
14829 ((= c ?\t)
14830 (condition-case nil
14831 (setq tg (org-icompleting-read
14832 "Tag: "
14833 (or buffer-tags
14834 (with-current-buffer buf
14835 (org-get-buffer-tags)))))
14836 (quit (setq tg "")))
14837 (when (string-match "\\S-" tg)
14838 (add-to-list 'buffer-tags (list tg))
14839 (if (member tg current)
14840 (setq current (delete tg current))
14841 (push tg current)))
14842 (if exit-after-next (setq exit-after-next 'now)))
14843 ((setq e (rassoc c todo-table) tg (car e))
14844 (with-current-buffer buf
14845 (save-excursion (org-todo tg)))
14846 (if exit-after-next (setq exit-after-next 'now)))
14847 ((setq e (rassoc c ntable) tg (car e))
14848 (if (member tg current)
14849 (setq current (delete tg current))
14850 (loop for g in groups do
14851 (if (member tg g)
14852 (mapc (lambda (x)
14853 (setq current (delete x current)))
14854 g)))
14855 (push tg current))
14856 (if exit-after-next (setq exit-after-next 'now))))
14858 ;; Create a sorted list
14859 (setq current
14860 (sort current
14861 (lambda (a b)
14862 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14863 (if (eq exit-after-next 'now) (throw 'exit t))
14864 (goto-char (point-min))
14865 (beginning-of-line 2)
14866 (delete-region (point) (point-at-eol))
14867 (org-fast-tag-insert "Current" current c-face)
14868 (org-set-current-tags-overlay current ov-prefix)
14869 (while (re-search-forward
14870 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14871 (setq tg (match-string 1))
14872 (add-text-properties
14873 (match-beginning 1) (match-end 1)
14874 (list 'face
14875 (cond
14876 ((member tg current) c-face)
14877 ((member tg inherited) i-face)
14878 (t (get-text-property (match-beginning 1) 'face))))))
14879 (goto-char (point-min)))))
14880 (org-detach-overlay org-tags-overlay)
14881 (if rtn
14882 (mapconcat 'identity current ":")
14883 nil))))
14885 (defun org-get-tags-string ()
14886 "Get the TAGS string in the current headline."
14887 (unless (org-at-heading-p t)
14888 (user-error "Not on a heading"))
14889 (save-excursion
14890 (beginning-of-line 1)
14891 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14892 (org-match-string-no-properties 1)
14893 "")))
14895 (defun org-get-tags ()
14896 "Get the list of tags specified in the current headline."
14897 (org-split-string (org-get-tags-string) ":"))
14899 (defun org-get-buffer-tags ()
14900 "Get a table of all tags used in the buffer, for completion."
14901 (let (tags)
14902 (save-excursion
14903 (goto-char (point-min))
14904 (while (re-search-forward
14905 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14906 (when (equal (char-after (point-at-bol 0)) ?*)
14907 (mapc (lambda (x) (add-to-list 'tags x))
14908 (org-split-string (org-match-string-no-properties 1) ":")))))
14909 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14910 (mapcar 'list tags)))
14912 ;;;; The mapping API
14914 (defun org-map-entries (func &optional match scope &rest skip)
14915 "Call FUNC at each headline selected by MATCH in SCOPE.
14917 FUNC is a function or a lisp form. The function will be called without
14918 arguments, with the cursor positioned at the beginning of the headline.
14919 The return values of all calls to the function will be collected and
14920 returned as a list.
14922 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14923 does not need to preserve point. After evaluation, the cursor will be
14924 moved to the end of the line (presumably of the headline of the
14925 processed entry) and search continues from there. Under some
14926 circumstances, this may not produce the wanted results. For example,
14927 if you have removed (e.g. archived) the current (sub)tree it could
14928 mean that the next entry will be skipped entirely. In such cases, you
14929 can specify the position from where search should continue by making
14930 FUNC set the variable `org-map-continue-from' to the desired buffer
14931 position.
14933 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14934 Only headlines that are matched by this query will be considered during
14935 the iteration. When MATCH is nil or t, all headlines will be
14936 visited by the iteration.
14938 SCOPE determines the scope of this command. It can be any of:
14940 nil The current buffer, respecting the restriction if any
14941 tree The subtree started with the entry at point
14942 region The entries within the active region, if any
14943 region-start-level
14944 The entries within the active region, but only those at
14945 the same level than the first one.
14946 file The current buffer, without restriction
14947 file-with-archives
14948 The current buffer, and any archives associated with it
14949 agenda All agenda files
14950 agenda-with-archives
14951 All agenda files with any archive files associated with them
14952 \(file1 file2 ...)
14953 If this is a list, all files in the list will be scanned
14955 The remaining args are treated as settings for the skipping facilities of
14956 the scanner. The following items can be given here:
14958 archive skip trees with the archive tag
14959 comment skip trees with the COMMENT keyword
14960 function or Emacs Lisp form:
14961 will be used as value for `org-agenda-skip-function', so
14962 whenever the function returns a position, FUNC will not be
14963 called for that entry and search will continue from the
14964 position returned
14966 If your function needs to retrieve the tags including inherited tags
14967 at the *current* entry, you can use the value of the variable
14968 `org-scanner-tags' which will be much faster than getting the value
14969 with `org-get-tags-at'. If your function gets properties with
14970 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14971 to t around the call to `org-entry-properties' to get the same speedup.
14972 Note that if your function moves around to retrieve tags and properties at
14973 a *different* entry, you cannot use these techniques."
14974 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14975 (not (org-region-active-p)))
14976 (let* ((org-agenda-archives-mode nil) ; just to make sure
14977 (org-agenda-skip-archived-trees (memq 'archive skip))
14978 (org-agenda-skip-comment-trees (memq 'comment skip))
14979 (org-agenda-skip-function
14980 (car (org-delete-all '(comment archive) skip)))
14981 (org-tags-match-list-sublevels t)
14982 (start-level (eq scope 'region-start-level))
14983 matcher file res
14984 org-todo-keywords-for-agenda
14985 org-done-keywords-for-agenda
14986 org-todo-keyword-alist-for-agenda
14987 org-drawers-for-agenda
14988 org-tag-alist-for-agenda
14989 todo-only)
14991 (cond
14992 ((eq match t) (setq matcher t))
14993 ((eq match nil) (setq matcher t))
14994 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14996 (save-excursion
14997 (save-restriction
14998 (cond ((eq scope 'tree)
14999 (org-back-to-heading t)
15000 (org-narrow-to-subtree)
15001 (setq scope nil))
15002 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15003 (org-region-active-p))
15004 ;; If needed, set start-level to a string like "2"
15005 (when start-level
15006 (save-excursion
15007 (goto-char (region-beginning))
15008 (unless (org-at-heading-p) (outline-next-heading))
15009 (setq start-level (org-current-level))))
15010 (narrow-to-region (region-beginning)
15011 (save-excursion
15012 (goto-char (region-end))
15013 (unless (and (bolp) (org-at-heading-p))
15014 (outline-next-heading))
15015 (point)))
15016 (setq scope nil)))
15018 (if (not scope)
15019 (progn
15020 (org-agenda-prepare-buffers
15021 (list (buffer-file-name (current-buffer))))
15022 (setq res (org-scan-tags func matcher todo-only start-level)))
15023 ;; Get the right scope
15024 (cond
15025 ((and scope (listp scope) (symbolp (car scope)))
15026 (setq scope (eval scope)))
15027 ((eq scope 'agenda)
15028 (setq scope (org-agenda-files t)))
15029 ((eq scope 'agenda-with-archives)
15030 (setq scope (org-agenda-files t))
15031 (setq scope (org-add-archive-files scope)))
15032 ((eq scope 'file)
15033 (setq scope (list (buffer-file-name))))
15034 ((eq scope 'file-with-archives)
15035 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15036 (org-agenda-prepare-buffers scope)
15037 (while (setq file (pop scope))
15038 (with-current-buffer (org-find-base-buffer-visiting file)
15039 (save-excursion
15040 (save-restriction
15041 (widen)
15042 (goto-char (point-min))
15043 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15044 res)))
15046 ;;;; Properties
15048 ;;; Setting and retrieving properties
15050 (defconst org-special-properties
15051 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15052 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15053 "The special properties valid in Org-mode.
15055 These are properties that are not defined in the property drawer,
15056 but in some other way.")
15058 (defconst org-default-properties
15059 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15060 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15061 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15062 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15063 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15064 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15065 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15066 "Some properties that are used by Org-mode for various purposes.
15067 Being in this list makes sure that they are offered for completion.")
15069 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15070 "Regular expression matching the first line of a property drawer.")
15072 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15073 "Regular expression matching the last line of a property drawer.")
15075 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15076 "Regular expression matching the first line of a property drawer.")
15078 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15079 "Regular expression matching the first line of a property drawer.")
15081 (defconst org-property-drawer-re
15082 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15083 org-property-end-re "\\)\n?")
15084 "Matches an entire property drawer.")
15086 (defconst org-clock-drawer-re
15087 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15088 org-property-end-re "\\)\n?")
15089 "Matches an entire clock drawer.")
15091 (defun org-property-action ()
15092 "Do an action on properties."
15093 (interactive)
15094 (let (c)
15095 (org-at-property-p)
15096 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15097 (setq c (read-char-exclusive))
15098 (cond
15099 ((equal c ?s)
15100 (call-interactively 'org-set-property))
15101 ((equal c ?d)
15102 (call-interactively 'org-delete-property))
15103 ((equal c ?D)
15104 (call-interactively 'org-delete-property-globally))
15105 ((equal c ?c)
15106 (call-interactively 'org-compute-property-at-point))
15107 (t (user-error "No such property action %c" c)))))
15109 (defun org-inc-effort ()
15110 "Increment the value of the effort property in the current entry."
15111 (interactive)
15112 (org-set-effort nil t))
15114 (defvar org-clock-effort) ;; Defined in org-clock.el
15115 (defvar org-clock-current-task) ;; Defined in org-clock.el
15116 (defun org-set-effort (&optional value increment)
15117 "Set the effort property of the current entry.
15118 With numerical prefix arg, use the nth allowed value, 0 stands for the
15119 10th allowed value.
15121 When INCREMENT is non-nil, set the property to the next allowed value."
15122 (interactive "P")
15123 (if (equal value 0) (setq value 10))
15124 (let* ((completion-ignore-case t)
15125 (prop org-effort-property)
15126 (cur (org-entry-get nil prop))
15127 (allowed (org-property-get-allowed-values nil prop 'table))
15128 (existing (mapcar 'list (org-property-values prop)))
15129 (heading (nth 4 (org-heading-components)))
15131 (val (cond
15132 ((stringp value) value)
15133 ((and allowed (integerp value))
15134 (or (car (nth (1- value) allowed))
15135 (car (org-last allowed))))
15136 ((and allowed increment)
15137 (or (caadr (member (list cur) allowed))
15138 (user-error "Allowed effort values are not set")))
15139 (allowed
15140 (message "Select 1-9,0, [RET%s]: %s"
15141 (if cur (concat "=" cur) "")
15142 (mapconcat 'car allowed " "))
15143 (setq rpl (read-char-exclusive))
15144 (if (equal rpl ?\r)
15146 (setq rpl (- rpl ?0))
15147 (if (equal rpl 0) (setq rpl 10))
15148 (if (and (> rpl 0) (<= rpl (length allowed)))
15149 (car (nth (1- rpl) allowed))
15150 (org-completing-read "Effort: " allowed nil))))
15152 (let (org-completion-use-ido org-completion-use-iswitchb)
15153 (org-completing-read
15154 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15155 (concat "[" cur "]") "")
15156 ": ")
15157 existing nil nil "" nil cur))))))
15158 (unless (equal (org-entry-get nil prop) val)
15159 (org-entry-put nil prop val))
15160 (save-excursion
15161 (org-back-to-heading t)
15162 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15163 (when (string= heading org-clock-current-task)
15164 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15165 (org-clock-update-mode-line))
15166 (message "%s is now %s" prop val)))
15168 (defun org-at-property-p ()
15169 "Is cursor inside a property drawer?"
15170 (save-excursion
15171 (when (equal 'node-property (car (org-element-at-point)))
15172 (beginning-of-line 1)
15173 (looking-at org-property-re))))
15175 (defun org-get-property-block (&optional beg end force)
15176 "Return the (beg . end) range of the body of the property drawer.
15177 BEG and END are the beginning and end of the current subtree, or of
15178 the part before the first headline. If they are not given, they will
15179 be found. If the drawer does not exist and FORCE is non-nil, create
15180 the drawer."
15181 (catch 'exit
15182 (save-excursion
15183 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15184 (progn (org-back-to-heading t) (point))))
15185 (end (or end (and (not (outline-next-heading)) (point-max))
15186 (point))))
15187 (goto-char beg)
15188 (if (re-search-forward org-property-start-re end t)
15189 (setq beg (1+ (match-end 0)))
15190 (if force
15191 (save-excursion
15192 (org-insert-property-drawer)
15193 (setq end (progn (outline-next-heading) (point))))
15194 (throw 'exit nil))
15195 (goto-char beg)
15196 (if (re-search-forward org-property-start-re end t)
15197 (setq beg (1+ (match-end 0)))))
15198 (if (re-search-forward org-property-end-re end t)
15199 (setq end (match-beginning 0))
15200 (or force (throw 'exit nil))
15201 (goto-char beg)
15202 (setq end beg)
15203 (org-indent-line)
15204 (insert ":END:\n"))
15205 (cons beg end)))))
15207 (defun org-entry-properties (&optional pom which specific)
15208 "Get all properties of the entry at point-or-marker POM.
15209 This includes the TODO keyword, the tags, time strings for deadline,
15210 scheduled, and clocking, and any additional properties defined in the
15211 entry. The return value is an alist, keys may occur multiple times
15212 if the property key was used several times.
15213 POM may also be nil, in which case the current entry is used.
15214 If WHICH is nil or `all', get all properties. If WHICH is
15215 `special' or `standard', only get that subclass. If WHICH
15216 is a string only get exactly this property. SPECIFIC can be a string, the
15217 specific property we are interested in. Specifying it can speed
15218 things up because then unnecessary parsing is avoided."
15219 (setq which (or which 'all))
15220 (org-with-wide-buffer
15221 (org-with-point-at pom
15222 (let ((clockstr (substring org-clock-string 0 -1))
15223 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15224 (case-fold-search nil)
15225 beg end range props sum-props key key1 value string clocksum clocksumt)
15226 (when (and (derived-mode-p 'org-mode)
15227 (ignore-errors (org-back-to-heading t)))
15228 (setq beg (point))
15229 (setq sum-props (get-text-property (point) 'org-summaries))
15230 (setq clocksum (get-text-property (point) :org-clock-minutes)
15231 clocksumt (get-text-property (point) :org-clock-minutes-today))
15232 (outline-next-heading)
15233 (setq end (point))
15234 (when (memq which '(all special))
15235 ;; Get the special properties, like TODO and tags
15236 (goto-char beg)
15237 (when (and (or (not specific) (string= specific "TODO"))
15238 (looking-at org-todo-line-regexp) (match-end 2))
15239 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15240 (when (and (or (not specific) (string= specific "PRIORITY"))
15241 (looking-at org-priority-regexp))
15242 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15243 (when (or (not specific) (string= specific "FILE"))
15244 (push (cons "FILE" buffer-file-name) props))
15245 (when (and (or (not specific) (string= specific "TAGS"))
15246 (setq value (org-get-tags-string))
15247 (string-match "\\S-" value))
15248 (push (cons "TAGS" value) props))
15249 (when (and (or (not specific) (string= specific "ALLTAGS"))
15250 (setq value (org-get-tags-at)))
15251 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15252 ":"))
15253 props))
15254 (when (or (not specific) (string= specific "BLOCKED"))
15255 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15256 (when (or (not specific)
15257 (member specific
15258 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15259 "TIMESTAMP" "TIMESTAMP_IA")))
15260 (catch 'match
15261 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15262 (setq key (if (match-end 1)
15263 (substring (org-match-string-no-properties 1)
15264 0 -1))
15265 string (if (equal key clockstr)
15266 (org-trim
15267 (buffer-substring-no-properties
15268 (match-beginning 3) (goto-char
15269 (point-at-eol))))
15270 (substring (org-match-string-no-properties 3)
15271 1 -1)))
15272 ;; Get the correct property name from the key. This is
15273 ;; necessary if the user has configured time keywords.
15274 (setq key1 (concat key ":"))
15275 (cond
15276 ((not key)
15277 (setq key
15278 (if (= (char-after (match-beginning 3)) ?\[)
15279 "TIMESTAMP_IA" "TIMESTAMP")))
15280 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15281 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15282 ((equal key1 org-closed-string) (setq key "CLOSED"))
15283 ((equal key1 org-clock-string) (setq key "CLOCK")))
15284 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15285 (progn
15286 (push (cons key string) props)
15287 ;; no need to search further if match is found
15288 (throw 'match t))
15289 (when (or (equal key "CLOCK") (not (assoc key props)))
15290 (push (cons key string) props)))))))
15292 (when (memq which '(all standard))
15293 ;; Get the standard properties, like :PROP: ...
15294 (setq range (org-get-property-block beg end))
15295 (when range
15296 (goto-char (car range))
15297 (while (re-search-forward org-property-re
15298 (cdr range) t)
15299 (setq key (org-match-string-no-properties 2)
15300 value (org-trim (or (org-match-string-no-properties 3) "")))
15301 (unless (member key excluded)
15302 (push (cons key (or value "")) props)))))
15303 (if clocksum
15304 (push (cons "CLOCKSUM"
15305 (org-columns-number-to-string (/ (float clocksum) 60.)
15306 'add_times))
15307 props))
15308 (if clocksumt
15309 (push (cons "CLOCKSUM_T"
15310 (org-columns-number-to-string (/ (float clocksumt) 60.)
15311 'add_times))
15312 props))
15313 (unless (assoc "CATEGORY" props)
15314 (push (cons "CATEGORY" (org-get-category)) props))
15315 (append sum-props (nreverse props)))))))
15317 (defun org-entry-get (pom property &optional inherit literal-nil)
15318 "Get value of PROPERTY for entry or content at point-or-marker POM.
15319 If INHERIT is non-nil and the entry does not have the property,
15320 then also check higher levels of the hierarchy.
15321 If INHERIT is the symbol `selective', use inheritance only if the setting
15322 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15323 If the property is present but empty, the return value is the empty string.
15324 If the property is not present at all, nil is returned.
15326 Return the value as a string.
15328 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15329 do not interpret it as the list atom nil. This is used for inheritance
15330 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15331 (org-with-point-at pom
15332 (if (and inherit (if (eq inherit 'selective)
15333 (org-property-inherit-p property)
15335 (org-entry-get-with-inheritance property literal-nil)
15336 (if (member property org-special-properties)
15337 ;; We need a special property. Use `org-entry-properties'
15338 ;; to retrieve it, but specify the wanted property
15339 (cdr (assoc property (org-entry-properties nil 'special property)))
15340 (org-with-wide-buffer
15341 (let ((range (org-get-property-block)))
15342 (when (and range (not (eq (car range) (cdr range)))
15343 (save-excursion
15344 (goto-char (car range))
15345 (re-search-forward
15346 (concat (org-re-property property) "\\|"
15347 (org-re-property (concat property "+")))
15348 (cdr range) t)))
15349 (let* ((props
15350 (list (or (assoc property org-file-properties)
15351 (assoc property org-global-properties)
15352 (assoc property org-global-properties-fixed))))
15353 (ap (lambda (key)
15354 (when (re-search-forward
15355 (org-re-property key) (cdr range) t)
15356 (setq props
15357 (org-update-property-plist
15359 (if (match-end 3)
15360 (org-match-string-no-properties 3) "")
15361 props)))))
15362 val)
15363 (goto-char (car range))
15364 (funcall ap property)
15365 (goto-char (car range))
15366 (while (funcall ap (concat property "+")))
15367 (setq val (cdr (assoc property props)))
15368 (when val (if literal-nil val (org-not-nil val)))))))))))
15370 (defun org-property-or-variable-value (var &optional inherit)
15371 "Check if there is a property fixing the value of VAR.
15372 If yes, return this value. If not, return the current value of the variable."
15373 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15374 (if (and prop (stringp prop) (string-match "\\S-" prop))
15375 (read prop)
15376 (symbol-value var))))
15378 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15379 "Delete the property PROPERTY from entry at point-or-marker POM.
15380 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15381 an empty drawer to delete."
15382 (org-with-point-at pom
15383 (if (member property org-special-properties)
15384 nil ; cannot delete these properties.
15385 (let ((range (org-get-property-block)))
15386 (if (and range
15387 (goto-char (car range))
15388 (re-search-forward
15389 (org-re-property property)
15390 (cdr range) t))
15391 (progn
15392 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15393 (and delete-empty-drawer
15394 (org-remove-empty-drawer-at
15395 delete-empty-drawer (car range)))
15397 nil)))))
15399 ;; Multi-values properties are properties that contain multiple values
15400 ;; These values are assumed to be single words, separated by whitespace.
15401 (defun org-entry-add-to-multivalued-property (pom property value)
15402 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15403 (let* ((old (org-entry-get pom property))
15404 (values (and old (org-split-string old "[ \t]"))))
15405 (setq value (org-entry-protect-space value))
15406 (unless (member value values)
15407 (setq values (append values (list value)))
15408 (org-entry-put pom property
15409 (mapconcat 'identity values " ")))))
15411 (defun org-entry-remove-from-multivalued-property (pom property value)
15412 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15413 (let* ((old (org-entry-get pom property))
15414 (values (and old (org-split-string old "[ \t]"))))
15415 (setq value (org-entry-protect-space value))
15416 (when (member value values)
15417 (setq values (delete value values))
15418 (org-entry-put pom property
15419 (mapconcat 'identity values " ")))))
15421 (defun org-entry-member-in-multivalued-property (pom property value)
15422 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15423 (let* ((old (org-entry-get pom property))
15424 (values (and old (org-split-string old "[ \t]"))))
15425 (setq value (org-entry-protect-space value))
15426 (member value values)))
15428 (defun org-entry-get-multivalued-property (pom property)
15429 "Return a list of values in a multivalued property."
15430 (let* ((value (org-entry-get pom property))
15431 (values (and value (org-split-string value "[ \t]"))))
15432 (mapcar 'org-entry-restore-space values)))
15434 (defun org-entry-put-multivalued-property (pom property &rest values)
15435 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15436 VALUES should be a list of strings. Spaces will be protected."
15437 (org-entry-put pom property
15438 (mapconcat 'org-entry-protect-space values " "))
15439 (let* ((value (org-entry-get pom property))
15440 (values (and value (org-split-string value "[ \t]"))))
15441 (mapcar 'org-entry-restore-space values)))
15443 (defun org-entry-protect-space (s)
15444 "Protect spaces and newline in string S."
15445 (while (string-match " " s)
15446 (setq s (replace-match "%20" t t s)))
15447 (while (string-match "\n" s)
15448 (setq s (replace-match "%0A" t t s)))
15451 (defun org-entry-restore-space (s)
15452 "Restore spaces and newline in string S."
15453 (while (string-match "%20" s)
15454 (setq s (replace-match " " t t s)))
15455 (while (string-match "%0A" s)
15456 (setq s (replace-match "\n" t t s)))
15459 (defvar org-entry-property-inherited-from (make-marker)
15460 "Marker pointing to the entry from where a property was inherited.
15461 Each call to `org-entry-get-with-inheritance' will set this marker to the
15462 location of the entry where the inheritance search matched. If there was
15463 no match, the marker will point nowhere.
15464 Note that also `org-entry-get' calls this function, if the INHERIT flag
15465 is set.")
15467 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15468 "Get PROPERTY of entry or content at point, search higher levels if needed.
15469 The search will stop at the first ancestor which has the property defined.
15470 If the value found is \"nil\", return nil to show that the property
15471 should be considered as undefined (this is the meaning of nil here).
15472 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15473 (move-marker org-entry-property-inherited-from nil)
15474 (let (tmp)
15475 (save-excursion
15476 (save-restriction
15477 (widen)
15478 (catch 'ex
15479 (while t
15480 (when (setq tmp (org-entry-get nil property nil literal-nil))
15481 (or (ignore-errors (org-back-to-heading t))
15482 (goto-char (point-min)))
15483 (move-marker org-entry-property-inherited-from (point))
15484 (throw 'ex tmp))
15485 (or (ignore-errors (org-up-heading-safe))
15486 (throw 'ex nil))))))
15487 (setq tmp (or tmp
15488 (cdr (assoc property org-file-properties))
15489 (cdr (assoc property org-global-properties))
15490 (cdr (assoc property org-global-properties-fixed))))
15491 (if literal-nil tmp (org-not-nil tmp))))
15493 (defvar org-property-changed-functions nil
15494 "Hook called when the value of a property has changed.
15495 Each hook function should accept two arguments, the name of the property
15496 and the new value.")
15498 (defun org-entry-put (pom property value)
15499 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15500 If the value is `nil', it is converted to the empty string.
15501 If it is not a string, an error is raised."
15502 (cond ((null value) (setq value ""))
15503 ((not (stringp value))
15504 (error "Properties values should be strings.")))
15505 (org-with-point-at pom
15506 (org-back-to-heading t)
15507 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15508 range)
15509 (cond
15510 ((equal property "TODO")
15511 (when (and (string-match "\\S-" value)
15512 (not (member value org-todo-keywords-1)))
15513 (user-error "\"%s\" is not a valid TODO state" value))
15514 (if (or (not value)
15515 (not (string-match "\\S-" value)))
15516 (setq value 'none))
15517 (org-todo value)
15518 (org-set-tags nil 'align))
15519 ((equal property "PRIORITY")
15520 (org-priority (if (and value (string-match "\\S-" value))
15521 (string-to-char value) ?\ ))
15522 (org-set-tags nil 'align))
15523 ((equal property "CLOCKSUM")
15524 (if (not (re-search-forward
15525 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15526 (error "Cannot find a clock log")
15527 (goto-char (- (match-end 1) 2))
15528 (cond
15529 ((eq value 'earlier) (org-timestamp-down))
15530 ((eq value 'later) (org-timestamp-up)))
15531 (org-clock-sum-current-item)))
15532 ((equal property "SCHEDULED")
15533 (if (re-search-forward org-scheduled-time-regexp end t)
15534 (cond
15535 ((eq value 'earlier) (org-timestamp-change -1 'day))
15536 ((eq value 'later) (org-timestamp-change 1 'day))
15537 (t (call-interactively 'org-schedule)))
15538 (call-interactively 'org-schedule)))
15539 ((equal property "DEADLINE")
15540 (if (re-search-forward org-deadline-time-regexp end t)
15541 (cond
15542 ((eq value 'earlier) (org-timestamp-change -1 'day))
15543 ((eq value 'later) (org-timestamp-change 1 'day))
15544 (t (call-interactively 'org-deadline)))
15545 (call-interactively 'org-deadline)))
15546 ((member property org-special-properties)
15547 (error "The %s property can not yet be set with `org-entry-put'"
15548 property))
15549 (t ; a non-special property
15550 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15551 (setq range (org-get-property-block beg end 'force))
15552 (goto-char (car range))
15553 (if (re-search-forward
15554 (org-re-property property) (cdr range) t)
15555 (progn
15556 (delete-region (match-beginning 0) (match-end 0))
15557 (goto-char (match-beginning 0)))
15558 (goto-char (cdr range))
15559 (insert "\n")
15560 (backward-char 1)
15561 (org-indent-line))
15562 (insert ":" property ":")
15563 (and value (insert " " value))
15564 (org-indent-line)))))
15565 (run-hook-with-args 'org-property-changed-functions property value)))
15567 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15568 "Get all property keys in the current buffer.
15569 With INCLUDE-SPECIALS, also list the special properties that reflect things
15570 like tags and TODO state.
15571 With INCLUDE-DEFAULTS, also include properties that has special meaning
15572 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15573 and others.
15574 With INCLUDE-COLUMNS, also include property names given in COLUMN
15575 formats in the current buffer."
15576 (let (rtn range cfmt s p)
15577 (save-excursion
15578 (save-restriction
15579 (widen)
15580 (goto-char (point-min))
15581 (while (re-search-forward org-property-start-re nil t)
15582 (setq range (org-get-property-block))
15583 (goto-char (car range))
15584 (while (re-search-forward org-property-re
15585 (cdr range) t)
15586 (add-to-list 'rtn (org-match-string-no-properties 2)))
15587 (outline-next-heading))))
15589 (when include-specials
15590 (setq rtn (append org-special-properties rtn)))
15592 (when include-defaults
15593 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15594 (add-to-list 'rtn org-effort-property))
15596 (when include-columns
15597 (save-excursion
15598 (save-restriction
15599 (widen)
15600 (goto-char (point-min))
15601 (while (re-search-forward
15602 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15603 nil t)
15604 (setq cfmt (match-string 2) s 0)
15605 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15606 cfmt s)
15607 (setq s (match-end 0)
15608 p (match-string 1 cfmt))
15609 (unless (or (equal p "ITEM")
15610 (member p org-special-properties))
15611 (add-to-list 'rtn (match-string 1 cfmt))))))))
15613 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15615 (defun org-property-values (key)
15616 "Return a list of all values of property KEY in the current buffer."
15617 (save-excursion
15618 (save-restriction
15619 (widen)
15620 (goto-char (point-min))
15621 (let ((re (org-re-property key))
15622 values)
15623 (while (re-search-forward re nil t)
15624 (add-to-list 'values (org-trim (match-string 3))))
15625 (delete "" values)))))
15627 (defun org-insert-property-drawer ()
15628 "Insert a property drawer into the current entry."
15629 (org-back-to-heading t)
15630 (looking-at org-outline-regexp)
15631 (let ((indent (if org-adapt-indentation
15632 (- (match-end 0) (match-beginning 0))
15634 (beg (point))
15635 (re (concat "^[ \t]*" org-keyword-time-regexp))
15636 end hiddenp)
15637 (outline-next-heading)
15638 (setq end (point))
15639 (goto-char beg)
15640 (while (re-search-forward re end t))
15641 (setq hiddenp (outline-invisible-p))
15642 (end-of-line 1)
15643 (and (equal (char-after) ?\n) (forward-char 1))
15644 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15645 (if (member (match-string 1) '("CLOCK:" ":END:"))
15646 ;; just skip this line
15647 (beginning-of-line 2)
15648 ;; Drawer start, find the end
15649 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15650 (beginning-of-line 1)))
15651 (org-skip-over-state-notes)
15652 (skip-chars-backward " \t\n\r")
15653 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15654 (forward-char 1))
15655 (goto-char (point-at-eol))
15656 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15657 (beginning-of-line 0)
15658 (org-indent-to-column indent)
15659 (beginning-of-line 2)
15660 (org-indent-to-column indent)
15661 (beginning-of-line 0)
15662 (if hiddenp
15663 (save-excursion
15664 (org-back-to-heading t)
15665 (hide-entry))
15666 (org-flag-drawer t))))
15668 (defun org-insert-drawer (&optional arg drawer)
15669 "Insert a drawer at point.
15671 Optional argument DRAWER, when non-nil, is a string representing
15672 drawer's name. Otherwise, the user is prompted for a name.
15674 If a region is active, insert the drawer around that region
15675 instead.
15677 Point is left between drawer's boundaries."
15678 (interactive "P")
15679 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15680 "LOGBOOK"))
15681 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15682 ;; internally by Org. They are meant to be inserted
15683 ;; automatically.
15684 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15685 ;; Remove system drawers from list. Note: For some reason,
15686 ;; `org-completing-read' ignores the predicate while
15687 ;; `completing-read' handles it fine.
15688 (drawer (if arg "PROPERTIES"
15689 (or drawer
15690 (completing-read
15691 "Drawer: " org-drawers
15692 (lambda (d) (not (member d system-drawers))))))))
15693 (cond
15694 ;; With C-u, fall back on `org-insert-property-drawer'
15695 (arg (org-insert-property-drawer))
15696 ;; With an active region, insert a drawer at point.
15697 ((not (org-region-active-p))
15698 (progn
15699 (unless (bolp) (insert "\n"))
15700 (insert (format ":%s:\n\n:END:\n" drawer))
15701 (forward-line -2)))
15702 ;; Otherwise, insert the drawer at point
15704 (let ((rbeg (region-beginning))
15705 (rend (copy-marker (region-end))))
15706 (unwind-protect
15707 (progn
15708 (goto-char rbeg)
15709 (beginning-of-line)
15710 (when (save-excursion
15711 (re-search-forward org-outline-regexp-bol rend t))
15712 (user-error "Drawers cannot contain headlines"))
15713 ;; Position point at the beginning of the first
15714 ;; non-blank line in region. Insert drawer's opening
15715 ;; there, then indent it.
15716 (org-skip-whitespace)
15717 (beginning-of-line)
15718 (insert ":" drawer ":\n")
15719 (forward-line -1)
15720 (indent-for-tab-command)
15721 ;; Move point to the beginning of the first blank line
15722 ;; after the last non-blank line in region. Insert
15723 ;; drawer's closing, then indent it.
15724 (goto-char rend)
15725 (skip-chars-backward " \r\t\n")
15726 (insert "\n:END:")
15727 (deactivate-mark t)
15728 (indent-for-tab-command)
15729 (unless (eolp) (insert "\n")))
15730 ;; Clear marker, whatever the outcome of insertion is.
15731 (set-marker rend nil)))))))
15733 (defvar org-property-set-functions-alist nil
15734 "Property set function alist.
15735 Each entry should have the following format:
15737 (PROPERTY . READ-FUNCTION)
15739 The read function will be called with the same argument as
15740 `org-completing-read'.")
15742 (defun org-set-property-function (property)
15743 "Get the function that should be used to set PROPERTY.
15744 This is computed according to `org-property-set-functions-alist'."
15745 (or (cdr (assoc property org-property-set-functions-alist))
15746 'org-completing-read))
15748 (defun org-read-property-value (property)
15749 "Read PROPERTY value from user."
15750 (let* ((completion-ignore-case t)
15751 (allowed (org-property-get-allowed-values nil property 'table))
15752 (cur (org-entry-get nil property))
15753 (prompt (concat property " value"
15754 (if (and cur (string-match "\\S-" cur))
15755 (concat " [" cur "]") "") ": "))
15756 (set-function (org-set-property-function property))
15757 (val (if allowed
15758 (funcall set-function prompt allowed nil
15759 (not (get-text-property 0 'org-unrestricted
15760 (caar allowed))))
15761 (let (org-completion-use-ido org-completion-use-iswitchb)
15762 (funcall set-function prompt
15763 (mapcar 'list (org-property-values property))
15764 nil nil "" nil cur)))))
15765 (if (equal val "")
15767 val)))
15769 (defvar org-last-set-property nil)
15770 (defvar org-last-set-property-value nil)
15771 (defun org-read-property-name ()
15772 "Read a property name."
15773 (let* ((completion-ignore-case t)
15774 (keys (org-buffer-property-keys nil t t))
15775 (default-prop (or (save-excursion
15776 (save-match-data
15777 (beginning-of-line)
15778 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15779 (null (string= (match-string 1) "END"))
15780 (match-string 1))))
15781 org-last-set-property))
15782 (property (org-icompleting-read
15783 (concat "Property"
15784 (if default-prop (concat " [" default-prop "]") "")
15785 ": ")
15786 (mapcar 'list keys)
15787 nil nil nil nil
15788 default-prop)))
15789 (if (member property keys)
15790 property
15791 (or (cdr (assoc (downcase property)
15792 (mapcar (lambda (x) (cons (downcase x) x))
15793 keys)))
15794 property))))
15796 (defun org-set-property-and-value (use-last)
15797 "Allow to set [PROPERTY]: [value] direction from prompt.
15798 When use-default, don't even ask, just use the last
15799 \"[PROPERTY]: [value]\" string from the history."
15800 (interactive "P")
15801 (let* ((completion-ignore-case t)
15802 (pv (or (and use-last org-last-set-property-value)
15803 (org-completing-read
15804 "Enter a \"[Property]: [value]\" pair: "
15805 nil nil nil nil nil
15806 org-last-set-property-value)))
15807 prop val)
15808 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15809 (setq prop (match-string 1 pv)
15810 val (match-string 2 pv))
15811 (org-set-property prop val))))
15813 (defun org-set-property (property value)
15814 "In the current entry, set PROPERTY to VALUE.
15815 When called interactively, this will prompt for a property name, offering
15816 completion on existing and default properties. And then it will prompt
15817 for a value, offering completion either on allowed values (via an inherited
15818 xxx_ALL property) or on existing values in other instances of this property
15819 in the current file."
15820 (interactive (list nil nil))
15821 (let* ((property (or property (org-read-property-name)))
15822 (value (or value (org-read-property-value property)))
15823 (fn (cdr (assoc property org-properties-postprocess-alist))))
15824 (setq org-last-set-property property)
15825 (setq org-last-set-property-value (concat property ": " value))
15826 ;; Possibly postprocess the inserted value:
15827 (when fn (setq value (funcall fn value)))
15828 (unless (equal (org-entry-get nil property) value)
15829 (org-entry-put nil property value))))
15831 (defun org-delete-property (property &optional delete-empty-drawer)
15832 "In the current entry, delete PROPERTY.
15833 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15834 an empty drawer to delete."
15835 (interactive
15836 (let* ((completion-ignore-case t)
15837 (cat (org-entry-get (point) "CATEGORY"))
15838 (props0 (org-entry-properties nil 'standard))
15839 (props (if cat props0
15840 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15841 (prop (if (< 1 (length props))
15842 (org-icompleting-read "Property: " props nil t)
15843 (caar props))))
15844 (list prop)))
15845 (if (org-entry-delete nil property delete-empty-drawer)
15846 (message "Property %s deleted" property)))
15848 (defun org-delete-property-globally (property)
15849 "Remove PROPERTY globally, from all entries."
15850 (interactive
15851 (let* ((completion-ignore-case t)
15852 (prop (org-icompleting-read
15853 "Globally remove property: "
15854 (mapcar 'list (org-buffer-property-keys)))))
15855 (list prop)))
15856 (save-excursion
15857 (save-restriction
15858 (widen)
15859 (goto-char (point-min))
15860 (let ((cnt 0))
15861 (while (re-search-forward
15862 (org-re-property property)
15863 nil t)
15864 (setq cnt (1+ cnt))
15865 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15866 (message "Property \"%s\" removed from %d entries" property cnt)))))
15868 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15870 (defun org-compute-property-at-point ()
15871 "Compute the property at point.
15872 This looks for an enclosing column format, extracts the operator and
15873 then applies it to the property in the column format's scope."
15874 (interactive)
15875 (unless (org-at-property-p)
15876 (user-error "Not at a property"))
15877 (let ((prop (org-match-string-no-properties 2)))
15878 (org-columns-get-format-and-top-level)
15879 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15880 (user-error "No operator defined for property %s" prop))
15881 (org-columns-compute prop)))
15883 (defvar org-property-allowed-value-functions nil
15884 "Hook for functions supplying allowed values for a specific property.
15885 The functions must take a single argument, the name of the property, and
15886 return a flat list of allowed values. If \":ETC\" is one of
15887 the values, this means that these values are intended as defaults for
15888 completion, but that other values should be allowed too.
15889 The functions must return nil if they are not responsible for this
15890 property.")
15892 (defun org-property-get-allowed-values (pom property &optional table)
15893 "Get allowed values for the property PROPERTY.
15894 When TABLE is non-nil, return an alist that can directly be used for
15895 completion."
15896 (let (vals)
15897 (cond
15898 ((equal property "TODO")
15899 (setq vals (org-with-point-at pom
15900 (append org-todo-keywords-1 '("")))))
15901 ((equal property "PRIORITY")
15902 (let ((n org-lowest-priority))
15903 (while (>= n org-highest-priority)
15904 (push (char-to-string n) vals)
15905 (setq n (1- n)))))
15906 ((member property org-special-properties))
15907 ((setq vals (run-hook-with-args-until-success
15908 'org-property-allowed-value-functions property)))
15910 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15911 (when (and vals (string-match "\\S-" vals))
15912 (setq vals (car (read-from-string (concat "(" vals ")"))))
15913 (setq vals (mapcar (lambda (x)
15914 (cond ((stringp x) x)
15915 ((numberp x) (number-to-string x))
15916 ((symbolp x) (symbol-name x))
15917 (t "???")))
15918 vals)))))
15919 (when (member ":ETC" vals)
15920 (setq vals (remove ":ETC" vals))
15921 (org-add-props (car vals) '(org-unrestricted t)))
15922 (if table (mapcar 'list vals) vals)))
15924 (defun org-property-previous-allowed-value (&optional previous)
15925 "Switch to the next allowed value for this property."
15926 (interactive)
15927 (org-property-next-allowed-value t))
15929 (defun org-property-next-allowed-value (&optional previous)
15930 "Switch to the next allowed value for this property."
15931 (interactive)
15932 (unless (org-at-property-p)
15933 (user-error "Not at a property"))
15934 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15935 (key (match-string 2))
15936 (value (match-string 3))
15937 (allowed (or (org-property-get-allowed-values (point) key)
15938 (and (member value '("[ ]" "[-]" "[X]"))
15939 '("[ ]" "[X]"))))
15940 (heading (save-match-data (nth 4 (org-heading-components))))
15941 nval)
15942 (unless allowed
15943 (user-error "Allowed values for this property have not been defined"))
15944 (if previous (setq allowed (reverse allowed)))
15945 (if (member value allowed)
15946 (setq nval (car (cdr (member value allowed)))))
15947 (setq nval (or nval (car allowed)))
15948 (if (equal nval value)
15949 (user-error "Only one allowed value for this property"))
15950 (org-at-property-p)
15951 (replace-match (concat " :" key ": " nval) t t)
15952 (org-indent-line)
15953 (beginning-of-line 1)
15954 (skip-chars-forward " \t")
15955 (when (equal prop org-effort-property)
15956 (save-excursion
15957 (org-back-to-heading t)
15958 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15959 (when (string= org-clock-current-task heading)
15960 (setq org-clock-effort nval)
15961 (org-clock-update-mode-line)))
15962 (run-hook-with-args 'org-property-changed-functions key nval)))
15964 (defun org-find-olp (path &optional this-buffer)
15965 "Return a marker pointing to the entry at outline path OLP.
15966 If anything goes wrong, throw an error.
15967 You can wrap this call to catch the error like this:
15969 (condition-case msg
15970 (org-mobile-locate-entry (match-string 4))
15971 (error (nth 1 msg)))
15973 The return value will then be either a string with the error message,
15974 or a marker if everything is OK.
15976 If THIS-BUFFER is set, the outline path does not contain a file,
15977 only headings."
15978 (let* ((file (if this-buffer buffer-file-name (pop path)))
15979 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15980 (level 1)
15981 (lmin 1)
15982 (lmax 1)
15983 limit re end found pos heading cnt flevel)
15984 (unless buffer (error "File not found :%s" file))
15985 (with-current-buffer buffer
15986 (save-excursion
15987 (save-restriction
15988 (widen)
15989 (setq limit (point-max))
15990 (goto-char (point-min))
15991 (while (setq heading (pop path))
15992 (setq re (format org-complex-heading-regexp-format
15993 (regexp-quote heading)))
15994 (setq cnt 0 pos (point))
15995 (while (re-search-forward re end t)
15996 (setq level (- (match-end 1) (match-beginning 1)))
15997 (if (and (>= level lmin) (<= level lmax))
15998 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15999 (when (= cnt 0) (error "Heading not found on level %d: %s"
16000 lmax heading))
16001 (when (> cnt 1) (error "Heading not unique on level %d: %s"
16002 lmax heading))
16003 (goto-char found)
16004 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16005 (setq end (save-excursion (org-end-of-subtree t t))))
16006 (when (org-at-heading-p)
16007 (point-marker)))))))
16009 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16010 "Find node HEADING in BUFFER.
16011 Return a marker to the heading if it was found, or nil if not.
16012 If POS-ONLY is set, return just the position instead of a marker.
16014 The heading text must match exact, but it may have a TODO keyword,
16015 a priority cookie and tags in the standard locations."
16016 (with-current-buffer (or buffer (current-buffer))
16017 (save-excursion
16018 (save-restriction
16019 (widen)
16020 (goto-char (point-min))
16021 (let (case-fold-search)
16022 (if (re-search-forward
16023 (format org-complex-heading-regexp-format
16024 (regexp-quote heading)) nil t)
16025 (if pos-only
16026 (match-beginning 0)
16027 (move-marker (make-marker) (match-beginning 0)))))))))
16029 (defun org-find-exact-heading-in-directory (heading &optional dir)
16030 "Find Org node headline HEADING in all .org files in directory DIR.
16031 When the target headline is found, return a marker to this location."
16032 (let ((files (directory-files (or dir default-directory)
16033 nil "\\`[^.#].*\\.org\\'"))
16034 file visiting m buffer)
16035 (catch 'found
16036 (while (setq file (pop files))
16037 (message "trying %s" file)
16038 (setq visiting (org-find-base-buffer-visiting file))
16039 (setq buffer (or visiting (find-file-noselect file)))
16040 (setq m (org-find-exact-headline-in-buffer
16041 heading buffer))
16042 (when (and (not m) (not visiting)) (kill-buffer buffer))
16043 (and m (throw 'found m))))))
16045 (defun org-find-entry-with-id (ident)
16046 "Locate the entry that contains the ID property with exact value IDENT.
16047 IDENT can be a string, a symbol or a number, this function will search for
16048 the string representation of it.
16049 Return the position where this entry starts, or nil if there is no such entry."
16050 (interactive "sID: ")
16051 (let ((id (cond
16052 ((stringp ident) ident)
16053 ((symbol-name ident) (symbol-name ident))
16054 ((numberp ident) (number-to-string ident))
16055 (t (error "IDENT %s must be a string, symbol or number" ident))))
16056 (case-fold-search nil))
16057 (save-excursion
16058 (save-restriction
16059 (widen)
16060 (goto-char (point-min))
16061 (when (re-search-forward
16062 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16063 nil t)
16064 (org-back-to-heading t)
16065 (point))))))
16067 ;;;; Timestamps
16069 (defvar org-last-changed-timestamp nil)
16070 (defvar org-last-inserted-timestamp nil
16071 "The last time stamp inserted with `org-insert-time-stamp'.")
16072 (defvar org-ts-what) ; dynamically scoped parameter
16074 (defun org-time-stamp (arg &optional inactive)
16075 "Prompt for a date/time and insert a time stamp.
16076 If the user specifies a time like HH:MM or if this command is
16077 called with at least one prefix argument, the time stamp contains
16078 the date and the time. Otherwise, only the date is be included.
16080 All parts of a date not specified by the user is filled in from
16081 the current date/time. So if you just press return without
16082 typing anything, the time stamp will represent the current
16083 date/time.
16085 If there is already a timestamp at the cursor, it will be
16086 modified.
16088 With two universal prefix arguments, insert an active timestamp
16089 with the current time without prompting the user.
16091 When called from lisp, the timestamp is inactive if INACTIVE is
16092 non-nil."
16093 (interactive "P")
16094 (let* ((ts nil)
16095 (default-time
16096 ;; Default time is either today, or, when entering a range,
16097 ;; the range start.
16098 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16099 (save-excursion
16100 (re-search-backward
16101 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16102 (- (point) 20) t)))
16103 (apply 'encode-time (org-parse-time-string (match-string 1)))
16104 (current-time)))
16105 (default-input (and ts (org-get-compact-tod ts)))
16106 (repeater (save-excursion
16107 (save-match-data
16108 (beginning-of-line)
16109 (when (re-search-forward
16110 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16111 (save-excursion (progn (end-of-line) (point))) t)
16112 (match-string 0)))))
16113 org-time-was-given org-end-time-was-given time)
16114 (cond
16115 ((and (org-at-timestamp-p t)
16116 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16117 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16118 (insert "--")
16119 (setq time (let ((this-command this-command))
16120 (org-read-date arg 'totime nil nil
16121 default-time default-input inactive)))
16122 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16123 ((org-at-timestamp-p t)
16124 (setq time (let ((this-command this-command))
16125 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16126 (when (org-at-timestamp-p t) ; just to get the match data
16127 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16128 (replace-match "")
16129 (setq org-last-changed-timestamp
16130 (org-insert-time-stamp
16131 time (or org-time-was-given arg)
16132 inactive nil nil (list org-end-time-was-given)))
16133 (when repeater (goto-char (1- (point))) (insert " " repeater)
16134 (setq org-last-changed-timestamp
16135 (concat (substring org-last-inserted-timestamp 0 -1)
16136 " " repeater ">"))))
16137 (message "Timestamp updated"))
16138 ((equal arg '(16))
16139 (org-insert-time-stamp (current-time) t inactive))
16141 (setq time (let ((this-command this-command))
16142 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16143 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16144 nil nil (list org-end-time-was-given))))))
16146 ;; FIXME: can we use this for something else, like computing time differences?
16147 (defun org-get-compact-tod (s)
16148 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16149 (let* ((t1 (match-string 1 s))
16150 (h1 (string-to-number (match-string 2 s)))
16151 (m1 (string-to-number (match-string 3 s)))
16152 (t2 (and (match-end 4) (match-string 5 s)))
16153 (h2 (and t2 (string-to-number (match-string 6 s))))
16154 (m2 (and t2 (string-to-number (match-string 7 s))))
16155 dh dm)
16156 (if (not t2)
16158 (setq dh (- h2 h1) dm (- m2 m1))
16159 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16160 (concat t1 "+" (number-to-string dh)
16161 (and (/= 0 dm) (format ":%02d" dm)))))))
16163 (defun org-time-stamp-inactive (&optional arg)
16164 "Insert an inactive time stamp.
16165 An inactive time stamp is enclosed in square brackets instead of angle
16166 brackets. It is inactive in the sense that it does not trigger agenda entries,
16167 does not link to the calendar and cannot be changed with the S-cursor keys.
16168 So these are more for recording a certain time/date."
16169 (interactive "P")
16170 (org-time-stamp arg 'inactive))
16172 (defvar org-date-ovl (make-overlay 1 1))
16173 (overlay-put org-date-ovl 'face 'org-date-selected)
16174 (org-detach-overlay org-date-ovl)
16176 (defvar org-ans1) ; dynamically scoped parameter
16177 (defvar org-ans2) ; dynamically scoped parameter
16179 (defvar org-plain-time-of-day-regexp) ; defined below
16181 (defvar org-overriding-default-time nil) ; dynamically scoped
16182 (defvar org-read-date-overlay nil)
16183 (defvar org-dcst nil) ; dynamically scoped
16184 (defvar org-read-date-history nil)
16185 (defvar org-read-date-final-answer nil)
16186 (defvar org-read-date-analyze-futurep nil)
16187 (defvar org-read-date-analyze-forced-year nil)
16188 (defvar org-read-date-inactive)
16190 (defvar org-read-date-minibuffer-local-map
16191 (let* ((org-replace-disputed-keys nil)
16192 (map (make-sparse-keymap)))
16193 (set-keymap-parent map minibuffer-local-map)
16194 (org-defkey map (kbd ".")
16195 (lambda () (interactive)
16196 ;; Are we at the beginning of the prompt?
16197 (if (looking-back "^[^:]+: ")
16198 (org-eval-in-calendar '(calendar-goto-today))
16199 (insert "."))))
16200 (org-defkey map (kbd "C-.")
16201 (lambda () (interactive)
16202 (org-eval-in-calendar '(calendar-goto-today))))
16203 (org-defkey map [(meta shift left)]
16204 (lambda () (interactive)
16205 (org-eval-in-calendar '(calendar-backward-month 1))))
16206 (org-defkey map [(meta shift right)]
16207 (lambda () (interactive)
16208 (org-eval-in-calendar '(calendar-forward-month 1))))
16209 (org-defkey map [(meta shift up)]
16210 (lambda () (interactive)
16211 (org-eval-in-calendar '(calendar-backward-year 1))))
16212 (org-defkey map [(meta shift down)]
16213 (lambda () (interactive)
16214 (org-eval-in-calendar '(calendar-forward-year 1))))
16215 (org-defkey map [?\e (shift left)]
16216 (lambda () (interactive)
16217 (org-eval-in-calendar '(calendar-backward-month 1))))
16218 (org-defkey map [?\e (shift right)]
16219 (lambda () (interactive)
16220 (org-eval-in-calendar '(calendar-forward-month 1))))
16221 (org-defkey map [?\e (shift up)]
16222 (lambda () (interactive)
16223 (org-eval-in-calendar '(calendar-backward-year 1))))
16224 (org-defkey map [?\e (shift down)]
16225 (lambda () (interactive)
16226 (org-eval-in-calendar '(calendar-forward-year 1))))
16227 (org-defkey map [(shift up)]
16228 (lambda () (interactive)
16229 (org-eval-in-calendar '(calendar-backward-week 1))))
16230 (org-defkey map [(shift down)]
16231 (lambda () (interactive)
16232 (org-eval-in-calendar '(calendar-forward-week 1))))
16233 (org-defkey map [(shift left)]
16234 (lambda () (interactive)
16235 (org-eval-in-calendar '(calendar-backward-day 1))))
16236 (org-defkey map [(shift right)]
16237 (lambda () (interactive)
16238 (org-eval-in-calendar '(calendar-forward-day 1))))
16239 (org-defkey map "!"
16240 (lambda () (interactive)
16241 (org-eval-in-calendar '(diary-view-entries))
16242 (message "")))
16243 (org-defkey map ">"
16244 (lambda () (interactive)
16245 (org-eval-in-calendar '(scroll-calendar-left 1))))
16246 (org-defkey map "<"
16247 (lambda () (interactive)
16248 (org-eval-in-calendar '(scroll-calendar-right 1))))
16249 (org-defkey map "\C-v"
16250 (lambda () (interactive)
16251 (org-eval-in-calendar
16252 '(calendar-scroll-left-three-months 1))))
16253 (org-defkey map "\M-v"
16254 (lambda () (interactive)
16255 (org-eval-in-calendar
16256 '(calendar-scroll-right-three-months 1))))
16257 map)
16258 "Keymap for minibuffer commands when using `org-read-date'.")
16260 (defvar org-def)
16261 (defvar org-defdecode)
16262 (defvar org-with-time)
16264 (defun org-read-date (&optional org-with-time to-time from-string prompt
16265 default-time default-input inactive)
16266 "Read a date, possibly a time, and make things smooth for the user.
16267 The prompt will suggest to enter an ISO date, but you can also enter anything
16268 which will at least partially be understood by `parse-time-string'.
16269 Unrecognized parts of the date will default to the current day, month, year,
16270 hour and minute. If this command is called to replace a timestamp at point,
16271 or to enter the second timestamp of a range, the default time is taken
16272 from the existing stamp. Furthermore, the command prefers the future,
16273 so if you are giving a date where the year is not given, and the day-month
16274 combination is already past in the current year, it will assume you
16275 mean next year. For details, see the manual. A few examples:
16277 3-2-5 --> 2003-02-05
16278 feb 15 --> currentyear-02-15
16279 2/15 --> currentyear-02-15
16280 sep 12 9 --> 2009-09-12
16281 12:45 --> today 12:45
16282 22 sept 0:34 --> currentyear-09-22 0:34
16283 12 --> currentyear-currentmonth-12
16284 Fri --> nearest Friday after today
16285 -Tue --> last Tuesday
16286 etc.
16288 Furthermore you can specify a relative date by giving, as the *first* thing
16289 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16290 change in days weeks, months, years.
16291 With a single plus or minus, the date is relative to today. With a double
16292 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16293 +4d --> four days from today
16294 +4 --> same as above
16295 +2w --> two weeks from today
16296 ++5 --> five days from default date
16298 The function understands only English month and weekday abbreviations.
16300 While prompting, a calendar is popped up - you can also select the
16301 date with the mouse (button 1). The calendar shows a period of three
16302 months. To scroll it to other months, use the keys `>' and `<'.
16303 If you don't like the calendar, turn it off with
16304 \(setq org-read-date-popup-calendar nil)
16306 With optional argument TO-TIME, the date will immediately be converted
16307 to an internal time.
16308 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16309 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16310 still enter a time, and this function will inform the calling routine
16311 about this change. The calling routine may then choose to change the
16312 format used to insert the time stamp into the buffer to include the time.
16313 With optional argument FROM-STRING, read from this string instead from
16314 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16315 the time/date that is used for everything that is not specified by the
16316 user."
16317 (require 'parse-time)
16318 (let* ((org-time-stamp-rounding-minutes
16319 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16320 (org-dcst org-display-custom-times)
16321 (ct (org-current-time))
16322 (org-def (or org-overriding-default-time default-time ct))
16323 (org-defdecode (decode-time org-def))
16324 (dummy (progn
16325 (when (< (nth 2 org-defdecode) org-extend-today-until)
16326 (setcar (nthcdr 2 org-defdecode) -1)
16327 (setcar (nthcdr 1 org-defdecode) 59)
16328 (setq org-def (apply 'encode-time org-defdecode)
16329 org-defdecode (decode-time org-def)))))
16330 (mouse-autoselect-window nil) ; Don't let the mouse jump
16331 (calendar-frame-setup nil)
16332 (calendar-setup nil)
16333 (calendar-move-hook nil)
16334 (calendar-view-diary-initially-flag nil)
16335 (calendar-view-holidays-initially-flag nil)
16336 (timestr (format-time-string
16337 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16338 (prompt (concat (if prompt (concat prompt " ") "")
16339 (format "Date+time [%s]: " timestr)))
16340 ans (org-ans0 "") org-ans1 org-ans2 final)
16342 (cond
16343 (from-string (setq ans from-string))
16344 (org-read-date-popup-calendar
16345 (save-excursion
16346 (save-window-excursion
16347 (calendar)
16348 (org-eval-in-calendar '(setq cursor-type nil) t)
16349 (unwind-protect
16350 (progn
16351 (calendar-forward-day (- (time-to-days org-def)
16352 (calendar-absolute-from-gregorian
16353 (calendar-current-date))))
16354 (org-eval-in-calendar nil t)
16355 (let* ((old-map (current-local-map))
16356 (map (copy-keymap calendar-mode-map))
16357 (minibuffer-local-map
16358 (copy-keymap org-read-date-minibuffer-local-map)))
16359 (org-defkey map (kbd "RET") 'org-calendar-select)
16360 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16361 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16362 (unwind-protect
16363 (progn
16364 (use-local-map map)
16365 (setq org-read-date-inactive inactive)
16366 (add-hook 'post-command-hook 'org-read-date-display)
16367 (setq org-ans0 (read-string prompt default-input
16368 'org-read-date-history nil))
16369 ;; org-ans0: from prompt
16370 ;; org-ans1: from mouse click
16371 ;; org-ans2: from calendar motion
16372 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16373 (remove-hook 'post-command-hook 'org-read-date-display)
16374 (use-local-map old-map)
16375 (when org-read-date-overlay
16376 (delete-overlay org-read-date-overlay)
16377 (setq org-read-date-overlay nil)))))
16378 (bury-buffer "*Calendar*")))))
16380 (t ; Naked prompt only
16381 (unwind-protect
16382 (setq ans (read-string prompt default-input
16383 'org-read-date-history timestr))
16384 (when org-read-date-overlay
16385 (delete-overlay org-read-date-overlay)
16386 (setq org-read-date-overlay nil)))))
16388 (setq final (org-read-date-analyze ans org-def org-defdecode))
16390 (when org-read-date-analyze-forced-year
16391 (message "Year was forced into %s"
16392 (if org-read-date-force-compatible-dates
16393 "compatible range (1970-2037)"
16394 "range representable on this machine"))
16395 (ding))
16397 ;; One round trip to get rid of 34th of August and stuff like that....
16398 (setq final (decode-time (apply 'encode-time final)))
16400 (setq org-read-date-final-answer ans)
16402 (if to-time
16403 (apply 'encode-time final)
16404 (if (and (boundp 'org-time-was-given) org-time-was-given)
16405 (format "%04d-%02d-%02d %02d:%02d"
16406 (nth 5 final) (nth 4 final) (nth 3 final)
16407 (nth 2 final) (nth 1 final))
16408 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16410 (defun org-read-date-display ()
16411 "Display the current date prompt interpretation in the minibuffer."
16412 (when org-read-date-display-live
16413 (when org-read-date-overlay
16414 (delete-overlay org-read-date-overlay))
16415 (when (minibufferp (current-buffer))
16416 (save-excursion
16417 (end-of-line 1)
16418 (while (not (equal (buffer-substring
16419 (max (point-min) (- (point) 4)) (point))
16420 " "))
16421 (insert " ")))
16422 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16423 " " (or org-ans1 org-ans2)))
16424 (org-end-time-was-given nil)
16425 (f (org-read-date-analyze ans org-def org-defdecode))
16426 (fmts (if org-dcst
16427 org-time-stamp-custom-formats
16428 org-time-stamp-formats))
16429 (fmt (if (or org-with-time
16430 (and (boundp 'org-time-was-given) org-time-was-given))
16431 (cdr fmts)
16432 (car fmts)))
16433 (txt (format-time-string fmt (apply 'encode-time f)))
16434 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16435 (txt (concat "=> " txt)))
16436 (when (and org-end-time-was-given
16437 (string-match org-plain-time-of-day-regexp txt))
16438 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16439 org-end-time-was-given
16440 (substring txt (match-end 0)))))
16441 (when org-read-date-analyze-futurep
16442 (setq txt (concat txt " (=>F)")))
16443 (setq org-read-date-overlay
16444 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16445 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16447 (defun org-read-date-analyze (ans org-def org-defdecode)
16448 "Analyze the combined answer of the date prompt."
16449 ;; FIXME: cleanup and comment
16450 (let ((nowdecode (decode-time (current-time)))
16451 delta deltan deltaw deltadef year month day
16452 hour minute second wday pm h2 m2 tl wday1
16453 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16454 (setq org-read-date-analyze-futurep nil
16455 org-read-date-analyze-forced-year nil)
16456 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16457 (setq ans "+0"))
16459 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16460 (setq ans (replace-match "" t t ans)
16461 deltan (car delta)
16462 deltaw (nth 1 delta)
16463 deltadef (nth 2 delta)))
16465 ;; Check if there is an iso week date in there. If yes, store the
16466 ;; info and postpone interpreting it until the rest of the parsing
16467 ;; is done.
16468 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16469 (setq iso-year (if (match-end 1)
16470 (org-small-year-to-year
16471 (string-to-number (match-string 1 ans))))
16472 iso-weekday (if (match-end 3)
16473 (string-to-number (match-string 3 ans)))
16474 iso-week (string-to-number (match-string 2 ans)))
16475 (setq ans (replace-match "" t t ans)))
16477 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16478 (when (string-match
16479 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16480 (setq year (if (match-end 2)
16481 (string-to-number (match-string 2 ans))
16482 (progn (setq kill-year t)
16483 (string-to-number (format-time-string "%Y"))))
16484 month (string-to-number (match-string 3 ans))
16485 day (string-to-number (match-string 4 ans)))
16486 (if (< year 100) (setq year (+ 2000 year)))
16487 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16488 t nil ans)))
16490 ;; Help matching dotted european dates
16491 (when (string-match
16492 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16493 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16494 (setq kill-year t)
16495 (string-to-number (format-time-string "%Y")))
16496 day (string-to-number (match-string 1 ans))
16497 month (string-to-number (match-string 2 ans))
16498 ans (replace-match (format "%04d-%02d-%02d" year month day)
16499 t nil ans)))
16501 ;; Help matching american dates, like 5/30 or 5/30/7
16502 (when (string-match
16503 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16504 (setq year (if (match-end 4)
16505 (string-to-number (match-string 4 ans))
16506 (progn (setq kill-year t)
16507 (string-to-number (format-time-string "%Y"))))
16508 month (string-to-number (match-string 1 ans))
16509 day (string-to-number (match-string 2 ans)))
16510 (if (< year 100) (setq year (+ 2000 year)))
16511 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16512 t nil ans)))
16513 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16514 ;; If there is a time with am/pm, and *no* time without it, we convert
16515 ;; so that matching will be successful.
16516 (loop for i from 1 to 2 do ; twice, for end time as well
16517 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16518 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16519 (setq hour (string-to-number (match-string 1 ans))
16520 minute (if (match-end 3)
16521 (string-to-number (match-string 3 ans))
16523 pm (equal ?p
16524 (string-to-char (downcase (match-string 4 ans)))))
16525 (if (and (= hour 12) (not pm))
16526 (setq hour 0)
16527 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16528 (setq ans (replace-match (format "%02d:%02d" hour minute)
16529 t t ans))))
16531 ;; Check if a time range is given as a duration
16532 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16533 (setq hour (string-to-number (match-string 1 ans))
16534 h2 (+ hour (string-to-number (match-string 3 ans)))
16535 minute (string-to-number (match-string 2 ans))
16536 m2 (+ minute (if (match-end 5) (string-to-number
16537 (match-string 5 ans))0)))
16538 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16539 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16540 t t ans)))
16542 ;; Check if there is a time range
16543 (when (boundp 'org-end-time-was-given)
16544 (setq org-time-was-given nil)
16545 (when (and (string-match org-plain-time-of-day-regexp ans)
16546 (match-end 8))
16547 (setq org-end-time-was-given (match-string 8 ans))
16548 (setq ans (concat (substring ans 0 (match-beginning 7))
16549 (substring ans (match-end 7))))))
16551 (setq tl (parse-time-string ans)
16552 day (or (nth 3 tl) (nth 3 org-defdecode))
16553 month (or (nth 4 tl)
16554 (if (and org-read-date-prefer-future
16555 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16556 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16557 (nth 4 org-defdecode)))
16558 year (or (and (not kill-year) (nth 5 tl))
16559 (if (and org-read-date-prefer-future
16560 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16561 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16562 (nth 5 org-defdecode)))
16563 hour (or (nth 2 tl) (nth 2 org-defdecode))
16564 minute (or (nth 1 tl) (nth 1 org-defdecode))
16565 second (or (nth 0 tl) 0)
16566 wday (nth 6 tl))
16568 (when (and (eq org-read-date-prefer-future 'time)
16569 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16570 (equal day (nth 3 nowdecode))
16571 (equal month (nth 4 nowdecode))
16572 (equal year (nth 5 nowdecode))
16573 (nth 2 tl)
16574 (or (< (nth 2 tl) (nth 2 nowdecode))
16575 (and (= (nth 2 tl) (nth 2 nowdecode))
16576 (nth 1 tl)
16577 (< (nth 1 tl) (nth 1 nowdecode)))))
16578 (setq day (1+ day)
16579 futurep t))
16581 ;; Special date definitions below
16582 (cond
16583 (iso-week
16584 ;; There was an iso week
16585 (require 'cal-iso)
16586 (setq futurep nil)
16587 (setq year (or iso-year year)
16588 day (or iso-weekday wday 1)
16589 wday nil ; to make sure that the trigger below does not match
16590 iso-date (calendar-gregorian-from-absolute
16591 (calendar-absolute-from-iso
16592 (list iso-week day year))))
16593 ; FIXME: Should we also push ISO weeks into the future?
16594 ; (when (and org-read-date-prefer-future
16595 ; (not iso-year)
16596 ; (< (calendar-absolute-from-gregorian iso-date)
16597 ; (time-to-days (current-time))))
16598 ; (setq year (1+ year)
16599 ; iso-date (calendar-gregorian-from-absolute
16600 ; (calendar-absolute-from-iso
16601 ; (list iso-week day year)))))
16602 (setq month (car iso-date)
16603 year (nth 2 iso-date)
16604 day (nth 1 iso-date)))
16605 (deltan
16606 (setq futurep nil)
16607 (unless deltadef
16608 (let ((now (decode-time (current-time))))
16609 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16610 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16611 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16612 ((equal deltaw "m") (setq month (+ month deltan)))
16613 ((equal deltaw "y") (setq year (+ year deltan)))))
16614 ((and wday (not (nth 3 tl)))
16615 ;; Weekday was given, but no day, so pick that day in the week
16616 ;; on or after the derived date.
16617 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16618 (unless (equal wday wday1)
16619 (setq day (+ day (% (- wday wday1 -7) 7))))))
16620 (if (and (boundp 'org-time-was-given)
16621 (nth 2 tl))
16622 (setq org-time-was-given t))
16623 (if (< year 100) (setq year (+ 2000 year)))
16624 ;; Check of the date is representable
16625 (if org-read-date-force-compatible-dates
16626 (progn
16627 (if (< year 1970)
16628 (setq year 1970 org-read-date-analyze-forced-year t))
16629 (if (> year 2037)
16630 (setq year 2037 org-read-date-analyze-forced-year t)))
16631 (condition-case nil
16632 (ignore (encode-time second minute hour day month year))
16633 (error
16634 (setq year (nth 5 org-defdecode))
16635 (setq org-read-date-analyze-forced-year t))))
16636 (setq org-read-date-analyze-futurep futurep)
16637 (list second minute hour day month year)))
16639 (defvar parse-time-weekdays)
16640 (defun org-read-date-get-relative (s today default)
16641 "Check string S for special relative date string.
16642 TODAY and DEFAULT are internal times, for today and for a default.
16643 Return shift list (N what def-flag)
16644 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16645 N is the number of WHATs to shift.
16646 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16647 the DEFAULT date rather than TODAY."
16648 (require 'parse-time)
16649 (when (and
16650 (string-match
16651 (concat
16652 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16653 "\\([0-9]+\\)?"
16654 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16655 "\\([ \t]\\|$\\)") s)
16656 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16657 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16658 (string-to-char (substring (match-string 1 s) -1))
16659 ?+))
16660 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16661 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16662 (what (if (match-end 3) (match-string 3 s) "d"))
16663 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16664 (date (if rel default today))
16665 (wday (nth 6 (decode-time date)))
16666 delta)
16667 (if wday1
16668 (progn
16669 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16670 (if (= delta 0) (setq delta 7))
16671 (if (= dir ?-)
16672 (progn
16673 (setq delta (- delta 7))
16674 (if (= delta 0) (setq delta -7))))
16675 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16676 (list delta "d" rel))
16677 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16679 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16680 "Turn a user-specified date into the internal representation.
16681 The internal representation needed by the calendar is (month day year).
16682 This is a wrapper to handle the brain-dead convention in calendar that
16683 user function argument order change dependent on argument order."
16684 (if (boundp 'calendar-date-style)
16685 (cond
16686 ((eq calendar-date-style 'american)
16687 (list arg1 arg2 arg3))
16688 ((eq calendar-date-style 'european)
16689 (list arg2 arg1 arg3))
16690 ((eq calendar-date-style 'iso)
16691 (list arg2 arg3 arg1)))
16692 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16693 (if (org-bound-and-true-p european-calendar-style)
16694 (list arg2 arg1 arg3)
16695 (list arg1 arg2 arg3)))))
16697 (defun org-eval-in-calendar (form &optional keepdate)
16698 "Eval FORM in the calendar window and return to current window.
16699 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16700 otherwise stick to the current value of `org-ans2'."
16701 (let ((sf (selected-frame))
16702 (sw (selected-window)))
16703 (select-window (get-buffer-window "*Calendar*" t))
16704 (eval form)
16705 (when (and (not keepdate) (calendar-cursor-to-date))
16706 (let* ((date (calendar-cursor-to-date))
16707 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16708 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16709 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16710 (select-window sw)
16711 (org-select-frame-set-input-focus sf)))
16713 (defun org-calendar-select ()
16714 "Return to `org-read-date' with the date currently selected.
16715 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16716 (interactive)
16717 (when (calendar-cursor-to-date)
16718 (let* ((date (calendar-cursor-to-date))
16719 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16720 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16721 (if (active-minibuffer-window) (exit-minibuffer))))
16723 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16724 "Insert a date stamp for the date given by the internal TIME.
16725 WITH-HM means use the stamp format that includes the time of the day.
16726 INACTIVE means use square brackets instead of angular ones, so that the
16727 stamp will not contribute to the agenda.
16728 PRE and POST are optional strings to be inserted before and after the
16729 stamp.
16730 The command returns the inserted time stamp."
16731 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16732 stamp)
16733 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16734 (insert-before-markers (or pre ""))
16735 (when (listp extra)
16736 (setq extra (car extra))
16737 (if (and (stringp extra)
16738 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16739 (setq extra (format "-%02d:%02d"
16740 (string-to-number (match-string 1 extra))
16741 (string-to-number (match-string 2 extra))))
16742 (setq extra nil)))
16743 (when extra
16744 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16745 (insert-before-markers (setq stamp (format-time-string fmt time)))
16746 (insert-before-markers (or post ""))
16747 (setq org-last-inserted-timestamp stamp)))
16749 (defun org-toggle-time-stamp-overlays ()
16750 "Toggle the use of custom time stamp formats."
16751 (interactive)
16752 (setq org-display-custom-times (not org-display-custom-times))
16753 (unless org-display-custom-times
16754 (let ((p (point-min)) (bmp (buffer-modified-p)))
16755 (while (setq p (next-single-property-change p 'display))
16756 (if (and (get-text-property p 'display)
16757 (eq (get-text-property p 'face) 'org-date))
16758 (remove-text-properties
16759 p (setq p (next-single-property-change p 'display))
16760 '(display t))))
16761 (set-buffer-modified-p bmp)))
16762 (if (featurep 'xemacs)
16763 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16764 (org-restart-font-lock)
16765 (setq org-table-may-need-update t)
16766 (if org-display-custom-times
16767 (message "Time stamps are overlaid with custom format")
16768 (message "Time stamp overlays removed")))
16770 (defun org-display-custom-time (beg end)
16771 "Overlay modified time stamp format over timestamp between BEG and END."
16772 (let* ((ts (buffer-substring beg end))
16773 t1 w1 with-hm tf time str w2 (off 0))
16774 (save-match-data
16775 (setq t1 (org-parse-time-string ts t))
16776 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16777 (setq off (- (match-end 0) (match-beginning 0)))))
16778 (setq end (- end off))
16779 (setq w1 (- end beg)
16780 with-hm (and (nth 1 t1) (nth 2 t1))
16781 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16782 time (org-fix-decoded-time t1)
16783 str (org-add-props
16784 (format-time-string
16785 (substring tf 1 -1) (apply 'encode-time time))
16786 nil 'mouse-face 'highlight)
16787 w2 (length str))
16788 (if (not (= w2 w1))
16789 (add-text-properties (1+ beg) (+ 2 beg)
16790 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16791 (if (featurep 'xemacs)
16792 (progn
16793 (put-text-property beg end 'invisible t)
16794 (put-text-property beg end 'end-glyph (make-glyph str)))
16795 (put-text-property beg end 'display str))))
16797 (defun org-translate-time (string)
16798 "Translate all timestamps in STRING to custom format.
16799 But do this only if the variable `org-display-custom-times' is set."
16800 (when org-display-custom-times
16801 (save-match-data
16802 (let* ((start 0)
16803 (re org-ts-regexp-both)
16804 t1 with-hm inactive tf time str beg end)
16805 (while (setq start (string-match re string start))
16806 (setq beg (match-beginning 0)
16807 end (match-end 0)
16808 t1 (save-match-data
16809 (org-parse-time-string (substring string beg end) t))
16810 with-hm (and (nth 1 t1) (nth 2 t1))
16811 inactive (equal (substring string beg (1+ beg)) "[")
16812 tf (funcall (if with-hm 'cdr 'car)
16813 org-time-stamp-custom-formats)
16814 time (org-fix-decoded-time t1)
16815 str (format-time-string
16816 (concat
16817 (if inactive "[" "<") (substring tf 1 -1)
16818 (if inactive "]" ">"))
16819 (apply 'encode-time time))
16820 string (replace-match str t t string)
16821 start (+ start (length str)))))))
16822 string)
16824 (defun org-fix-decoded-time (time)
16825 "Set 0 instead of nil for the first 6 elements of time.
16826 Don't touch the rest."
16827 (let ((n 0))
16828 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16830 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16832 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16833 "Difference between TIMESTAMP-STRING and now in days.
16834 If SECONDS is non-nil, return the difference in seconds."
16835 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16836 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16837 (funcall fdiff (current-time)))))
16839 (defun org-deadline-close (timestamp-string &optional ndays)
16840 "Is the time in TIMESTAMP-STRING close to the current date?"
16841 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16842 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16843 (not (org-entry-is-done-p))))
16845 (defun org-get-wdays (ts &optional delay zero-delay)
16846 "Get the deadline lead time appropriate for timestring TS.
16847 When DELAY is non-nil, get the delay time for scheduled items
16848 instead of the deadline lead time. When ZERO-DELAY is non-nil
16849 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16850 don't try to find the delay cookie in the scheduled timestamp."
16851 (let ((tv (if delay org-scheduled-delay-days
16852 org-deadline-warning-days)))
16853 (cond
16854 ((or (and delay (< tv 0))
16855 (and delay zero-delay (<= tv 0))
16856 (and (not delay) (<= tv 0)))
16857 ;; Enforce this value no matter what
16858 (- tv))
16859 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16860 ;; lead time is specified.
16861 (floor (* (string-to-number (match-string 1 ts))
16862 (cdr (assoc (match-string 2 ts)
16863 '(("d" . 1) ("w" . 7)
16864 ("m" . 30.4) ("y" . 365.25)
16865 ("h" . 0.041667)))))))
16866 ;; go for the default.
16867 (t tv))))
16869 (defun org-calendar-select-mouse (ev)
16870 "Return to `org-read-date' with the date currently selected.
16871 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16872 (interactive "e")
16873 (mouse-set-point ev)
16874 (when (calendar-cursor-to-date)
16875 (let* ((date (calendar-cursor-to-date))
16876 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16877 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16878 (if (active-minibuffer-window) (exit-minibuffer))))
16880 (defun org-check-deadlines (ndays)
16881 "Check if there are any deadlines due or past due.
16882 A deadline is considered due if it happens within `org-deadline-warning-days'
16883 days from today's date. If the deadline appears in an entry marked DONE,
16884 it is not shown. The prefix arg NDAYS can be used to test that many
16885 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16886 (interactive "P")
16887 (let* ((org-warn-days
16888 (cond
16889 ((equal ndays '(4)) 100000)
16890 (ndays (prefix-numeric-value ndays))
16891 (t (abs org-deadline-warning-days))))
16892 (case-fold-search nil)
16893 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16894 (callback
16895 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16897 (message "%d deadlines past-due or due within %d days"
16898 (org-occur regexp nil callback)
16899 org-warn-days)))
16901 (defsubst org-re-timestamp (type)
16902 "Return a regexp for timestamp TYPE.
16903 Allowed values for TYPE are:
16905 all: all timestamps
16906 active: only active timestamps (<...>)
16907 inactive: only inactive timestamps ([...])
16908 scheduled: only scheduled timestamps
16909 deadline: only deadline timestamps
16910 closed: only closed time-stamps
16912 When TYPE is nil, fall back on returning a regexp that matches
16913 both scheduled and deadline timestamps."
16914 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16915 ((eq type 'active) org-ts-regexp)
16916 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16917 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16918 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16919 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16920 ((eq type 'scheduled-or-deadline)
16921 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16923 (defun org-check-before-date (date)
16924 "Check if there are deadlines or scheduled entries before DATE."
16925 (interactive (list (org-read-date)))
16926 (let ((case-fold-search nil)
16927 (regexp (org-re-timestamp org-ts-type))
16928 (callback
16929 (lambda () (time-less-p
16930 (org-time-string-to-time (match-string 1))
16931 (org-time-string-to-time date)))))
16932 (message "%d entries before %s"
16933 (org-occur regexp nil callback) date)))
16935 (defun org-check-after-date (date)
16936 "Check if there are deadlines or scheduled entries after DATE."
16937 (interactive (list (org-read-date)))
16938 (let ((case-fold-search nil)
16939 (regexp (org-re-timestamp org-ts-type))
16940 (callback
16941 (lambda () (not
16942 (time-less-p
16943 (org-time-string-to-time (match-string 1))
16944 (org-time-string-to-time date))))))
16945 (message "%d entries after %s"
16946 (org-occur regexp nil callback) date)))
16948 (defun org-check-dates-range (start-date end-date)
16949 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16950 (interactive (list (org-read-date nil nil nil "Range starts")
16951 (org-read-date nil nil nil "Range end")))
16952 (let ((case-fold-search nil)
16953 (regexp (org-re-timestamp org-ts-type))
16954 (callback
16955 (lambda ()
16956 (let ((match (match-string 1)))
16957 (and
16958 (not (time-less-p
16959 (org-time-string-to-time match)
16960 (org-time-string-to-time start-date)))
16961 (time-less-p
16962 (org-time-string-to-time match)
16963 (org-time-string-to-time end-date)))))))
16964 (message "%d entries between %s and %s"
16965 (org-occur regexp nil callback) start-date end-date)))
16967 (defun org-evaluate-time-range (&optional to-buffer)
16968 "Evaluate a time range by computing the difference between start and end.
16969 Normally the result is just printed in the echo area, but with prefix arg
16970 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16971 If the time range is actually in a table, the result is inserted into the
16972 next column.
16973 For time difference computation, a year is assumed to be exactly 365
16974 days in order to avoid rounding problems."
16975 (interactive "P")
16977 (org-clock-update-time-maybe)
16978 (save-excursion
16979 (unless (org-at-date-range-p t)
16980 (goto-char (point-at-bol))
16981 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16982 (if (not (org-at-date-range-p t))
16983 (user-error "Not at a time-stamp range, and none found in current line")))
16984 (let* ((ts1 (match-string 1))
16985 (ts2 (match-string 2))
16986 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16987 (match-end (match-end 0))
16988 (time1 (org-time-string-to-time ts1))
16989 (time2 (org-time-string-to-time ts2))
16990 (t1 (org-float-time time1))
16991 (t2 (org-float-time time2))
16992 (diff (abs (- t2 t1)))
16993 (negative (< (- t2 t1) 0))
16994 ;; (ys (floor (* 365 24 60 60)))
16995 (ds (* 24 60 60))
16996 (hs (* 60 60))
16997 (fy "%dy %dd %02d:%02d")
16998 (fy1 "%dy %dd")
16999 (fd "%dd %02d:%02d")
17000 (fd1 "%dd")
17001 (fh "%02d:%02d")
17002 y d h m align)
17003 (if havetime
17004 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17006 d (floor (/ diff ds)) diff (mod diff ds)
17007 h (floor (/ diff hs)) diff (mod diff hs)
17008 m (floor (/ diff 60)))
17009 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17011 d (floor (+ (/ diff ds) 0.5))
17012 h 0 m 0))
17013 (if (not to-buffer)
17014 (message "%s" (org-make-tdiff-string y d h m))
17015 (if (org-at-table-p)
17016 (progn
17017 (goto-char match-end)
17018 (setq align t)
17019 (and (looking-at " *|") (goto-char (match-end 0))))
17020 (goto-char match-end))
17021 (if (looking-at
17022 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17023 (replace-match ""))
17024 (if negative (insert " -"))
17025 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17026 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17027 (insert " " (format fh h m))))
17028 (if align (org-table-align))
17029 (message "Time difference inserted")))))
17031 (defun org-make-tdiff-string (y d h m)
17032 (let ((fmt "")
17033 (l nil))
17034 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17035 l (push y l)))
17036 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17037 l (push d l)))
17038 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17039 l (push h l)))
17040 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17041 l (push m l)))
17042 (apply 'format fmt (nreverse l))))
17044 (defun org-time-string-to-time (s &optional buffer pos)
17045 "Convert a timestamp string into internal time."
17046 (condition-case errdata
17047 (apply 'encode-time (org-parse-time-string s))
17048 (error (error "Bad timestamp `%s'%s\nError was: %s"
17049 s (if (not (and buffer pos))
17051 (format " at %d in buffer `%s'" pos buffer))
17052 (cdr errdata)))))
17054 (defun org-time-string-to-seconds (s)
17055 "Convert a timestamp string to a number of seconds."
17056 (org-float-time (org-time-string-to-time s)))
17058 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17059 "Convert a time stamp to an absolute day number.
17060 If there is a specifier for a cyclic time stamp, get the closest
17061 date to DAYNR.
17062 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17063 The variable `date' is bound by the calendar when this is called."
17064 (cond
17065 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17066 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17067 daynr
17068 (+ daynr 1000)))
17069 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17070 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17071 (time-to-days (current-time))) (match-string 0 s)
17072 prefer show-all))
17073 (t (time-to-days
17074 (condition-case errdata
17075 (apply 'encode-time (org-parse-time-string s))
17076 (error (error "Bad timestamp `%s'%s\nError was: %s"
17077 s (if (not (and buffer pos))
17079 (format " at %d in buffer `%s'" pos buffer))
17080 (cdr errdata))))))))
17082 (defun org-days-to-iso-week (days)
17083 "Return the iso week number."
17084 (require 'cal-iso)
17085 (car (calendar-iso-from-absolute days)))
17087 (defun org-small-year-to-year (year)
17088 "Convert 2-digit years into 4-digit years.
17089 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17090 The year 2000 cannot be abbreviated. Any year larger than 99
17091 is returned unchanged."
17092 (if (< year 38)
17093 (setq year (+ 2000 year))
17094 (if (< year 100)
17095 (setq year (+ 1900 year))))
17096 year)
17098 (defun org-time-from-absolute (d)
17099 "Return the time corresponding to date D.
17100 D may be an absolute day number, or a calendar-type list (month day year)."
17101 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17102 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17104 (defun org-calendar-holiday ()
17105 "List of holidays, for Diary display in Org-mode."
17106 (require 'holidays)
17107 (let ((hl (funcall
17108 (if (fboundp 'calendar-check-holidays)
17109 'calendar-check-holidays 'check-calendar-holidays) date)))
17110 (if hl (mapconcat 'identity hl "; "))))
17112 (defun org-diary-sexp-entry (sexp entry date)
17113 "Process a SEXP diary ENTRY for DATE."
17114 (require 'diary-lib)
17115 (let ((result (if calendar-debug-sexp
17116 (let ((stack-trace-on-error t))
17117 (eval (car (read-from-string sexp))))
17118 (condition-case nil
17119 (eval (car (read-from-string sexp)))
17120 (error
17121 (beep)
17122 (message "Bad sexp at line %d in %s: %s"
17123 (org-current-line)
17124 (buffer-file-name) sexp)
17125 (sleep-for 2))))))
17126 (cond ((stringp result) (split-string result "; "))
17127 ((and (consp result)
17128 (not (consp (cdr result)))
17129 (stringp (cdr result))) (cdr result))
17130 ((and (consp result)
17131 (stringp (car result))) result)
17132 (result entry))))
17134 (defun org-diary-to-ical-string (frombuf)
17135 "Get iCalendar entries from diary entries in buffer FROMBUF.
17136 This uses the icalendar.el library."
17137 (let* ((tmpdir (if (featurep 'xemacs)
17138 (temp-directory)
17139 temporary-file-directory))
17140 (tmpfile (make-temp-name
17141 (expand-file-name "orgics" tmpdir)))
17142 buf rtn b e)
17143 (with-current-buffer frombuf
17144 (icalendar-export-region (point-min) (point-max) tmpfile)
17145 (setq buf (find-buffer-visiting tmpfile))
17146 (set-buffer buf)
17147 (goto-char (point-min))
17148 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17149 (setq b (match-beginning 0)))
17150 (goto-char (point-max))
17151 (if (re-search-backward "^END:VEVENT" nil t)
17152 (setq e (match-end 0)))
17153 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17154 (kill-buffer buf)
17155 (delete-file tmpfile)
17156 rtn))
17158 (defun org-closest-date (start current change prefer show-all)
17159 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17160 When PREFER is `past', return a date that is either CURRENT or past.
17161 When PREFER is `future', return a date that is either CURRENT or future.
17162 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17163 ;; Make the proper lists from the dates
17164 (catch 'exit
17165 (let ((a1 '(("h" . hour)
17166 ("d" . day)
17167 ("w" . week)
17168 ("m" . month)
17169 ("y" . year)))
17170 (shour (nth 2 (org-parse-time-string start)))
17171 dn dw sday cday n1 n2 n0
17172 d m y y1 y2 date1 date2 nmonths nm ny m2)
17174 (setq start (org-date-to-gregorian start)
17175 current (org-date-to-gregorian
17176 (if show-all
17177 current
17178 (time-to-days (current-time))))
17179 sday (calendar-absolute-from-gregorian start)
17180 cday (calendar-absolute-from-gregorian current))
17182 (if (<= cday sday) (throw 'exit sday))
17184 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17185 (setq dn (string-to-number (match-string 1 change))
17186 dw (cdr (assoc (match-string 2 change) a1)))
17187 (user-error "Invalid change specifier: %s" change))
17188 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17189 (cond
17190 ((eq dw 'hour)
17191 (let ((missing-hours
17192 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17193 dn)))
17194 (setq n1 (if (zerop missing-hours) cday
17195 (- cday (1+ (floor (/ missing-hours 24)))))
17196 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17197 ((eq dw 'day)
17198 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17199 n2 (+ n1 dn)))
17200 ((eq dw 'year)
17201 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17202 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17203 (setq date1 (list m d y1)
17204 n1 (calendar-absolute-from-gregorian date1)
17205 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17206 n2 (calendar-absolute-from-gregorian date2)))
17207 ((eq dw 'month)
17208 ;; approx number of month between the two dates
17209 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17210 ;; How often does dn fit in there?
17211 (setq d (nth 1 start) m (car start) y (nth 2 start)
17212 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17213 m (+ m nm)
17214 ny (floor (/ m 12))
17215 y (+ y ny)
17216 m (- m (* ny 12)))
17217 (while (> m 12) (setq m (- m 12) y (1+ y)))
17218 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17219 (setq m2 (+ m dn) y2 y)
17220 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17221 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17222 (while (<= n2 cday)
17223 (setq n1 n2 m m2 y y2)
17224 (setq m2 (+ m dn) y2 y)
17225 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17226 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17227 ;; Make sure n1 is the earlier date
17228 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17229 (if show-all
17230 (cond
17231 ((eq prefer 'past) (if (= cday n2) n2 n1))
17232 ((eq prefer 'future) (if (= cday n1) n1 n2))
17233 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17234 (cond
17235 ((eq prefer 'past) (if (= cday n2) n2 n1))
17236 ((eq prefer 'future) (if (= cday n1) n1 n2))
17237 (t (if (= cday n1) n1 n2)))))))
17239 (defun org-date-to-gregorian (date)
17240 "Turn any specification of DATE into a Gregorian date for the calendar."
17241 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17242 ((and (listp date) (= (length date) 3)) date)
17243 ((stringp date)
17244 (setq date (org-parse-time-string date))
17245 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17246 ((listp date)
17247 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17249 (defun org-parse-time-string (s &optional nodefault)
17250 "Parse the standard Org-mode time string.
17251 This should be a lot faster than the normal `parse-time-string'.
17252 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17253 hour and minute fields will be nil if not given."
17254 (cond ((string-match org-ts-regexp0 s)
17255 (list 0
17256 (if (or (match-beginning 8) (not nodefault))
17257 (string-to-number (or (match-string 8 s) "0")))
17258 (if (or (match-beginning 7) (not nodefault))
17259 (string-to-number (or (match-string 7 s) "0")))
17260 (string-to-number (match-string 4 s))
17261 (string-to-number (match-string 3 s))
17262 (string-to-number (match-string 2 s))
17263 nil nil nil))
17264 ((string-match "^<[^>]+>$" s)
17265 (decode-time (seconds-to-time (org-matcher-time s))))
17266 (t (error "Not a standard Org-mode time string: %s" s))))
17268 (defun org-timestamp-up (&optional arg)
17269 "Increase the date item at the cursor by one.
17270 If the cursor is on the year, change the year. If it is on the month,
17271 the day or the time, change that.
17272 With prefix ARG, change by that many units."
17273 (interactive "p")
17274 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17276 (defun org-timestamp-down (&optional arg)
17277 "Decrease the date item at the cursor by one.
17278 If the cursor is on the year, change the year. If it is on the month,
17279 the day or the time, change that.
17280 With prefix ARG, change by that many units."
17281 (interactive "p")
17282 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17284 (defun org-timestamp-up-day (&optional arg)
17285 "Increase the date in the time stamp by one day.
17286 With prefix ARG, change that many days."
17287 (interactive "p")
17288 (if (and (not (org-at-timestamp-p t))
17289 (org-at-heading-p))
17290 (org-todo 'up)
17291 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17293 (defun org-timestamp-down-day (&optional arg)
17294 "Decrease the date in the time stamp by one day.
17295 With prefix ARG, change that many days."
17296 (interactive "p")
17297 (if (and (not (org-at-timestamp-p t))
17298 (org-at-heading-p))
17299 (org-todo 'down)
17300 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17302 (defun org-at-timestamp-p (&optional inactive-ok)
17303 "Determine if the cursor is in or at a timestamp."
17304 (interactive)
17305 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17306 (pos (point))
17307 (ans (or (looking-at tsr)
17308 (save-excursion
17309 (skip-chars-backward "^[<\n\r\t")
17310 (if (> (point) (point-min)) (backward-char 1))
17311 (and (looking-at tsr)
17312 (> (- (match-end 0) pos) -1))))))
17313 (and ans
17314 (boundp 'org-ts-what)
17315 (setq org-ts-what
17316 (cond
17317 ((= pos (match-beginning 0)) 'bracket)
17318 ;; Point is considered to be "on the bracket" whether
17319 ;; it's really on it or right after it.
17320 ((= pos (1- (match-end 0))) 'bracket)
17321 ((= pos (match-end 0)) 'after)
17322 ((org-pos-in-match-range pos 2) 'year)
17323 ((org-pos-in-match-range pos 3) 'month)
17324 ((org-pos-in-match-range pos 7) 'hour)
17325 ((org-pos-in-match-range pos 8) 'minute)
17326 ((or (org-pos-in-match-range pos 4)
17327 (org-pos-in-match-range pos 5)) 'day)
17328 ((and (> pos (or (match-end 8) (match-end 5)))
17329 (< pos (match-end 0)))
17330 (- pos (or (match-end 8) (match-end 5))))
17331 (t 'day))))
17332 ans))
17334 (defun org-toggle-timestamp-type ()
17335 "Toggle the type (<active> or [inactive]) of a time stamp."
17336 (interactive)
17337 (when (org-at-timestamp-p t)
17338 (let ((beg (match-beginning 0)) (end (match-end 0))
17339 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17340 (save-excursion
17341 (goto-char beg)
17342 (while (re-search-forward "[][<>]" end t)
17343 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17344 t t)))
17345 (message "Timestamp is now %sactive"
17346 (if (equal (char-after beg) ?<) "" "in")))))
17348 (defun org-at-clock-log-p nil
17349 "Is the cursor on the clock log line?"
17350 (save-excursion
17351 (move-beginning-of-line 1)
17352 (looking-at "^[ \t]*CLOCK:")))
17354 (defvar org-clock-history) ; defined in org-clock.el
17355 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17356 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17357 "Change the date in the time stamp at point.
17358 The date will be changed by N times WHAT. WHAT can be `day', `month',
17359 `year', `minute', `second'. If WHAT is not given, the cursor position
17360 in the timestamp determines what will be changed.
17361 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17362 (let ((origin (point)) origin-cat
17363 with-hm inactive
17364 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17365 org-ts-what
17366 extra rem
17367 ts time time0 fixnext clrgx)
17368 (if (not (org-at-timestamp-p t))
17369 (user-error "Not at a timestamp"))
17370 (if (and (not what) (eq org-ts-what 'bracket))
17371 (org-toggle-timestamp-type)
17372 ;; Point isn't on brackets. Remember the part of the time-stamp
17373 ;; the point was in. Indeed, size of time-stamps may change,
17374 ;; but point must be kept in the same category nonetheless.
17375 (setq origin-cat org-ts-what)
17376 (if (and (not what) (not (eq org-ts-what 'day))
17377 org-display-custom-times
17378 (get-text-property (point) 'display)
17379 (not (get-text-property (1- (point)) 'display)))
17380 (setq org-ts-what 'day))
17381 (setq org-ts-what (or what org-ts-what)
17382 inactive (= (char-after (match-beginning 0)) ?\[)
17383 ts (match-string 0))
17384 (replace-match "")
17385 (when (string-match
17386 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17388 (setq extra (match-string 1 ts))
17389 (if suppress-tmp-delay
17390 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17391 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17392 (setq with-hm t))
17393 (setq time0 (org-parse-time-string ts))
17394 (when (and updown
17395 (eq org-ts-what 'minute)
17396 (not current-prefix-arg))
17397 ;; This looks like s-up and s-down. Change by one rounding step.
17398 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17399 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17400 (setcar (cdr time0) (+ (nth 1 time0)
17401 (if (> n 0) (- rem) (- dm rem))))))
17402 (setq time
17403 (encode-time (or (car time0) 0)
17404 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17405 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17406 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17407 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17408 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17409 (nthcdr 6 time0)))
17410 (when (and (member org-ts-what '(hour minute))
17411 extra
17412 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17413 (setq extra (org-modify-ts-extra
17414 extra
17415 (if (eq org-ts-what 'hour) 2 5)
17416 n dm)))
17417 (when (integerp org-ts-what)
17418 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17419 (if (eq what 'calendar)
17420 (let ((cal-date (org-get-date-from-calendar)))
17421 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17422 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17423 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17424 (setcar time0 (or (car time0) 0))
17425 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17426 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17427 (setq time (apply 'encode-time time0))))
17428 ;; Insert the new time-stamp, and ensure point stays in the same
17429 ;; category as before (i.e. not after the last position in that
17430 ;; category).
17431 (let ((pos (point)))
17432 ;; Stay before inserted string. `save-excursion' is of no use.
17433 (setq org-last-changed-timestamp
17434 (org-insert-time-stamp time with-hm inactive nil nil extra))
17435 (goto-char pos))
17436 (save-match-data
17437 (looking-at org-ts-regexp3)
17438 (goto-char (cond
17439 ;; `day' category ends before `hour' if any, or at
17440 ;; the end of the day name.
17441 ((eq origin-cat 'day)
17442 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17443 ((eq origin-cat 'hour) (min (match-end 7) origin))
17444 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17445 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17446 ;; `year' and `month' have both fixed size: point
17447 ;; couldn't have moved into another part.
17448 (t origin))))
17449 ;; Update clock if on a CLOCK line.
17450 (org-clock-update-time-maybe)
17451 ;; Maybe adjust the closest clock in `org-clock-history'
17452 (when org-clock-adjust-closest
17453 (if (not (and (org-at-clock-log-p)
17454 (< 1 (length (delq nil (mapcar 'marker-position
17455 org-clock-history))))))
17456 (message "No clock to adjust")
17457 (cond ((save-excursion ; fix previous clock?
17458 (re-search-backward org-ts-regexp0 nil t)
17459 (org-looking-back (concat org-clock-string " \\[")))
17460 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17461 ((save-excursion ; fix next clock?
17462 (re-search-backward org-ts-regexp0 nil t)
17463 (looking-at (concat org-ts-regexp0 "\\] =>")))
17464 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17465 (save-window-excursion
17466 ;; Find closest clock to point, adjust the previous/next one in history
17467 (let* ((p (save-excursion (org-back-to-heading t)))
17468 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17469 (clfixnth
17470 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17471 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17472 (if (not clfixpos)
17473 (message "No clock to adjust")
17474 (save-excursion
17475 (org-goto-marker-or-bmk clfixpos)
17476 (org-show-subtree)
17477 (when (re-search-forward clrgx nil t)
17478 (goto-char (match-beginning 1))
17479 (let (org-clock-adjust-closest)
17480 (org-timestamp-change n org-ts-what updown))
17481 (message "Clock adjusted in %s for heading: %s"
17482 (file-name-nondirectory (buffer-file-name))
17483 (org-get-heading t t)))))))))
17484 ;; Try to recenter the calendar window, if any.
17485 (if (and org-calendar-follow-timestamp-change
17486 (get-buffer-window "*Calendar*" t)
17487 (memq org-ts-what '(day month year)))
17488 (org-recenter-calendar (time-to-days time))))))
17490 (defun org-modify-ts-extra (s pos n dm)
17491 "Change the different parts of the lead-time and repeat fields in timestamp."
17492 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17493 ng h m new rem)
17494 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17495 (cond
17496 ((or (org-pos-in-match-range pos 2)
17497 (org-pos-in-match-range pos 3))
17498 (setq m (string-to-number (match-string 3 s))
17499 h (string-to-number (match-string 2 s)))
17500 (if (org-pos-in-match-range pos 2)
17501 (setq h (+ h n))
17502 (setq n (* dm (org-no-warnings (signum n))))
17503 (when (not (= 0 (setq rem (% m dm))))
17504 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17505 (setq m (+ m n)))
17506 (if (< m 0) (setq m (+ m 60) h (1- h)))
17507 (if (> m 59) (setq m (- m 60) h (1+ h)))
17508 (setq h (min 24 (max 0 h)))
17509 (setq ng 1 new (format "-%02d:%02d" h m)))
17510 ((org-pos-in-match-range pos 6)
17511 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17512 ((org-pos-in-match-range pos 5)
17513 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17515 ((org-pos-in-match-range pos 9)
17516 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17517 ((org-pos-in-match-range pos 8)
17518 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17520 (when ng
17521 (setq s (concat
17522 (substring s 0 (match-beginning ng))
17524 (substring s (match-end ng))))))
17527 (defun org-recenter-calendar (date)
17528 "If the calendar is visible, recenter it to DATE."
17529 (let ((cwin (get-buffer-window "*Calendar*" t)))
17530 (when cwin
17531 (let ((calendar-move-hook nil))
17532 (with-selected-window cwin
17533 (calendar-goto-date (if (listp date) date
17534 (calendar-gregorian-from-absolute date))))))))
17536 (defun org-goto-calendar (&optional arg)
17537 "Go to the Emacs calendar at the current date.
17538 If there is a time stamp in the current line, go to that date.
17539 A prefix ARG can be used to force the current date."
17540 (interactive "P")
17541 (let ((tsr org-ts-regexp) diff
17542 (calendar-move-hook nil)
17543 (calendar-view-holidays-initially-flag nil)
17544 (calendar-view-diary-initially-flag nil))
17545 (if (or (org-at-timestamp-p)
17546 (save-excursion
17547 (beginning-of-line 1)
17548 (looking-at (concat ".*" tsr))))
17549 (let ((d1 (time-to-days (current-time)))
17550 (d2 (time-to-days
17551 (org-time-string-to-time (match-string 1)))))
17552 (setq diff (- d2 d1))))
17553 (calendar)
17554 (calendar-goto-today)
17555 (if (and diff (not arg)) (calendar-forward-day diff))))
17557 (defun org-get-date-from-calendar ()
17558 "Return a list (month day year) of date at point in calendar."
17559 (with-current-buffer "*Calendar*"
17560 (save-match-data
17561 (calendar-cursor-to-date))))
17563 (defun org-date-from-calendar ()
17564 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17565 If there is already a time stamp at the cursor position, update it."
17566 (interactive)
17567 (if (org-at-timestamp-p t)
17568 (org-timestamp-change 0 'calendar)
17569 (let ((cal-date (org-get-date-from-calendar)))
17570 (org-insert-time-stamp
17571 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17573 (defcustom org-effort-durations
17574 `(("h" . 60)
17575 ("d" . ,(* 60 8))
17576 ("w" . ,(* 60 8 5))
17577 ("m" . ,(* 60 8 5 4))
17578 ("y" . ,(* 60 8 5 40)))
17579 "Conversion factor to minutes for an effort modifier.
17581 Each entry has the form (MODIFIER . MINUTES).
17583 In an effort string, a number followed by MODIFIER is multiplied
17584 by the specified number of MINUTES to obtain an effort in
17585 minutes.
17587 For example, if the value of this variable is ((\"hours\" . 60)), then an
17588 effort string \"2hours\" is equivalent to 120 minutes."
17589 :group 'org-agenda
17590 :version "24.1"
17591 :type '(alist :key-type (string :tag "Modifier")
17592 :value-type (number :tag "Minutes")))
17594 (defun org-minutes-to-clocksum-string (m)
17595 "Format number of minutes as a clocksum string.
17596 The format is determined by `org-time-clocksum-format',
17597 `org-time-clocksum-use-fractional' and
17598 `org-time-clocksum-fractional-format' and
17599 `org-time-clocksum-use-effort-durations'."
17600 (let ((clocksum "")
17601 (m (round m)) ; Don't allow fractions of minutes
17602 h d w mo y fmt n)
17603 (setq h (if org-time-clocksum-use-effort-durations
17604 (cdr (assoc "h" org-effort-durations)) 60)
17605 d (if org-time-clocksum-use-effort-durations
17606 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17607 w (if org-time-clocksum-use-effort-durations
17608 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17609 mo (if org-time-clocksum-use-effort-durations
17610 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17611 y (if org-time-clocksum-use-effort-durations
17612 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17613 ;; fractional format
17614 (if org-time-clocksum-use-fractional
17615 (cond
17616 ;; single format string
17617 ((stringp org-time-clocksum-fractional-format)
17618 (format org-time-clocksum-fractional-format (/ m (float h))))
17619 ;; choice of fractional formats for different time units
17620 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17621 (> (/ (truncate m) (* y d h)) 0))
17622 (format fmt (/ m (* y d (float h)))))
17623 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17624 (> (/ (truncate m) (* mo d h)) 0))
17625 (format fmt (/ m (* mo d (float h)))))
17626 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17627 (> (/ (truncate m) (* w d h)) 0))
17628 (format fmt (/ m (* w d (float h)))))
17629 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17630 (> (/ (truncate m) (* d h)) 0))
17631 (format fmt (/ m (* d (float h)))))
17632 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17633 (> (/ (truncate m) h) 0))
17634 (format fmt (/ m (float h))))
17635 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17636 (format fmt m))
17637 ;; fall back to smallest time unit with a format
17638 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17639 (format fmt (/ m (float h))))
17640 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17641 (format fmt (/ m (* d (float h)))))
17642 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17643 (format fmt (/ m (* w d (float h)))))
17644 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17645 (format fmt (/ m (* mo d (float h)))))
17646 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17647 (format fmt (/ m (* y d (float h))))))
17648 ;; standard (non-fractional) format, with single format string
17649 (if (stringp org-time-clocksum-format)
17650 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17651 ;; separate formats components
17652 (and (setq fmt (plist-get org-time-clocksum-format :years))
17653 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17654 (plist-get org-time-clocksum-format :require-years))
17655 (setq clocksum (concat clocksum (format fmt n))
17656 m (- m (* n y d h))))
17657 (and (setq fmt (plist-get org-time-clocksum-format :months))
17658 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17659 (plist-get org-time-clocksum-format :require-months))
17660 (setq clocksum (concat clocksum (format fmt n))
17661 m (- m (* n mo d h))))
17662 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17663 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17664 (plist-get org-time-clocksum-format :require-weeks))
17665 (setq clocksum (concat clocksum (format fmt n))
17666 m (- m (* n w d h))))
17667 (and (setq fmt (plist-get org-time-clocksum-format :days))
17668 (or (> (setq n (/ (truncate m) (* d h))) 0)
17669 (plist-get org-time-clocksum-format :require-days))
17670 (setq clocksum (concat clocksum (format fmt n))
17671 m (- m (* n d h))))
17672 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17673 (or (> (setq n (/ (truncate m) h)) 0)
17674 (plist-get org-time-clocksum-format :require-hours))
17675 (setq clocksum (concat clocksum (format fmt n))
17676 m (- m (* n h))))
17677 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17678 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17679 (setq clocksum (concat clocksum (format fmt m))))
17680 ;; return formatted time duration
17681 clocksum))))
17683 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17684 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17685 "Org mode version 8.0")
17687 (defun org-hours-to-clocksum-string (n)
17688 (org-minutes-to-clocksum-string (* n 60)))
17690 (defun org-hh:mm-string-to-minutes (s)
17691 "Convert a string H:MM to a number of minutes.
17692 If the string is just a number, interpret it as minutes.
17693 In fact, the first hh:mm or number in the string will be taken,
17694 there can be extra stuff in the string.
17695 If no number is found, the return value is 0."
17696 (cond
17697 ((integerp s) s)
17698 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17699 (+ (* (string-to-number (match-string 1 s)) 60)
17700 (string-to-number (match-string 2 s))))
17701 ((string-match "\\([0-9]+\\)" s)
17702 (string-to-number (match-string 1 s)))
17703 (t 0)))
17705 (defcustom org-image-actual-width t
17706 "Should we use the actual width of images when inlining them?
17708 When set to `t', always use the image width.
17710 When set to a number, use imagemagick (when available) to set
17711 the image's width to this value.
17713 When set to a number in a list, try to get the width from any
17714 #+ATTR.* keyword if it matches a width specification like
17716 #+ATTR_HTML: :width 300px
17718 and fall back on that number if none is found.
17720 When set to nil, try to get the width from an #+ATTR.* keyword
17721 and fall back on the original width if none is found.
17723 This requires Emacs >= 24.1, build with imagemagick support."
17724 :group 'org-appearance
17725 :version "24.4"
17726 :package-version '(Org . "8.0")
17727 :type '(choice
17728 (const :tag "Use the image width" t)
17729 (integer :tag "Use a number of pixels")
17730 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17731 (const :tag "Use #+ATTR* or don't resize" nil)))
17733 (defcustom org-agenda-inhibit-startup nil
17734 "Inhibit startup when preparing agenda buffers.
17735 When this variable is `t' (the default), the initialization of
17736 the Org agenda buffers is inhibited: e.g. the visibility state
17737 is not set, the tables are not re-aligned, etc."
17738 :type 'boolean
17739 :version "24.3"
17740 :group 'org-agenda)
17742 (defcustom org-agenda-ignore-drawer-properties nil
17743 "Avoid updating text properties when building the agenda.
17744 Properties are used to prepare buffers for effort estimates, appointments,
17745 and subtree-local categories.
17746 If you don't use these in the agenda, you can add them to this list and
17747 agenda building will be a bit faster.
17748 The value is a list, with zero or more of the symbols `effort', `appt',
17749 or `category'."
17750 :type '(set :greedy t
17751 (const effort)
17752 (const appt)
17753 (const category))
17754 :version "24.3"
17755 :group 'org-agenda)
17757 (defun org-duration-string-to-minutes (s &optional output-to-string)
17758 "Convert a duration string S to minutes.
17760 A bare number is interpreted as minutes, modifiers can be set by
17761 customizing `org-effort-durations' (which see).
17763 Entries containing a colon are interpreted as H:MM by
17764 `org-hh:mm-string-to-minutes'."
17765 (let ((result 0)
17766 (re (concat "\\([0-9.]+\\) *\\("
17767 (regexp-opt (mapcar 'car org-effort-durations))
17768 "\\)")))
17769 (while (string-match re s)
17770 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17771 (string-to-number (match-string 1 s))))
17772 (setq s (replace-match "" nil t s)))
17773 (setq result (floor result))
17774 (incf result (org-hh:mm-string-to-minutes s))
17775 (if output-to-string (number-to-string result) result)))
17777 ;;;; Files
17779 (defun org-save-all-org-buffers ()
17780 "Save all Org-mode buffers without user confirmation."
17781 (interactive)
17782 (message "Saving all Org-mode buffers...")
17783 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17784 (when (featurep 'org-id) (org-id-locations-save))
17785 (message "Saving all Org-mode buffers... done"))
17787 (defun org-revert-all-org-buffers ()
17788 "Revert all Org-mode buffers.
17789 Prompt for confirmation when there are unsaved changes.
17790 Be sure you know what you are doing before letting this function
17791 overwrite your changes.
17793 This function is useful in a setup where one tracks org files
17794 with a version control system, to revert on one machine after pulling
17795 changes from another. I believe the procedure must be like this:
17797 1. M-x org-save-all-org-buffers
17798 2. Pull changes from the other machine, resolve conflicts
17799 3. M-x org-revert-all-org-buffers"
17800 (interactive)
17801 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17802 (user-error "Abort"))
17803 (save-excursion
17804 (save-window-excursion
17805 (mapc
17806 (lambda (b)
17807 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17808 (with-current-buffer b buffer-file-name))
17809 (org-pop-to-buffer-same-window b)
17810 (revert-buffer t 'no-confirm)))
17811 (buffer-list))
17812 (when (and (featurep 'org-id) org-id-track-globally)
17813 (org-id-locations-load)))))
17815 ;;;; Agenda files
17817 ;;;###autoload
17818 (defun org-switchb (&optional arg)
17819 "Switch between Org buffers.
17820 With one prefix argument, restrict available buffers to files.
17821 With two prefix arguments, restrict available buffers to agenda files.
17823 Defaults to `iswitchb' for buffer name completion.
17824 Set `org-completion-use-ido' to make it use ido instead."
17825 (interactive "P")
17826 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17827 ((equal arg '(16)) (org-buffer-list 'agenda))
17828 (t (org-buffer-list))))
17829 (org-completion-use-iswitchb org-completion-use-iswitchb)
17830 (org-completion-use-ido org-completion-use-ido))
17831 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17832 (setq org-completion-use-iswitchb t))
17833 (org-pop-to-buffer-same-window
17834 (org-icompleting-read "Org buffer: "
17835 (mapcar 'list (mapcar 'buffer-name blist))
17836 nil t))))
17838 ;;; Define some older names previously used for this functionality
17839 ;;;###autoload
17840 (defalias 'org-ido-switchb 'org-switchb)
17841 ;;;###autoload
17842 (defalias 'org-iswitchb 'org-switchb)
17844 (defun org-buffer-list (&optional predicate exclude-tmp)
17845 "Return a list of Org buffers.
17846 PREDICATE can be `export', `files' or `agenda'.
17848 export restrict the list to Export buffers.
17849 files restrict the list to buffers visiting Org files.
17850 agenda restrict the list to buffers visiting agenda files.
17852 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17853 (let* ((bfn nil)
17854 (agenda-files (and (eq predicate 'agenda)
17855 (mapcar 'file-truename (org-agenda-files t))))
17856 (filter
17857 (cond
17858 ((eq predicate 'files)
17859 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17860 ((eq predicate 'export)
17861 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17862 ((eq predicate 'agenda)
17863 (lambda (b)
17864 (with-current-buffer b
17865 (and (derived-mode-p 'org-mode)
17866 (setq bfn (buffer-file-name b))
17867 (member (file-truename bfn) agenda-files)))))
17868 (t (lambda (b) (with-current-buffer b
17869 (or (derived-mode-p 'org-mode)
17870 (string-match "\*Org .*Export"
17871 (buffer-name b)))))))))
17872 (delq nil
17873 (mapcar
17874 (lambda(b)
17875 (if (and (funcall filter b)
17876 (or (not exclude-tmp)
17877 (not (string-match "tmp" (buffer-name b)))))
17879 nil))
17880 (buffer-list)))))
17882 (defun org-agenda-files (&optional unrestricted archives)
17883 "Get the list of agenda files.
17884 Optional UNRESTRICTED means return the full list even if a restriction
17885 is currently in place.
17886 When ARCHIVES is t, include all archive files that are really being
17887 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17888 `org-agenda-archives-mode' is t."
17889 (let ((files
17890 (cond
17891 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17892 ((stringp org-agenda-files) (org-read-agenda-file-list))
17893 ((listp org-agenda-files) org-agenda-files)
17894 (t (error "Invalid value of `org-agenda-files'")))))
17895 (setq files (apply 'append
17896 (mapcar (lambda (f)
17897 (if (file-directory-p f)
17898 (directory-files
17899 f t org-agenda-file-regexp)
17900 (list f)))
17901 files)))
17902 (when org-agenda-skip-unavailable-files
17903 (setq files (delq nil
17904 (mapcar (function
17905 (lambda (file)
17906 (and (file-readable-p file) file)))
17907 files))))
17908 (when (or (eq archives t)
17909 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17910 (setq files (org-add-archive-files files)))
17911 files))
17913 (defun org-agenda-file-p (&optional file)
17914 "Return non-nil, if FILE is an agenda file.
17915 If FILE is omitted, use the file associated with the current
17916 buffer."
17917 (member (or file (buffer-file-name))
17918 (org-agenda-files t)))
17920 (defun org-edit-agenda-file-list ()
17921 "Edit the list of agenda files.
17922 Depending on setup, this either uses customize to edit the variable
17923 `org-agenda-files', or it visits the file that is holding the list. In the
17924 latter case, the buffer is set up in a way that saving it automatically kills
17925 the buffer and restores the previous window configuration."
17926 (interactive)
17927 (if (stringp org-agenda-files)
17928 (let ((cw (current-window-configuration)))
17929 (find-file org-agenda-files)
17930 (org-set-local 'org-window-configuration cw)
17931 (org-add-hook 'after-save-hook
17932 (lambda ()
17933 (set-window-configuration
17934 (prog1 org-window-configuration
17935 (kill-buffer (current-buffer))))
17936 (org-install-agenda-files-menu)
17937 (message "New agenda file list installed"))
17938 nil 'local)
17939 (message "%s" (substitute-command-keys
17940 "Edit list and finish with \\[save-buffer]")))
17941 (customize-variable 'org-agenda-files)))
17943 (defun org-store-new-agenda-file-list (list)
17944 "Set new value for the agenda file list and save it correctly."
17945 (if (stringp org-agenda-files)
17946 (let ((fe (org-read-agenda-file-list t)) b u)
17947 (while (setq b (find-buffer-visiting org-agenda-files))
17948 (kill-buffer b))
17949 (with-temp-file org-agenda-files
17950 (insert
17951 (mapconcat
17952 (lambda (f) ;; Keep un-expanded entries.
17953 (if (setq u (assoc f fe))
17954 (cdr u)
17956 list "\n")
17957 "\n")))
17958 (let ((org-mode-hook nil) (org-inhibit-startup t)
17959 (org-insert-mode-line-in-empty-file nil))
17960 (setq org-agenda-files list)
17961 (customize-save-variable 'org-agenda-files org-agenda-files))))
17963 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17964 "Read the list of agenda files from a file.
17965 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17966 filenames, used by `org-store-new-agenda-file-list' to write back
17967 un-expanded file names."
17968 (when (file-directory-p org-agenda-files)
17969 (error "`org-agenda-files' cannot be a single directory"))
17970 (when (stringp org-agenda-files)
17971 (with-temp-buffer
17972 (insert-file-contents org-agenda-files)
17973 (mapcar
17974 (lambda (f)
17975 (let ((e (expand-file-name (substitute-in-file-name f)
17976 org-directory)))
17977 (if pair-with-expansion
17978 (cons e f)
17979 e)))
17980 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17982 ;;;###autoload
17983 (defun org-cycle-agenda-files ()
17984 "Cycle through the files in `org-agenda-files'.
17985 If the current buffer visits an agenda file, find the next one in the list.
17986 If the current buffer does not, find the first agenda file."
17987 (interactive)
17988 (let* ((fs (org-agenda-files t))
17989 (files (append fs (list (car fs))))
17990 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17991 file)
17992 (unless files (user-error "No agenda files"))
17993 (catch 'exit
17994 (while (setq file (pop files))
17995 (if (equal (file-truename file) tcf)
17996 (when (car files)
17997 (find-file (car files))
17998 (throw 'exit t))))
17999 (find-file (car fs)))
18000 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18002 (defun org-agenda-file-to-front (&optional to-end)
18003 "Move/add the current file to the top of the agenda file list.
18004 If the file is not present in the list, it is added to the front. If it is
18005 present, it is moved there. With optional argument TO-END, add/move to the
18006 end of the list."
18007 (interactive "P")
18008 (let ((org-agenda-skip-unavailable-files nil)
18009 (file-alist (mapcar (lambda (x)
18010 (cons (file-truename x) x))
18011 (org-agenda-files t)))
18012 (ctf (file-truename
18013 (or buffer-file-name
18014 (user-error "Please save the current buffer to a file"))))
18015 x had)
18016 (setq x (assoc ctf file-alist) had x)
18018 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18019 (if to-end
18020 (setq file-alist (append (delq x file-alist) (list x)))
18021 (setq file-alist (cons x (delq x file-alist))))
18022 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18023 (org-install-agenda-files-menu)
18024 (message "File %s to %s of agenda file list"
18025 (if had "moved" "added") (if to-end "end" "front"))))
18027 (defun org-remove-file (&optional file)
18028 "Remove current file from the list of files in variable `org-agenda-files'.
18029 These are the files which are being checked for agenda entries.
18030 Optional argument FILE means use this file instead of the current."
18031 (interactive)
18032 (let* ((org-agenda-skip-unavailable-files nil)
18033 (file (or file buffer-file-name
18034 (user-error "Current buffer does not visit a file")))
18035 (true-file (file-truename file))
18036 (afile (abbreviate-file-name file))
18037 (files (delq nil (mapcar
18038 (lambda (x)
18039 (if (equal true-file
18040 (file-truename x))
18041 nil x))
18042 (org-agenda-files t)))))
18043 (if (not (= (length files) (length (org-agenda-files t))))
18044 (progn
18045 (org-store-new-agenda-file-list files)
18046 (org-install-agenda-files-menu)
18047 (message "Removed file: %s" afile))
18048 (message "File was not in list: %s (not removed)" afile))))
18050 (defun org-file-menu-entry (file)
18051 (vector file (list 'find-file file) t))
18053 (defun org-check-agenda-file (file)
18054 "Make sure FILE exists. If not, ask user what to do."
18055 (when (not (file-exists-p file))
18056 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18057 (abbreviate-file-name file))
18058 (let ((r (downcase (read-char-exclusive))))
18059 (cond
18060 ((equal r ?r)
18061 (org-remove-file file)
18062 (throw 'nextfile t))
18063 (t (error "Abort"))))))
18065 (defun org-get-agenda-file-buffer (file)
18066 "Get a buffer visiting FILE. If the buffer needs to be created, add
18067 it to the list of buffers which might be released later."
18068 (let ((buf (org-find-base-buffer-visiting file)))
18069 (if buf
18070 buf ; just return it
18071 ;; Make a new buffer and remember it
18072 (setq buf (find-file-noselect file))
18073 (if buf (push buf org-agenda-new-buffers))
18074 buf)))
18076 (defun org-release-buffers (blist)
18077 "Release all buffers in list, asking the user for confirmation when needed.
18078 When a buffer is unmodified, it is just killed. When modified, it is saved
18079 \(if the user agrees) and then killed."
18080 (let (buf file)
18081 (while (setq buf (pop blist))
18082 (setq file (buffer-file-name buf))
18083 (when (and (buffer-modified-p buf)
18084 file
18085 (y-or-n-p (format "Save file %s? " file)))
18086 (with-current-buffer buf (save-buffer)))
18087 (kill-buffer buf))))
18089 (defun org-agenda-prepare-buffers (files)
18090 "Create buffers for all agenda files, protect archived trees and comments."
18091 (interactive)
18092 (let ((pa '(:org-archived t))
18093 (pc '(:org-comment t))
18094 (pall '(:org-archived t :org-comment t))
18095 (inhibit-read-only t)
18096 (org-inhibit-startup org-agenda-inhibit-startup)
18097 (rea (concat ":" org-archive-tag ":"))
18098 file re pos)
18099 (setq org-tag-alist-for-agenda nil
18100 org-tag-groups-alist-for-agenda nil)
18101 (save-excursion
18102 (save-restriction
18103 (while (setq file (pop files))
18104 (catch 'nextfile
18105 (if (bufferp file)
18106 (set-buffer file)
18107 (org-check-agenda-file file)
18108 (set-buffer (org-get-agenda-file-buffer file)))
18109 (widen)
18110 (org-set-regexps-and-options-for-tags)
18111 (setq pos (point))
18112 (goto-char (point-min))
18113 (let ((case-fold-search t))
18114 (when (search-forward "#+setupfile" nil t)
18115 ;; Don't set all regexps and options systematically as
18116 ;; this is only run for setting agenda tags from setup
18117 ;; file
18118 (org-set-regexps-and-options)))
18119 (or (memq 'category org-agenda-ignore-drawer-properties)
18120 (org-refresh-category-properties))
18121 (or (memq 'effort org-agenda-ignore-drawer-properties)
18122 (org-refresh-properties org-effort-property 'org-effort))
18123 (or (memq 'appt org-agenda-ignore-drawer-properties)
18124 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18125 (setq org-todo-keywords-for-agenda
18126 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18127 (setq org-done-keywords-for-agenda
18128 (append org-done-keywords-for-agenda org-done-keywords))
18129 (setq org-todo-keyword-alist-for-agenda
18130 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18131 (setq org-drawers-for-agenda
18132 (append org-drawers-for-agenda org-drawers))
18133 (setq org-tag-alist-for-agenda
18134 (org-uniquify
18135 (append org-tag-alist-for-agenda
18136 org-tag-alist
18137 org-tag-persistent-alist)))
18138 (if org-group-tags
18139 (setq org-tag-groups-alist-for-agenda
18140 (org-uniquify-alist
18141 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18142 (org-with-silent-modifications
18143 (save-excursion
18144 (remove-text-properties (point-min) (point-max) pall)
18145 (when org-agenda-skip-archived-trees
18146 (goto-char (point-min))
18147 (while (re-search-forward rea nil t)
18148 (if (org-at-heading-p t)
18149 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18150 (goto-char (point-min))
18151 (setq re (format org-heading-keyword-regexp-format
18152 org-comment-string))
18153 (while (re-search-forward re nil t)
18154 (add-text-properties
18155 (match-beginning 0) (org-end-of-subtree t) pc))))
18156 (goto-char pos)))))
18157 (setq org-todo-keywords-for-agenda
18158 (org-uniquify org-todo-keywords-for-agenda))
18159 (setq org-todo-keyword-alist-for-agenda
18160 (org-uniquify org-todo-keyword-alist-for-agenda))))
18163 ;;;; CDLaTeX minor mode
18165 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18166 "Keymap for the minor `org-cdlatex-mode'.")
18168 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18169 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18170 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18171 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18172 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18174 (defvar org-cdlatex-texmathp-advice-is-done nil
18175 "Flag remembering if we have applied the advice to texmathp already.")
18177 (define-minor-mode org-cdlatex-mode
18178 "Toggle the minor `org-cdlatex-mode'.
18179 This mode supports entering LaTeX environment and math in LaTeX fragments
18180 in Org-mode.
18181 \\{org-cdlatex-mode-map}"
18182 nil " OCDL" nil
18183 (when org-cdlatex-mode
18184 (require 'cdlatex)
18185 (run-hooks 'cdlatex-mode-hook)
18186 (cdlatex-compute-tables))
18187 (unless org-cdlatex-texmathp-advice-is-done
18188 (setq org-cdlatex-texmathp-advice-is-done t)
18189 (defadvice texmathp (around org-math-always-on activate)
18190 "Always return t in org-mode buffers.
18191 This is because we want to insert math symbols without dollars even outside
18192 the LaTeX math segments. If Orgmode thinks that point is actually inside
18193 an embedded LaTeX fragment, let texmathp do its job.
18194 \\[org-cdlatex-mode-map]"
18195 (interactive)
18196 (let (p)
18197 (cond
18198 ((not (derived-mode-p 'org-mode)) ad-do-it)
18199 ((eq this-command 'cdlatex-math-symbol)
18200 (setq ad-return-value t
18201 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18203 (let ((p (org-inside-LaTeX-fragment-p)))
18204 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18205 (setq ad-return-value t
18206 texmathp-why '("Org-mode embedded math" . 0))
18207 (if p ad-do-it)))))))))
18209 (defun turn-on-org-cdlatex ()
18210 "Unconditionally turn on `org-cdlatex-mode'."
18211 (org-cdlatex-mode 1))
18213 (defun org-try-cdlatex-tab ()
18214 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18215 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18216 - inside a LaTeX fragment, or
18217 - after the first word in a line, where an abbreviation expansion could
18218 insert a LaTeX environment."
18219 (when org-cdlatex-mode
18220 (cond
18221 ;; Before any word on the line: No expansion possible.
18222 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18223 ;; Just after first word on the line: Expand it. Make sure it
18224 ;; cannot happen on headlines, though.
18225 ((save-excursion
18226 (skip-chars-backward "a-zA-Z0-9*")
18227 (skip-chars-backward " \t")
18228 (and (bolp) (not (org-at-heading-p))))
18229 (cdlatex-tab) t)
18230 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18232 (defun org-cdlatex-underscore-caret (&optional arg)
18233 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18234 Revert to the normal definition outside of these fragments."
18235 (interactive "P")
18236 (if (org-inside-LaTeX-fragment-p)
18237 (call-interactively 'cdlatex-sub-superscript)
18238 (let (org-cdlatex-mode)
18239 (call-interactively (key-binding (vector last-input-event))))))
18241 (defun org-cdlatex-math-modify (&optional arg)
18242 "Execute `cdlatex-math-modify' in LaTeX fragments.
18243 Revert to the normal definition outside of these fragments."
18244 (interactive "P")
18245 (if (org-inside-LaTeX-fragment-p)
18246 (call-interactively 'cdlatex-math-modify)
18247 (let (org-cdlatex-mode)
18248 (call-interactively (key-binding (vector last-input-event))))))
18252 ;;;; LaTeX fragments
18254 (defvar org-latex-regexps
18255 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18256 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18257 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18258 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18259 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18260 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18261 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18262 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18263 "Regular expressions for matching embedded LaTeX.")
18265 (defun org-inside-LaTeX-fragment-p ()
18266 "Test if point is inside a LaTeX fragment.
18267 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18268 sequence appearing also before point.
18269 Even though the matchers for math are configurable, this function assumes
18270 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18271 delimiters are skipped when they have been removed by customization.
18272 The return value is nil, or a cons cell with the delimiter and the
18273 position of this delimiter.
18275 This function does a reasonably good job, but can locally be fooled by
18276 for example currency specifications. For example it will assume being in
18277 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18278 fragments that are properly closed, but during editing, we have to live
18279 with the uncertainty caused by missing closing delimiters. This function
18280 looks only before point, not after."
18281 (catch 'exit
18282 (let ((pos (point))
18283 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18284 (lim (progn
18285 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18286 (point)))
18287 dd-on str (start 0) m re)
18288 (goto-char pos)
18289 (when dodollar
18290 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18291 re (nth 1 (assoc "$" org-latex-regexps)))
18292 (while (string-match re str start)
18293 (cond
18294 ((= (match-end 0) (length str))
18295 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18296 ((= (match-end 0) (- (length str) 5))
18297 (throw 'exit nil))
18298 (t (setq start (match-end 0))))))
18299 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18300 (goto-char pos)
18301 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18302 (and (match-beginning 2) (throw 'exit nil))
18303 ;; count $$
18304 (while (re-search-backward "\\$\\$" lim t)
18305 (setq dd-on (not dd-on)))
18306 (goto-char pos)
18307 (if dd-on (cons "$$" m))))))
18309 (defun org-inside-latex-macro-p ()
18310 "Is point inside a LaTeX macro or its arguments?"
18311 (save-match-data
18312 (org-in-regexp
18313 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18315 (defvar org-latex-fragment-image-overlays nil
18316 "List of overlays carrying the images of latex fragments.")
18317 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18319 (defun org-remove-latex-fragment-image-overlays ()
18320 "Remove all overlays with LaTeX fragment images in current buffer."
18321 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18322 (setq org-latex-fragment-image-overlays nil))
18324 (defun org-preview-latex-fragment (&optional subtree)
18325 "Preview the LaTeX fragment at point, or all locally or globally.
18326 If the cursor is in a LaTeX fragment, create the image and overlay
18327 it over the source code. If there is no fragment at point, display
18328 all fragments in the current text, from one headline to the next. With
18329 prefix SUBTREE, display all fragments in the current subtree. With a
18330 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18331 the cursor is before the first headline,
18332 display all fragments in the buffer.
18333 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18334 (interactive "P")
18335 (unless buffer-file-name
18336 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18337 (when (display-graphic-p)
18338 (org-remove-latex-fragment-image-overlays)
18339 (save-excursion
18340 (save-restriction
18341 (let (beg end at msg)
18342 (cond
18343 ((or (equal subtree '(16))
18344 (not (save-excursion
18345 (re-search-backward org-outline-regexp-bol nil t))))
18346 (setq beg (point-min) end (point-max)
18347 msg "Creating images for buffer...%s"))
18348 ((equal subtree '(4))
18349 (org-back-to-heading)
18350 (setq beg (point) end (org-end-of-subtree t)
18351 msg "Creating images for subtree...%s"))
18353 (if (setq at (org-inside-LaTeX-fragment-p))
18354 (goto-char (max (point-min) (- (cdr at) 2)))
18355 (org-back-to-heading))
18356 (setq beg (point) end (progn (outline-next-heading) (point))
18357 msg (if at "Creating image...%s"
18358 "Creating images for entry...%s"))))
18359 (message msg "")
18360 (narrow-to-region beg end)
18361 (goto-char beg)
18362 (org-format-latex
18363 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18364 (file-name-nondirectory
18365 buffer-file-name)))
18366 default-directory 'overlays msg at 'forbuffer
18367 org-latex-create-formula-image-program)
18368 (message msg "done. Use `C-c C-c' to remove images."))))))
18370 (defun org-format-latex (prefix &optional dir overlays msg at
18371 forbuffer processing-type)
18372 "Replace LaTeX fragments with links to an image, and produce images.
18373 Some of the options can be changed using the variable
18374 `org-format-latex-options'."
18375 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18376 (let* ((prefixnodir (file-name-nondirectory prefix))
18377 (absprefix (expand-file-name prefix dir))
18378 (todir (file-name-directory absprefix))
18379 (opt org-format-latex-options)
18380 (optnew org-format-latex-options)
18381 (matchers (plist-get opt :matchers))
18382 (re-list org-latex-regexps)
18383 (cnt 0) txt hash link beg end re e checkdir
18384 string
18385 m n block-type block linkfile movefile ov)
18386 ;; Check the different regular expressions
18387 (while (setq e (pop re-list))
18388 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18389 block (if block-type "\n\n" ""))
18390 (when (member m matchers)
18391 (goto-char (point-min))
18392 (while (re-search-forward re nil t)
18393 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18394 (or (not overlays)
18395 (not (eq (get-char-property (match-beginning n)
18396 'org-overlay-type)
18397 'org-latex-overlay))))
18398 (cond
18399 ((eq processing-type 'verbatim))
18400 ((eq processing-type 'mathjax)
18401 ;; Prepare for MathJax processing.
18402 (setq string (match-string n))
18403 (when (member m '("$" "$1"))
18404 (save-excursion
18405 (delete-region (match-beginning n) (match-end n))
18406 (goto-char (match-beginning n))
18407 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18408 ((or (eq processing-type 'dvipng)
18409 (eq processing-type 'imagemagick))
18410 ;; Process to an image.
18411 (setq txt (match-string n)
18412 beg (match-beginning n) end (match-end n)
18413 cnt (1+ cnt))
18414 (let ((face (face-at-point))
18415 (fg (plist-get opt :foreground))
18416 (bg (plist-get opt :background))
18417 ;; Ensure full list is printed.
18418 print-length print-level)
18419 (when forbuffer
18420 ;; Get the colors from the face at point.
18421 (goto-char beg)
18422 (when (eq fg 'auto)
18423 (setq fg (face-attribute face :foreground nil 'default)))
18424 (when (eq bg 'auto)
18425 (setq bg (face-attribute face :background nil 'default)))
18426 (setq optnew (copy-sequence opt))
18427 (plist-put optnew :foreground fg)
18428 (plist-put optnew :background bg))
18429 (setq hash (sha1 (prin1-to-string
18430 (list org-format-latex-header
18431 org-latex-default-packages-alist
18432 org-latex-packages-alist
18433 org-format-latex-options
18434 forbuffer txt fg bg)))
18435 linkfile (format "%s_%s.png" prefix hash)
18436 movefile (format "%s_%s.png" absprefix hash)))
18437 (setq link (concat block "[[file:" linkfile "]]" block))
18438 (if msg (message msg cnt))
18439 (goto-char beg)
18440 (unless checkdir ; Ensure the directory exists.
18441 (setq checkdir t)
18442 (or (file-directory-p todir) (make-directory todir t)))
18443 (unless (file-exists-p movefile)
18444 (org-create-formula-image
18445 txt movefile optnew forbuffer processing-type))
18446 (if overlays
18447 (progn
18448 (mapc (lambda (o)
18449 (if (eq (overlay-get o 'org-overlay-type)
18450 'org-latex-overlay)
18451 (delete-overlay o)))
18452 (overlays-in beg end))
18453 (setq ov (make-overlay beg end))
18454 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18455 (if (featurep 'xemacs)
18456 (progn
18457 (overlay-put ov 'invisible t)
18458 (overlay-put
18459 ov 'end-glyph
18460 (make-glyph (vector 'png :file movefile))))
18461 (overlay-put
18462 ov 'display
18463 (list 'image :type 'png :file movefile :ascent 'center)))
18464 (push ov org-latex-fragment-image-overlays)
18465 (goto-char end))
18466 (delete-region beg end)
18467 (insert (org-add-props link
18468 (list 'org-latex-src
18469 (replace-regexp-in-string
18470 "\"" "" txt)
18471 'org-latex-src-embed-type
18472 (if block-type 'paragraph 'character))))))
18473 ((eq processing-type 'mathml)
18474 ;; Process to MathML
18475 (unless (save-match-data (org-format-latex-mathml-available-p))
18476 (user-error "LaTeX to MathML converter not configured"))
18477 (setq txt (match-string n)
18478 beg (match-beginning n) end (match-end n)
18479 cnt (1+ cnt))
18480 (if msg (message msg cnt))
18481 (goto-char beg)
18482 (delete-region beg end)
18483 (insert (org-format-latex-as-mathml
18484 txt block-type prefix dir)))
18486 (error "Unknown conversion type %s for LaTeX fragments"
18487 processing-type)))))))))
18489 (defun org-create-math-formula (latex-frag &optional mathml-file)
18490 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18491 Use `org-latex-to-mathml-convert-command'. If the conversion is
18492 sucessful, return the portion between \"<math...> </math>\"
18493 elements otherwise return nil. When MATHML-FILE is specified,
18494 write the results in to that file. When invoked as an
18495 interactive command, prompt for LATEX-FRAG, with initial value
18496 set to the current active region and echo the results for user
18497 inspection."
18498 (interactive (list (let ((frag (when (org-region-active-p)
18499 (buffer-substring-no-properties
18500 (region-beginning) (region-end)))))
18501 (read-string "LaTeX Fragment: " frag nil frag))))
18502 (unless latex-frag (error "Invalid LaTeX fragment"))
18503 (let* ((tmp-in-file (file-relative-name
18504 (make-temp-name (expand-file-name "ltxmathml-in"))))
18505 (ignore (write-region latex-frag nil tmp-in-file))
18506 (tmp-out-file (file-relative-name
18507 (make-temp-name (expand-file-name "ltxmathml-out"))))
18508 (cmd (format-spec
18509 org-latex-to-mathml-convert-command
18510 `((?j . ,(shell-quote-argument
18511 (expand-file-name org-latex-to-mathml-jar-file)))
18512 (?I . ,(shell-quote-argument tmp-in-file))
18513 (?o . ,(shell-quote-argument tmp-out-file)))))
18514 mathml shell-command-output)
18515 (when (org-called-interactively-p 'any)
18516 (unless (org-format-latex-mathml-available-p)
18517 (user-error "LaTeX to MathML converter not configured")))
18518 (message "Running %s" cmd)
18519 (setq shell-command-output (shell-command-to-string cmd))
18520 (setq mathml
18521 (when (file-readable-p tmp-out-file)
18522 (with-current-buffer (find-file-noselect tmp-out-file t)
18523 (goto-char (point-min))
18524 (when (re-search-forward
18525 (concat
18526 (regexp-quote
18527 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18528 "\\(.\\|\n\\)*"
18529 (regexp-quote "</math>")) nil t)
18530 (prog1 (match-string 0) (kill-buffer))))))
18531 (cond
18532 (mathml
18533 (setq mathml
18534 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18535 (when mathml-file
18536 (write-region mathml nil mathml-file))
18537 (when (org-called-interactively-p 'any)
18538 (message mathml)))
18539 ((message "LaTeX to MathML conversion failed")
18540 (message shell-command-output)))
18541 (delete-file tmp-in-file)
18542 (when (file-exists-p tmp-out-file)
18543 (delete-file tmp-out-file))
18544 mathml))
18546 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18547 prefix &optional dir)
18548 "Use `org-create-math-formula' but check local cache first."
18549 (let* ((absprefix (expand-file-name prefix dir))
18550 (print-length nil) (print-level nil)
18551 (formula-id (concat
18552 "formula-"
18553 (sha1
18554 (prin1-to-string
18555 (list latex-frag
18556 org-latex-to-mathml-convert-command)))))
18557 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18558 (formula-cache-dir (file-name-directory formula-cache)))
18560 (unless (file-directory-p formula-cache-dir)
18561 (make-directory formula-cache-dir t))
18563 (unless (file-exists-p formula-cache)
18564 (org-create-math-formula latex-frag formula-cache))
18566 (if (file-exists-p formula-cache)
18567 ;; Successful conversion. Return the link to MathML file.
18568 (org-add-props
18569 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18570 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18571 'org-latex-src-embed-type (if latex-frag-type
18572 'paragraph 'character)))
18573 ;; Failed conversion. Return the LaTeX fragment verbatim
18574 latex-frag)))
18576 (defun org-create-formula-image (string tofile options buffer &optional type)
18577 "Create an image from LaTeX source using dvipng or convert.
18578 This function calls either `org-create-formula-image-with-dvipng'
18579 or `org-create-formula-image-with-imagemagick' depending on the
18580 value of `org-latex-create-formula-image-program' or on the value
18581 of the optional TYPE variable.
18583 Note: ultimately these two function should be combined as they
18584 share a good deal of logic."
18585 (org-check-external-command
18586 "latex" "needed to convert LaTeX fragments to images")
18587 (funcall
18588 (case (or type org-latex-create-formula-image-program)
18589 ('dvipng
18590 (org-check-external-command
18591 "dvipng" "needed to convert LaTeX fragments to images")
18592 #'org-create-formula-image-with-dvipng)
18593 ('imagemagick
18594 (org-check-external-command
18595 "convert" "you need to install imagemagick")
18596 #'org-create-formula-image-with-imagemagick)
18597 (t (error
18598 "Invalid value of `org-latex-create-formula-image-program'")))
18599 string tofile options buffer))
18601 (declare-function org-export-get-backend "ox" (name))
18602 (declare-function org-export--get-global-options "ox" (&optional backend))
18603 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18604 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18605 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18606 (defun org-create-formula--latex-header ()
18607 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18608 (let ((info (org-combine-plists (org-export--get-global-options
18609 (org-export-get-backend 'latex))
18610 (org-export--get-inbuffer-options
18611 (org-export-get-backend 'latex)))))
18612 (org-latex-guess-babel-language
18613 (org-latex-guess-inputenc
18614 (org-splice-latex-header
18615 org-format-latex-header
18616 org-latex-default-packages-alist
18617 org-latex-packages-alist t
18618 (plist-get info :latex-header)))
18619 info)))
18621 ;; This function borrows from Ganesh Swami's latex2png.el
18622 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18623 "This calls dvipng."
18624 (require 'ox-latex)
18625 (let* ((tmpdir (if (featurep 'xemacs)
18626 (temp-directory)
18627 temporary-file-directory))
18628 (texfilebase (make-temp-name
18629 (expand-file-name "orgtex" tmpdir)))
18630 (texfile (concat texfilebase ".tex"))
18631 (dvifile (concat texfilebase ".dvi"))
18632 (pngfile (concat texfilebase ".png"))
18633 (fnh (if (featurep 'xemacs)
18634 (font-height (face-font 'default))
18635 (face-attribute 'default :height nil)))
18636 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18637 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18638 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18639 "Black"))
18640 (bg (or (plist-get options (if buffer :background :html-background))
18641 "Transparent")))
18642 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18643 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18644 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18645 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18646 (let ((latex-header (org-create-formula--latex-header)))
18647 (with-temp-file texfile
18648 (insert latex-header)
18649 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18650 (let ((dir default-directory))
18651 (condition-case nil
18652 (progn
18653 (cd tmpdir)
18654 (call-process "latex" nil nil nil texfile))
18655 (error nil))
18656 (cd dir))
18657 (if (not (file-exists-p dvifile))
18658 (progn (message "Failed to create dvi file from %s" texfile) nil)
18659 (condition-case nil
18660 (if (featurep 'xemacs)
18661 (call-process "dvipng" nil nil nil
18662 "-fg" fg "-bg" bg
18663 "-T" "tight"
18664 "-o" pngfile
18665 dvifile)
18666 (call-process "dvipng" nil nil nil
18667 "-fg" fg "-bg" bg
18668 "-D" dpi
18669 ;;"-x" scale "-y" scale
18670 "-T" "tight"
18671 "-o" pngfile
18672 dvifile))
18673 (error nil))
18674 (if (not (file-exists-p pngfile))
18675 (if org-format-latex-signal-error
18676 (error "Failed to create png file from %s" texfile)
18677 (message "Failed to create png file from %s" texfile)
18678 nil)
18679 ;; Use the requested file name and clean up
18680 (copy-file pngfile tofile 'replace)
18681 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18682 (if (file-exists-p (concat texfilebase e))
18683 (delete-file (concat texfilebase e))))
18684 pngfile))))
18686 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18687 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18688 "This calls convert, which is included into imagemagick."
18689 (require 'ox-latex)
18690 (let* ((tmpdir (if (featurep 'xemacs)
18691 (temp-directory)
18692 temporary-file-directory))
18693 (texfilebase (make-temp-name
18694 (expand-file-name "orgtex" tmpdir)))
18695 (texfile (concat texfilebase ".tex"))
18696 (pdffile (concat texfilebase ".pdf"))
18697 (pngfile (concat texfilebase ".png"))
18698 (fnh (if (featurep 'xemacs)
18699 (font-height (face-font 'default))
18700 (face-attribute 'default :height nil)))
18701 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18702 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18703 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18704 "black"))
18705 (bg (or (plist-get options (if buffer :background :html-background))
18706 "white")))
18707 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18708 (setq fg (org-latex-color-format fg)))
18709 (if (eq bg 'default) (setq bg (org-latex-color :background))
18710 (setq bg (org-latex-color-format
18711 (if (string= bg "Transparent") "white" bg))))
18712 (let ((latex-header (org-create-formula--latex-header)))
18713 (with-temp-file texfile
18714 (insert latex-header)
18715 (insert "\n\\begin{document}\n"
18716 "\\definecolor{fg}{rgb}{" fg "}\n"
18717 "\\definecolor{bg}{rgb}{" bg "}\n"
18718 "\n\\pagecolor{bg}\n"
18719 "\n{\\color{fg}\n"
18720 string
18721 "\n}\n"
18722 "\n\\end{document}\n")))
18723 (org-latex-compile texfile t)
18724 (if (not (file-exists-p pdffile))
18725 (progn (message "Failed to create pdf file from %s" texfile) nil)
18726 (condition-case nil
18727 (if (featurep 'xemacs)
18728 (call-process "convert" nil nil nil
18729 "-density" "96"
18730 "-trim"
18731 "-antialias"
18732 pdffile
18733 "-quality" "100"
18734 ;; "-sharpen" "0x1.0"
18735 pngfile)
18736 (call-process "convert" nil nil nil
18737 "-density" dpi
18738 "-trim"
18739 "-antialias"
18740 pdffile
18741 "-quality" "100"
18742 ;; "-sharpen" "0x1.0"
18743 pngfile))
18744 (error nil))
18745 (if (not (file-exists-p pngfile))
18746 (if org-format-latex-signal-error
18747 (error "Failed to create png file from %s" texfile)
18748 (message "Failed to create png file from %s" texfile)
18749 nil)
18750 ;; Use the requested file name and clean up
18751 (copy-file pngfile tofile 'replace)
18752 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18753 (if (file-exists-p (concat texfilebase e))
18754 (delete-file (concat texfilebase e))))
18755 pngfile))))
18757 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18758 "Fill a LaTeX header template TPL.
18759 In the template, the following place holders will be recognized:
18761 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18762 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18763 [PACKAGES] \\usepackage statements for PKG
18764 [NO-PACKAGES] do not include PKG
18765 [EXTRA] the string EXTRA
18766 [NO-EXTRA] do not include EXTRA
18768 For backward compatibility, if both the positive and the negative place
18769 holder is missing, the positive one (without the \"NO-\") will be
18770 assumed to be present at the end of the template.
18771 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18772 EXTRA is a string.
18773 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18774 (let (rpl (end ""))
18775 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18776 (setq rpl (if (or (match-end 1) (not def-pkg))
18777 "" (org-latex-packages-to-string def-pkg snippets-p t))
18778 tpl (replace-match rpl t t tpl))
18779 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18781 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18782 (setq rpl (if (or (match-end 1) (not pkg))
18783 "" (org-latex-packages-to-string pkg snippets-p t))
18784 tpl (replace-match rpl t t tpl))
18785 (if pkg (setq end
18786 (concat end "\n"
18787 (org-latex-packages-to-string pkg snippets-p)))))
18789 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18790 (setq rpl (if (or (match-end 1) (not extra))
18791 "" (concat extra "\n"))
18792 tpl (replace-match rpl t t tpl))
18793 (if (and extra (string-match "\\S-" extra))
18794 (setq end (concat end "\n" extra))))
18796 (if (string-match "\\S-" end)
18797 (concat tpl "\n" end)
18798 tpl)))
18800 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18801 "Turn an alist of packages into a string with the \\usepackage macros."
18802 (setq pkg (mapconcat (lambda(p)
18803 (cond
18804 ((stringp p) p)
18805 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18806 (format "%% Package %s omitted" (cadr p)))
18807 ((equal "" (car p))
18808 (format "\\usepackage{%s}" (cadr p)))
18810 (format "\\usepackage[%s]{%s}"
18811 (car p) (cadr p)))))
18813 "\n"))
18814 (if newline (concat pkg "\n") pkg))
18816 (defun org-dvipng-color (attr)
18817 "Return a RGB color specification for dvipng."
18818 (apply 'format "rgb %s %s %s"
18819 (mapcar 'org-normalize-color
18820 (if (featurep 'xemacs)
18821 (color-rgb-components
18822 (face-property 'default
18823 (cond ((eq attr :foreground) 'foreground)
18824 ((eq attr :background) 'background))))
18825 (color-values (face-attribute 'default attr nil))))))
18827 (defun org-dvipng-color-format (color-name)
18828 "Convert COLOR-NAME to a RGB color value for dvipng."
18829 (apply 'format "rgb %s %s %s"
18830 (mapcar 'org-normalize-color
18831 (color-values color-name))))
18833 (defun org-latex-color (attr)
18834 "Return a RGB color for the LaTeX color package."
18835 (apply 'format "%s,%s,%s"
18836 (mapcar 'org-normalize-color
18837 (if (featurep 'xemacs)
18838 (color-rgb-components
18839 (face-property 'default
18840 (cond ((eq attr :foreground) 'foreground)
18841 ((eq attr :background) 'background))))
18842 (color-values (face-attribute 'default attr nil))))))
18844 (defun org-latex-color-format (color-name)
18845 "Convert COLOR-NAME to a RGB color value."
18846 (apply 'format "%s,%s,%s"
18847 (mapcar 'org-normalize-color
18848 (color-values color-name))))
18850 (defun org-normalize-color (value)
18851 "Return string to be used as color value for an RGB component."
18852 (format "%g" (/ value 65535.0)))
18856 ;; Image display
18858 (defvar org-inline-image-overlays nil)
18859 (make-variable-buffer-local 'org-inline-image-overlays)
18861 (defun org-toggle-inline-images (&optional include-linked)
18862 "Toggle the display of inline images.
18863 INCLUDE-LINKED is passed to `org-display-inline-images'."
18864 (interactive "P")
18865 (if org-inline-image-overlays
18866 (progn
18867 (org-remove-inline-images)
18868 (message "Inline image display turned off"))
18869 (org-display-inline-images include-linked)
18870 (if (and (org-called-interactively-p)
18871 org-inline-image-overlays)
18872 (message "%d images displayed inline"
18873 (length org-inline-image-overlays))
18874 (message "No images to display inline"))))
18876 (defun org-redisplay-inline-images ()
18877 "Refresh the display of inline images."
18878 (interactive)
18879 (if (not org-inline-image-overlays)
18880 (org-toggle-inline-images)
18881 (org-toggle-inline-images)
18882 (org-toggle-inline-images)))
18884 (defun org-display-inline-images (&optional include-linked refresh beg end)
18885 "Display inline images.
18886 Normally only links without a description part are inlined, because this
18887 is how it will work for export. When INCLUDE-LINKED is set, also links
18888 with a description part will be inlined. This can be nice for a quick
18889 look at those images, but it does not reflect what exported files will look
18890 like.
18891 When REFRESH is set, refresh existing images between BEG and END.
18892 This will create new image displays only if necessary.
18893 BEG and END default to the buffer boundaries."
18894 (interactive "P")
18895 (when (display-graphic-p)
18896 (unless refresh
18897 (org-remove-inline-images)
18898 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18899 (save-excursion
18900 (save-restriction
18901 (widen)
18902 (setq beg (or beg (point-min)) end (or end (point-max)))
18903 (goto-char beg)
18904 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18905 (substring (org-image-file-name-regexp) 0 -2)
18906 "\\)\\]" (if include-linked "" "\\]")))
18907 (case-fold-search t)
18908 old file ov img type attrwidth width)
18909 (while (re-search-forward re end t)
18910 (setq old (get-char-property-and-overlay (match-beginning 1)
18911 'org-image-overlay)
18912 file (expand-file-name
18913 (concat (or (match-string 3) "") (match-string 4))))
18914 (when (image-type-available-p 'imagemagick)
18915 (setq attrwidth (if (or (listp org-image-actual-width)
18916 (null org-image-actual-width))
18917 (save-excursion
18918 (save-match-data
18919 (when (re-search-backward
18920 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18921 (save-excursion
18922 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18923 (string-to-number (match-string 1))))))
18924 width (cond ((eq org-image-actual-width t) nil)
18925 ((null org-image-actual-width) attrwidth)
18926 ((numberp org-image-actual-width)
18927 org-image-actual-width)
18928 ((listp org-image-actual-width)
18929 (or attrwidth (car org-image-actual-width))))
18930 type (if width 'imagemagick)))
18931 (when (file-exists-p file)
18932 (if (and (car-safe old) refresh)
18933 (image-refresh (overlay-get (cdr old) 'display))
18934 (setq img (save-match-data (create-image file type nil :width width)))
18935 (when img
18936 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18937 (overlay-put ov 'display img)
18938 (overlay-put ov 'face 'default)
18939 (overlay-put ov 'org-image-overlay t)
18940 (overlay-put ov 'modification-hooks
18941 (list 'org-display-inline-remove-overlay))
18942 (push ov org-inline-image-overlays))))))))))
18944 (define-obsolete-function-alias
18945 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18947 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18948 "Remove inline-display overlay if a corresponding region is modified."
18949 (let ((inhibit-modification-hooks t))
18950 (when (and ov after)
18951 (delete ov org-inline-image-overlays)
18952 (delete-overlay ov))))
18954 (defun org-remove-inline-images ()
18955 "Remove inline display of images."
18956 (interactive)
18957 (mapc 'delete-overlay org-inline-image-overlays)
18958 (setq org-inline-image-overlays nil))
18960 ;;;; Key bindings
18962 ;; Outline functions from `outline-mode-prefix-map'
18963 ;; that can be remapped in Org:
18964 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18965 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18966 (define-key org-mode-map [remap outline-forward-same-level]
18967 'org-forward-heading-same-level)
18968 (define-key org-mode-map [remap outline-backward-same-level]
18969 'org-backward-heading-same-level)
18970 (define-key org-mode-map [remap show-branches]
18971 'org-kill-note-or-show-branches)
18972 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18973 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18974 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18976 ;; Outline functions from `outline-mode-prefix-map' that can not
18977 ;; be remapped in Org:
18979 ;; - the column "key binding" shows whether the Outline function is still
18980 ;; available in Org mode on the same key that it has been bound to in
18981 ;; Outline mode:
18982 ;; - "overridden": key used for a different functionality in Org mode
18983 ;; - else: key still bound to the same Outline function in Org mode
18985 ;; | Outline function | key binding | Org replacement |
18986 ;; |------------------------------------+-------------+-----------------------|
18987 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18988 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18989 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18990 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18991 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18992 ;; | `show-entry' | overridden | no replacement |
18993 ;; | `show-children' | `C-c C-i' | visibility cycling |
18994 ;; | `show-branches' | `C-c C-k' | still same function |
18995 ;; | `show-subtree' | overridden | visibility cycling |
18996 ;; | `show-all' | overridden | no replacement |
18997 ;; | `hide-subtree' | overridden | visibility cycling |
18998 ;; | `hide-body' | overridden | no replacement |
18999 ;; | `hide-entry' | overridden | visibility cycling |
19000 ;; | `hide-leaves' | overridden | no replacement |
19001 ;; | `hide-sublevels' | overridden | no replacement |
19002 ;; | `hide-other' | overridden | no replacement |
19004 ;; Make `C-c C-x' a prefix key
19005 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19007 ;; TAB key with modifiers
19008 (org-defkey org-mode-map "\C-i" 'org-cycle)
19009 (org-defkey org-mode-map [(tab)] 'org-cycle)
19010 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19011 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19012 ;; The following line is necessary under Suse GNU/Linux
19013 (unless (featurep 'xemacs)
19014 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19015 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19016 (define-key org-mode-map [backtab] 'org-shifttab)
19018 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19019 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19020 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19022 ;; Cursor keys with modifiers
19023 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19024 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19025 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19026 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19028 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19029 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19030 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19031 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19033 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19034 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19035 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19036 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19038 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19039 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19040 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19041 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19043 ;; Babel keys
19044 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19045 (mapc (lambda (pair)
19046 (define-key org-babel-map (car pair) (cdr pair)))
19047 org-babel-key-bindings)
19049 ;;; Extra keys for tty access.
19050 ;; We only set them when really needed because otherwise the
19051 ;; menus don't show the simple keys
19053 (when (or org-use-extra-keys
19054 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19055 (not window-system))
19056 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19057 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19058 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19059 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19060 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19061 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19062 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19063 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19064 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19065 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19066 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19067 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19068 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19069 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19070 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19071 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19072 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19073 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19074 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19075 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19076 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19077 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19078 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19079 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19080 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19081 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19082 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19083 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19085 ;; All the other keys
19087 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19088 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19089 (if (boundp 'narrow-map)
19090 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19091 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19092 (if (boundp 'narrow-map)
19093 (org-defkey narrow-map "b" 'org-narrow-to-block)
19094 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19095 (if (boundp 'narrow-map)
19096 (org-defkey narrow-map "e" 'org-narrow-to-element)
19097 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19098 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19099 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19100 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19101 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19102 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19103 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19104 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19105 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19106 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19107 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19108 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19109 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19110 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19111 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19112 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19113 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19114 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19115 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19116 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19117 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19118 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19119 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19120 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19121 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19122 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19123 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19124 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19125 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19126 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19127 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19128 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19129 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19130 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19131 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19132 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19133 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19134 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19135 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19136 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19137 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19138 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19139 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19140 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19141 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19142 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19143 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19144 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19145 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19146 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19147 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19148 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19149 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19150 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19151 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19152 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19153 (org-defkey org-mode-map "\C-c^" 'org-sort)
19154 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19155 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19156 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19157 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19158 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19159 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19160 (org-defkey org-mode-map "\C-m" 'org-return)
19161 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19162 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19163 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19164 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19165 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19166 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19167 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19168 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19169 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19170 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19171 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19172 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19173 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19174 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19175 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19176 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19177 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19178 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19179 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19180 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19181 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19182 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19183 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19185 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19186 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19187 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19189 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19190 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19191 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19192 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19193 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19194 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19195 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19196 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19197 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19198 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19199 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19200 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19201 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19202 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19203 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19204 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19205 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19206 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19207 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19208 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19209 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19210 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19211 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19213 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19214 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19215 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19216 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19217 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19219 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19221 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19223 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19224 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19226 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19229 (when (featurep 'xemacs)
19230 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19233 (defconst org-speed-commands-default
19235 ("Outline Navigation")
19236 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19237 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19238 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19239 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19240 ("F" . org-next-block)
19241 ("B" . org-previous-block)
19242 ("u" . (org-speed-move-safe 'outline-up-heading))
19243 ("j" . org-goto)
19244 ("g" . (org-refile t))
19245 ("Outline Visibility")
19246 ("c" . org-cycle)
19247 ("C" . org-shifttab)
19248 (" " . org-display-outline-path)
19249 ("s" . org-narrow-to-subtree)
19250 ("=" . org-columns)
19251 ("Outline Structure Editing")
19252 ("U" . org-shiftmetaup)
19253 ("D" . org-shiftmetadown)
19254 ("r" . org-metaright)
19255 ("l" . org-metaleft)
19256 ("R" . org-shiftmetaright)
19257 ("L" . org-shiftmetaleft)
19258 ("i" . (progn (forward-char 1) (call-interactively
19259 'org-insert-heading-respect-content)))
19260 ("^" . org-sort)
19261 ("w" . org-refile)
19262 ("a" . org-archive-subtree-default-with-confirmation)
19263 ("@" . org-mark-subtree)
19264 ("#" . org-toggle-comment)
19265 ("Clock Commands")
19266 ("I" . org-clock-in)
19267 ("O" . org-clock-out)
19268 ("Meta Data Editing")
19269 ("t" . org-todo)
19270 ("," . (org-priority))
19271 ("0" . (org-priority ?\ ))
19272 ("1" . (org-priority ?A))
19273 ("2" . (org-priority ?B))
19274 ("3" . (org-priority ?C))
19275 (":" . org-set-tags-command)
19276 ("e" . org-set-effort)
19277 ("E" . org-inc-effort)
19278 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19279 (org-entry-put (point) "APPT_WARNTIME" m)))
19280 ("Agenda Views etc")
19281 ("v" . org-agenda)
19282 ("/" . org-sparse-tree)
19283 ("Misc")
19284 ("o" . org-open-at-point)
19285 ("?" . org-speed-command-help)
19286 ("<" . (org-agenda-set-restriction-lock 'subtree))
19287 (">" . (org-agenda-remove-restriction-lock))
19289 "The default speed commands.")
19291 (defun org-print-speed-command (e)
19292 (if (> (length (car e)) 1)
19293 (progn
19294 (princ "\n")
19295 (princ (car e))
19296 (princ "\n")
19297 (princ (make-string (length (car e)) ?-))
19298 (princ "\n"))
19299 (princ (car e))
19300 (princ " ")
19301 (if (symbolp (cdr e))
19302 (princ (symbol-name (cdr e)))
19303 (prin1 (cdr e)))
19304 (princ "\n")))
19306 (defun org-speed-command-help ()
19307 "Show the available speed commands."
19308 (interactive)
19309 (if (not org-use-speed-commands)
19310 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19311 (with-output-to-temp-buffer "*Help*"
19312 (princ "User-defined Speed commands\n===========================\n")
19313 (mapc 'org-print-speed-command org-speed-commands-user)
19314 (princ "\n")
19315 (princ "Built-in Speed commands\n=======================\n")
19316 (mapc 'org-print-speed-command org-speed-commands-default))
19317 (with-current-buffer "*Help*"
19318 (setq truncate-lines t))))
19320 (defun org-speed-move-safe (cmd)
19321 "Execute CMD, but make sure that the cursor always ends up in a headline.
19322 If not, return to the original position and throw an error."
19323 (interactive)
19324 (let ((pos (point)))
19325 (call-interactively cmd)
19326 (unless (and (bolp) (org-at-heading-p))
19327 (goto-char pos)
19328 (error "Boundary reached while executing %s" cmd))))
19330 (defvar org-self-insert-command-undo-counter 0)
19332 (defvar org-table-auto-blank-field) ; defined in org-table.el
19333 (defvar org-speed-command nil)
19335 (define-obsolete-function-alias
19336 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19338 (defun org-speed-command-activate (keys)
19339 "Hook for activating single-letter speed commands.
19340 `org-speed-commands-default' specifies a minimal command set.
19341 Use `org-speed-commands-user' for further customization."
19342 (when (or (and (bolp) (looking-at org-outline-regexp))
19343 (and (functionp org-use-speed-commands)
19344 (funcall org-use-speed-commands)))
19345 (cdr (assoc keys (append org-speed-commands-user
19346 org-speed-commands-default)))))
19348 (define-obsolete-function-alias
19349 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19351 (defun org-babel-speed-command-activate (keys)
19352 "Hook for activating single-letter code block commands."
19353 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19354 (cdr (assoc keys org-babel-key-bindings))))
19356 (defcustom org-speed-command-hook
19357 '(org-speed-command-default-hook org-babel-speed-command-hook)
19358 "Hook for activating speed commands at strategic locations.
19359 Hook functions are called in sequence until a valid handler is
19360 found.
19362 Each hook takes a single argument, a user-pressed command key
19363 which is also a `self-insert-command' from the global map.
19365 Within the hook, examine the cursor position and the command key
19366 and return nil or a valid handler as appropriate. Handler could
19367 be one of an interactive command, a function, or a form.
19369 Set `org-use-speed-commands' to non-nil value to enable this
19370 hook. The default setting is `org-speed-command-activate'."
19371 :group 'org-structure
19372 :version "24.1"
19373 :type 'hook)
19375 (defun org-self-insert-command (N)
19376 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19377 If the cursor is in a table looking at whitespace, the whitespace is
19378 overwritten, and the table is not marked as requiring realignment."
19379 (interactive "p")
19380 (org-check-before-invisible-edit 'insert)
19381 (cond
19382 ((and org-use-speed-commands
19383 (setq org-speed-command
19384 (run-hook-with-args-until-success
19385 'org-speed-command-hook (this-command-keys))))
19386 (cond
19387 ((commandp org-speed-command)
19388 (setq this-command org-speed-command)
19389 (call-interactively org-speed-command))
19390 ((functionp org-speed-command)
19391 (funcall org-speed-command))
19392 ((and org-speed-command (listp org-speed-command))
19393 (eval org-speed-command))
19394 (t (let (org-use-speed-commands)
19395 (call-interactively 'org-self-insert-command)))))
19396 ((and
19397 (org-table-p)
19398 (progn
19399 ;; check if we blank the field, and if that triggers align
19400 (and (featurep 'org-table) org-table-auto-blank-field
19401 (member last-command
19402 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19403 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19404 ;; got extra space, this field does not determine column width
19405 (let (org-table-may-need-update) (org-table-blank-field))
19406 ;; no extra space, this field may determine column width
19407 (org-table-blank-field)))
19409 (eq N 1)
19410 (looking-at "[^|\n]* |"))
19411 (let (org-table-may-need-update)
19412 (goto-char (1- (match-end 0)))
19413 (backward-delete-char 1)
19414 (goto-char (match-beginning 0))
19415 (self-insert-command N)))
19417 (setq org-table-may-need-update t)
19418 (self-insert-command N)
19419 (org-fix-tags-on-the-fly)
19420 (if org-self-insert-cluster-for-undo
19421 (if (not (eq last-command 'org-self-insert-command))
19422 (setq org-self-insert-command-undo-counter 1)
19423 (if (>= org-self-insert-command-undo-counter 20)
19424 (setq org-self-insert-command-undo-counter 1)
19425 (and (> org-self-insert-command-undo-counter 0)
19426 buffer-undo-list (listp buffer-undo-list)
19427 (not (cadr buffer-undo-list)) ; remove nil entry
19428 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19429 (setq org-self-insert-command-undo-counter
19430 (1+ org-self-insert-command-undo-counter))))))))
19432 (defun org-check-before-invisible-edit (kind)
19433 "Check is editing if kind KIND would be dangerous with invisible text around.
19434 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19435 ;; First, try to get out of here as quickly as possible, to reduce overhead
19436 (if (and org-catch-invisible-edits
19437 (or (not (boundp 'visible-mode)) (not visible-mode))
19438 (or (get-char-property (point) 'invisible)
19439 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19440 ;; OK, we need to take a closer look
19441 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19442 (invisible-before-point (if (bobp) nil (get-char-property
19443 (1- (point)) 'invisible)))
19444 (border-and-ok-direction
19446 ;; Check if we are acting predictably before invisible text
19447 (and invisible-at-point (not invisible-before-point)
19448 (memq kind '(insert delete-backward)))
19449 ;; Check if we are acting predictably after invisible text
19450 ;; This works not well, and I have turned it off. It seems
19451 ;; better to always show and stop after invisible text.
19452 ;; (and (not invisible-at-point) invisible-before-point
19453 ;; (memq kind '(insert delete)))
19455 (when (or (memq invisible-at-point '(outline org-hide-block t))
19456 (memq invisible-before-point '(outline org-hide-block t)))
19457 (if (eq org-catch-invisible-edits 'error)
19458 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19459 (if (and org-custom-properties-overlays
19460 (y-or-n-p "Display invisible properties in this buffer? "))
19461 (org-toggle-custom-properties-visibility)
19462 ;; Make the area visible
19463 (save-excursion
19464 (if invisible-before-point
19465 (goto-char (previous-single-char-property-change
19466 (point) 'invisible)))
19467 (org-cycle))
19468 (cond
19469 ((eq org-catch-invisible-edits 'show)
19470 ;; That's it, we do the edit after showing
19471 (message
19472 "Unfolding invisible region around point before editing")
19473 (sit-for 1))
19474 ((and (eq org-catch-invisible-edits 'smart)
19475 border-and-ok-direction)
19476 (message "Unfolding invisible region around point before editing"))
19478 ;; Don't do the edit, make the user repeat it in full visibility
19479 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19481 (defun org-fix-tags-on-the-fly ()
19482 (when (and (equal (char-after (point-at-bol)) ?*)
19483 (org-at-heading-p))
19484 (org-align-tags-here org-tags-column)))
19486 (defun org-delete-backward-char (N)
19487 "Like `delete-backward-char', insert whitespace at field end in tables.
19488 When deleting backwards, in tables this function will insert whitespace in
19489 front of the next \"|\" separator, to keep the table aligned. The table will
19490 still be marked for re-alignment if the field did fill the entire column,
19491 because, in this case the deletion might narrow the column."
19492 (interactive "p")
19493 (save-match-data
19494 (org-check-before-invisible-edit 'delete-backward)
19495 (if (and (org-table-p)
19496 (eq N 1)
19497 (string-match "|" (buffer-substring (point-at-bol) (point)))
19498 (looking-at ".*?|"))
19499 (let ((pos (point))
19500 (noalign (looking-at "[^|\n\r]* |"))
19501 (c org-table-may-need-update))
19502 (backward-delete-char N)
19503 (if (not overwrite-mode)
19504 (progn
19505 (skip-chars-forward "^|")
19506 (insert " ")
19507 (goto-char (1- pos))))
19508 ;; noalign: if there were two spaces at the end, this field
19509 ;; does not determine the width of the column.
19510 (if noalign (setq org-table-may-need-update c)))
19511 (backward-delete-char N)
19512 (org-fix-tags-on-the-fly))))
19514 (defun org-delete-char (N)
19515 "Like `delete-char', but insert whitespace at field end in tables.
19516 When deleting characters, in tables this function will insert whitespace in
19517 front of the next \"|\" separator, to keep the table aligned. The table will
19518 still be marked for re-alignment if the field did fill the entire column,
19519 because, in this case the deletion might narrow the column."
19520 (interactive "p")
19521 (save-match-data
19522 (org-check-before-invisible-edit 'delete)
19523 (if (and (org-table-p)
19524 (not (bolp))
19525 (not (= (char-after) ?|))
19526 (eq N 1))
19527 (if (looking-at ".*?|")
19528 (let ((pos (point))
19529 (noalign (looking-at "[^|\n\r]* |"))
19530 (c org-table-may-need-update))
19531 (replace-match
19532 (concat (substring (match-string 0) 1 -1) " |") nil t)
19533 (goto-char pos)
19534 ;; noalign: if there were two spaces at the end, this field
19535 ;; does not determine the width of the column.
19536 (if noalign (setq org-table-may-need-update c)))
19537 (delete-char N))
19538 (delete-char N)
19539 (org-fix-tags-on-the-fly))))
19541 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19542 (put 'org-self-insert-command 'delete-selection
19543 (lambda ()
19544 (not (run-hook-with-args-until-success
19545 'self-insert-uses-region-functions))))
19546 (put 'orgtbl-self-insert-command 'delete-selection
19547 (lambda ()
19548 (not (run-hook-with-args-until-success
19549 'self-insert-uses-region-functions))))
19550 (put 'org-delete-char 'delete-selection 'supersede)
19551 (put 'org-delete-backward-char 'delete-selection 'supersede)
19552 (put 'org-yank 'delete-selection 'yank)
19554 ;; Make `flyspell-mode' delay after some commands
19555 (put 'org-self-insert-command 'flyspell-delayed t)
19556 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19557 (put 'org-delete-char 'flyspell-delayed t)
19558 (put 'org-delete-backward-char 'flyspell-delayed t)
19560 ;; Make pabbrev-mode expand after org-mode commands
19561 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19562 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19564 (defun org-remap (map &rest commands)
19565 "In MAP, remap the functions given in COMMANDS.
19566 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19567 (let (new old)
19568 (while commands
19569 (setq old (pop commands) new (pop commands))
19570 (if (fboundp 'command-remapping)
19571 (org-defkey map (vector 'remap old) new)
19572 (substitute-key-definition old new map global-map)))))
19574 (defun org-transpose-words ()
19575 "Transpose words for Org.
19576 This uses the `org-mode-transpose-word-syntax-table' syntax
19577 table, which interprets characters in `org-emphasis-alist' as
19578 word constituents."
19579 (interactive)
19580 (with-syntax-table org-mode-transpose-word-syntax-table
19581 (call-interactively 'transpose-words)))
19582 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19584 (when (eq org-enable-table-editor 'optimized)
19585 ;; If the user wants maximum table support, we need to hijack
19586 ;; some standard editing functions
19587 (org-remap org-mode-map
19588 'self-insert-command 'org-self-insert-command
19589 'delete-char 'org-delete-char
19590 'delete-backward-char 'org-delete-backward-char)
19591 (org-defkey org-mode-map "|" 'org-force-self-insert))
19593 (defvar org-ctrl-c-ctrl-c-hook nil
19594 "Hook for functions attaching themselves to `C-c C-c'.
19596 This can be used to add additional functionality to the C-c C-c
19597 key which executes context-dependent commands. This hook is run
19598 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19599 run after the last test.
19601 Each function will be called with no arguments. The function
19602 must check if the context is appropriate for it to act. If yes,
19603 it should do its thing and then return a non-nil value. If the
19604 context is wrong, just do nothing and return nil.")
19606 (defvar org-ctrl-c-ctrl-c-final-hook nil
19607 "Hook for functions attaching themselves to `C-c C-c'.
19609 This can be used to add additional functionality to the C-c C-c
19610 key which executes context-dependent commands. This hook is run
19611 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19612 before the first test.
19614 Each function will be called with no arguments. The function
19615 must check if the context is appropriate for it to act. If yes,
19616 it should do its thing and then return a non-nil value. If the
19617 context is wrong, just do nothing and return nil.")
19619 (defvar org-tab-first-hook nil
19620 "Hook for functions to attach themselves to TAB.
19621 See `org-ctrl-c-ctrl-c-hook' for more information.
19622 This hook runs as the first action when TAB is pressed, even before
19623 `org-cycle' messes around with the `outline-regexp' to cater for
19624 inline tasks and plain list item folding.
19625 If any function in this hook returns t, any other actions that
19626 would have been caused by TAB (such as table field motion or visibility
19627 cycling) will not occur.")
19629 (defvar org-tab-after-check-for-table-hook nil
19630 "Hook for functions to attach themselves to TAB.
19631 See `org-ctrl-c-ctrl-c-hook' for more information.
19632 This hook runs after it has been established that the cursor is not in a
19633 table, but before checking if the cursor is in a headline or if global cycling
19634 should be done.
19635 If any function in this hook returns t, not other actions like visibility
19636 cycling will be done.")
19638 (defvar org-tab-after-check-for-cycling-hook nil
19639 "Hook for functions to attach themselves to TAB.
19640 See `org-ctrl-c-ctrl-c-hook' for more information.
19641 This hook runs after it has been established that not table field motion and
19642 not visibility should be done because of current context. This is probably
19643 the place where a package like yasnippets can hook in.")
19645 (defvar org-tab-before-tab-emulation-hook nil
19646 "Hook for functions to attach themselves to TAB.
19647 See `org-ctrl-c-ctrl-c-hook' for more information.
19648 This hook runs after every other options for TAB have been exhausted, but
19649 before indentation and \t insertion takes place.")
19651 (defvar org-metaleft-hook nil
19652 "Hook for functions attaching themselves to `M-left'.
19653 See `org-ctrl-c-ctrl-c-hook' for more information.")
19654 (defvar org-metaright-hook nil
19655 "Hook for functions attaching themselves to `M-right'.
19656 See `org-ctrl-c-ctrl-c-hook' for more information.")
19657 (defvar org-metaup-hook nil
19658 "Hook for functions attaching themselves to `M-up'.
19659 See `org-ctrl-c-ctrl-c-hook' for more information.")
19660 (defvar org-metadown-hook nil
19661 "Hook for functions attaching themselves to `M-down'.
19662 See `org-ctrl-c-ctrl-c-hook' for more information.")
19663 (defvar org-shiftmetaleft-hook nil
19664 "Hook for functions attaching themselves to `M-S-left'.
19665 See `org-ctrl-c-ctrl-c-hook' for more information.")
19666 (defvar org-shiftmetaright-hook nil
19667 "Hook for functions attaching themselves to `M-S-right'.
19668 See `org-ctrl-c-ctrl-c-hook' for more information.")
19669 (defvar org-shiftmetaup-hook nil
19670 "Hook for functions attaching themselves to `M-S-up'.
19671 See `org-ctrl-c-ctrl-c-hook' for more information.")
19672 (defvar org-shiftmetadown-hook nil
19673 "Hook for functions attaching themselves to `M-S-down'.
19674 See `org-ctrl-c-ctrl-c-hook' for more information.")
19675 (defvar org-metareturn-hook nil
19676 "Hook for functions attaching themselves to `M-RET'.
19677 See `org-ctrl-c-ctrl-c-hook' for more information.")
19678 (defvar org-shiftup-hook nil
19679 "Hook for functions attaching themselves to `S-up'.
19680 See `org-ctrl-c-ctrl-c-hook' for more information.")
19681 (defvar org-shiftup-final-hook nil
19682 "Hook for functions attaching themselves to `S-up'.
19683 This one runs after all other options except shift-select have been excluded.
19684 See `org-ctrl-c-ctrl-c-hook' for more information.")
19685 (defvar org-shiftdown-hook nil
19686 "Hook for functions attaching themselves to `S-down'.
19687 See `org-ctrl-c-ctrl-c-hook' for more information.")
19688 (defvar org-shiftdown-final-hook nil
19689 "Hook for functions attaching themselves to `S-down'.
19690 This one runs after all other options except shift-select have been excluded.
19691 See `org-ctrl-c-ctrl-c-hook' for more information.")
19692 (defvar org-shiftleft-hook nil
19693 "Hook for functions attaching themselves to `S-left'.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.")
19695 (defvar org-shiftleft-final-hook nil
19696 "Hook for functions attaching themselves to `S-left'.
19697 This one runs after all other options except shift-select have been excluded.
19698 See `org-ctrl-c-ctrl-c-hook' for more information.")
19699 (defvar org-shiftright-hook nil
19700 "Hook for functions attaching themselves to `S-right'.
19701 See `org-ctrl-c-ctrl-c-hook' for more information.")
19702 (defvar org-shiftright-final-hook nil
19703 "Hook for functions attaching themselves to `S-right'.
19704 This one runs after all other options except shift-select have been excluded.
19705 See `org-ctrl-c-ctrl-c-hook' for more information.")
19707 (defun org-modifier-cursor-error ()
19708 "Throw an error, a modified cursor command was applied in wrong context."
19709 (user-error "This command is active in special context like tables, headlines or items"))
19711 (defun org-shiftselect-error ()
19712 "Throw an error because Shift-Cursor command was applied in wrong context."
19713 (if (and (boundp 'shift-select-mode) shift-select-mode)
19714 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19715 (user-error "This command works only in special context like headlines or timestamps")))
19717 (defun org-call-for-shift-select (cmd)
19718 (let ((this-command-keys-shift-translated t))
19719 (call-interactively cmd)))
19721 (defun org-shifttab (&optional arg)
19722 "Global visibility cycling or move to previous table field.
19723 Call `org-table-previous-field' within a table.
19724 When ARG is nil, cycle globally through visibility states.
19725 When ARG is a numeric prefix, show contents of this level."
19726 (interactive "P")
19727 (cond
19728 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19729 ((integerp arg)
19730 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19731 (message "Content view to level: %d" arg)
19732 (org-content (prefix-numeric-value arg2))
19733 (org-cycle-show-empty-lines t)
19734 (setq org-cycle-global-status 'overview)))
19735 (t (call-interactively 'org-global-cycle))))
19737 (defun org-shiftmetaleft ()
19738 "Promote subtree or delete table column.
19739 Calls `org-promote-subtree', `org-outdent-item-tree', or
19740 `org-table-delete-column', depending on context. See the
19741 individual commands for more information."
19742 (interactive)
19743 (cond
19744 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19745 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19746 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19747 ((if (not (org-region-active-p)) (org-at-item-p)
19748 (save-excursion (goto-char (region-beginning))
19749 (org-at-item-p)))
19750 (call-interactively 'org-outdent-item-tree))
19751 (t (org-modifier-cursor-error))))
19753 (defun org-shiftmetaright ()
19754 "Demote subtree or insert table column.
19755 Calls `org-demote-subtree', `org-indent-item-tree', or
19756 `org-table-insert-column', depending on context. See the
19757 individual commands for more information."
19758 (interactive)
19759 (cond
19760 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19761 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19762 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19763 ((if (not (org-region-active-p)) (org-at-item-p)
19764 (save-excursion (goto-char (region-beginning))
19765 (org-at-item-p)))
19766 (call-interactively 'org-indent-item-tree))
19767 (t (org-modifier-cursor-error))))
19769 (defun org-shiftmetaup (&optional arg)
19770 "Move subtree up or kill table row.
19771 Calls `org-move-subtree-up' or `org-table-kill-row' or
19772 `org-move-item-up' or `org-timestamp-up', depending on context.
19773 See the individual commands for more information."
19774 (interactive "P")
19775 (cond
19776 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19777 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19778 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19779 ((org-at-item-p) (call-interactively 'org-move-item-up))
19780 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19781 (call-interactively 'org-timestamp-up)))
19782 (t (call-interactively 'org-drag-line-backward))))
19784 (defun org-shiftmetadown (&optional arg)
19785 "Move subtree down or insert table row.
19786 Calls `org-move-subtree-down' or `org-table-insert-row' or
19787 `org-move-item-down' or `org-timestamp-up', depending on context.
19788 See the individual commands for more information."
19789 (interactive "P")
19790 (cond
19791 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19792 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19793 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19794 ((org-at-item-p) (call-interactively 'org-move-item-down))
19795 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19796 (call-interactively 'org-timestamp-down)))
19797 (t (call-interactively 'org-drag-line-forward))))
19799 (defsubst org-hidden-tree-error ()
19800 (user-error
19801 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19803 (defun org-metaleft (&optional arg)
19804 "Promote heading or move table column to left.
19805 Calls `org-do-promote' or `org-table-move-column', depending on context.
19806 With no specific context, calls the Emacs default `backward-word'.
19807 See the individual commands for more information."
19808 (interactive "P")
19809 (cond
19810 ((run-hook-with-args-until-success 'org-metaleft-hook))
19811 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19812 ((org-with-limited-levels
19813 (or (org-at-heading-p)
19814 (and (org-region-active-p)
19815 (save-excursion
19816 (goto-char (region-beginning))
19817 (org-at-heading-p)))))
19818 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19819 (call-interactively 'org-do-promote))
19820 ;; At an inline task.
19821 ((org-at-heading-p)
19822 (call-interactively 'org-inlinetask-promote))
19823 ((or (org-at-item-p)
19824 (and (org-region-active-p)
19825 (save-excursion
19826 (goto-char (region-beginning))
19827 (org-at-item-p))))
19828 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19829 (call-interactively 'org-outdent-item))
19830 (t (call-interactively 'backward-word))))
19832 (defun org-metaright (&optional arg)
19833 "Demote a subtree, a list item or move table column to right.
19834 In front of a drawer or a block keyword, indent it correctly.
19835 With no specific context, calls the Emacs default `forward-word'.
19836 See the individual commands for more information."
19837 (interactive "P")
19838 (cond
19839 ((run-hook-with-args-until-success 'org-metaright-hook))
19840 ((org-at-table-p) (call-interactively 'org-table-move-column))
19841 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19842 ((org-at-block-p) (call-interactively 'org-indent-block))
19843 ((org-with-limited-levels
19844 (or (org-at-heading-p)
19845 (and (org-region-active-p)
19846 (save-excursion
19847 (goto-char (region-beginning))
19848 (org-at-heading-p)))))
19849 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19850 (call-interactively 'org-do-demote))
19851 ;; At an inline task.
19852 ((org-at-heading-p)
19853 (call-interactively 'org-inlinetask-demote))
19854 ((or (org-at-item-p)
19855 (and (org-region-active-p)
19856 (save-excursion
19857 (goto-char (region-beginning))
19858 (org-at-item-p))))
19859 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19860 (call-interactively 'org-indent-item))
19861 (t (call-interactively 'forward-word))))
19863 (defun org-check-for-hidden (what)
19864 "Check if there are hidden headlines/items in the current visual line.
19865 WHAT can be either `headlines' or `items'. If the current line is
19866 an outline or item heading and it has a folded subtree below it,
19867 this function returns t, nil otherwise."
19868 (let ((re (cond
19869 ((eq what 'headlines) org-outline-regexp-bol)
19870 ((eq what 'items) (org-item-beginning-re))
19871 (t (error "This should not happen"))))
19872 beg end)
19873 (save-excursion
19874 (catch 'exit
19875 (unless (org-region-active-p)
19876 (setq beg (point-at-bol))
19877 (beginning-of-line 2)
19878 (while (and (not (eobp)) ;; this is like `next-line'
19879 (get-char-property (1- (point)) 'invisible))
19880 (beginning-of-line 2))
19881 (setq end (point))
19882 (goto-char beg)
19883 (goto-char (point-at-eol))
19884 (setq end (max end (point)))
19885 (while (re-search-forward re end t)
19886 (if (get-char-property (match-beginning 0) 'invisible)
19887 (throw 'exit t))))
19888 nil))))
19890 (defun org-metaup (&optional arg)
19891 "Move subtree up or move table row up.
19892 Calls `org-move-subtree-up' or `org-table-move-row' or
19893 `org-move-item-up', depending on context. See the individual commands
19894 for more information."
19895 (interactive "P")
19896 (cond
19897 ((run-hook-with-args-until-success 'org-metaup-hook))
19898 ((org-region-active-p)
19899 (let* ((a (min (region-beginning) (region-end)))
19900 (b (1- (max (region-beginning) (region-end))))
19901 (c (save-excursion (goto-char a)
19902 (move-beginning-of-line 0)))
19903 (d (save-excursion (goto-char a)
19904 (move-end-of-line 0) (point))))
19905 (transpose-regions a b c d)
19906 (goto-char c)))
19907 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19908 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19909 ((org-at-item-p) (call-interactively 'org-move-item-up))
19910 (t (org-drag-element-backward))))
19912 (defun org-metadown (&optional arg)
19913 "Move subtree down or move table row down.
19914 Calls `org-move-subtree-down' or `org-table-move-row' or
19915 `org-move-item-down', depending on context. See the individual
19916 commands for more information."
19917 (interactive "P")
19918 (cond
19919 ((run-hook-with-args-until-success 'org-metadown-hook))
19920 ((org-region-active-p)
19921 (let* ((a (min (region-beginning) (region-end)))
19922 (b (max (region-beginning) (region-end)))
19923 (c (save-excursion (goto-char b)
19924 (move-beginning-of-line 1)))
19925 (d (save-excursion (goto-char b)
19926 (move-end-of-line 1) (1+ (point)))))
19927 (transpose-regions a b c d)
19928 (goto-char d)))
19929 ((org-at-table-p) (call-interactively 'org-table-move-row))
19930 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19931 ((org-at-item-p) (call-interactively 'org-move-item-down))
19932 (t (org-drag-element-forward))))
19934 (defun org-shiftup (&optional arg)
19935 "Increase item in timestamp or increase priority of current headline.
19936 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19937 depending on context. See the individual commands for more information."
19938 (interactive "P")
19939 (cond
19940 ((run-hook-with-args-until-success 'org-shiftup-hook))
19941 ((and org-support-shift-select (org-region-active-p))
19942 (org-call-for-shift-select 'previous-line))
19943 ((org-at-timestamp-p t)
19944 (call-interactively (if org-edit-timestamp-down-means-later
19945 'org-timestamp-down 'org-timestamp-up)))
19946 ((and (not (eq org-support-shift-select 'always))
19947 org-enable-priority-commands
19948 (org-at-heading-p))
19949 (call-interactively 'org-priority-up))
19950 ((and (not org-support-shift-select) (org-at-item-p))
19951 (call-interactively 'org-previous-item))
19952 ((org-clocktable-try-shift 'up arg))
19953 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19954 (org-support-shift-select
19955 (org-call-for-shift-select 'previous-line))
19956 (t (org-shiftselect-error))))
19958 (defun org-shiftdown (&optional arg)
19959 "Decrease item in timestamp or decrease priority of current headline.
19960 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19961 depending on context. See the individual commands for more information."
19962 (interactive "P")
19963 (cond
19964 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19965 ((and org-support-shift-select (org-region-active-p))
19966 (org-call-for-shift-select 'next-line))
19967 ((org-at-timestamp-p t)
19968 (call-interactively (if org-edit-timestamp-down-means-later
19969 'org-timestamp-up 'org-timestamp-down)))
19970 ((and (not (eq org-support-shift-select 'always))
19971 org-enable-priority-commands
19972 (org-at-heading-p))
19973 (call-interactively 'org-priority-down))
19974 ((and (not org-support-shift-select) (org-at-item-p))
19975 (call-interactively 'org-next-item))
19976 ((org-clocktable-try-shift 'down arg))
19977 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19978 (org-support-shift-select
19979 (org-call-for-shift-select 'next-line))
19980 (t (org-shiftselect-error))))
19982 (defun org-shiftright (&optional arg)
19983 "Cycle the thing at point or in the current line, depending on context.
19984 Depending on context, this does one of the following:
19986 - switch a timestamp at point one day into the future
19987 - on a headline, switch to the next TODO keyword.
19988 - on an item, switch entire list to the next bullet type
19989 - on a property line, switch to the next allowed value
19990 - on a clocktable definition line, move time block into the future"
19991 (interactive "P")
19992 (cond
19993 ((run-hook-with-args-until-success 'org-shiftright-hook))
19994 ((and org-support-shift-select (org-region-active-p))
19995 (org-call-for-shift-select 'forward-char))
19996 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19997 ((and (not (eq org-support-shift-select 'always))
19998 (org-at-heading-p))
19999 (let ((org-inhibit-logging
20000 (not org-treat-S-cursor-todo-selection-as-state-change))
20001 (org-inhibit-blocking
20002 (not org-treat-S-cursor-todo-selection-as-state-change)))
20003 (org-call-with-arg 'org-todo 'right)))
20004 ((or (and org-support-shift-select
20005 (not (eq org-support-shift-select 'always))
20006 (org-at-item-bullet-p))
20007 (and (not org-support-shift-select) (org-at-item-p)))
20008 (org-call-with-arg 'org-cycle-list-bullet nil))
20009 ((and (not (eq org-support-shift-select 'always))
20010 (org-at-property-p))
20011 (call-interactively 'org-property-next-allowed-value))
20012 ((org-clocktable-try-shift 'right arg))
20013 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20014 (org-support-shift-select
20015 (org-call-for-shift-select 'forward-char))
20016 (t (org-shiftselect-error))))
20018 (defun org-shiftleft (&optional arg)
20019 "Cycle the thing at point or in the current line, depending on context.
20020 Depending on context, this does one of the following:
20022 - switch a timestamp at point one day into the past
20023 - on a headline, switch to the previous TODO keyword.
20024 - on an item, switch entire list to the previous bullet type
20025 - on a property line, switch to the previous allowed value
20026 - on a clocktable definition line, move time block into the past"
20027 (interactive "P")
20028 (cond
20029 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20030 ((and org-support-shift-select (org-region-active-p))
20031 (org-call-for-shift-select 'backward-char))
20032 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20033 ((and (not (eq org-support-shift-select 'always))
20034 (org-at-heading-p))
20035 (let ((org-inhibit-logging
20036 (not org-treat-S-cursor-todo-selection-as-state-change))
20037 (org-inhibit-blocking
20038 (not org-treat-S-cursor-todo-selection-as-state-change)))
20039 (org-call-with-arg 'org-todo 'left)))
20040 ((or (and org-support-shift-select
20041 (not (eq org-support-shift-select 'always))
20042 (org-at-item-bullet-p))
20043 (and (not org-support-shift-select) (org-at-item-p)))
20044 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20045 ((and (not (eq org-support-shift-select 'always))
20046 (org-at-property-p))
20047 (call-interactively 'org-property-previous-allowed-value))
20048 ((org-clocktable-try-shift 'left arg))
20049 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20050 (org-support-shift-select
20051 (org-call-for-shift-select 'backward-char))
20052 (t (org-shiftselect-error))))
20054 (defun org-shiftcontrolright ()
20055 "Switch to next TODO set."
20056 (interactive)
20057 (cond
20058 ((and org-support-shift-select (org-region-active-p))
20059 (org-call-for-shift-select 'forward-word))
20060 ((and (not (eq org-support-shift-select 'always))
20061 (org-at-heading-p))
20062 (org-call-with-arg 'org-todo 'nextset))
20063 (org-support-shift-select
20064 (org-call-for-shift-select 'forward-word))
20065 (t (org-shiftselect-error))))
20067 (defun org-shiftcontrolleft ()
20068 "Switch to previous TODO set."
20069 (interactive)
20070 (cond
20071 ((and org-support-shift-select (org-region-active-p))
20072 (org-call-for-shift-select 'backward-word))
20073 ((and (not (eq org-support-shift-select 'always))
20074 (org-at-heading-p))
20075 (org-call-with-arg 'org-todo 'previousset))
20076 (org-support-shift-select
20077 (org-call-for-shift-select 'backward-word))
20078 (t (org-shiftselect-error))))
20080 (defun org-shiftcontrolup (&optional n)
20081 "Change timestamps synchronously up in CLOCK log lines.
20082 Optional argument N tells to change by that many units."
20083 (interactive "P")
20084 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20085 (let (org-support-shift-select)
20086 (org-clock-timestamps-up n))
20087 (user-error "Not at a clock log")))
20089 (defun org-shiftcontroldown (&optional n)
20090 "Change timestamps synchronously down in CLOCK log lines.
20091 Optional argument N tells to change by that many units."
20092 (interactive "P")
20093 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20094 (let (org-support-shift-select)
20095 (org-clock-timestamps-down n))
20096 (user-error "Not at a clock log")))
20098 (defun org-ctrl-c-ret ()
20099 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20100 (interactive)
20101 (cond
20102 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20103 (t (call-interactively 'org-insert-heading))))
20105 (defun org-find-visible ()
20106 (let ((s (point)))
20107 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20108 (get-char-property s 'invisible)))
20110 (defun org-find-invisible ()
20111 (let ((s (point)))
20112 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20113 (not (get-char-property s 'invisible))))
20116 (defun org-copy-visible (beg end)
20117 "Copy the visible parts of the region."
20118 (interactive "r")
20119 (let (snippets s)
20120 (save-excursion
20121 (save-restriction
20122 (narrow-to-region beg end)
20123 (setq s (goto-char (point-min)))
20124 (while (not (= (point) (point-max)))
20125 (goto-char (org-find-invisible))
20126 (push (buffer-substring s (point)) snippets)
20127 (setq s (goto-char (org-find-visible))))))
20128 (kill-new (apply 'concat (nreverse snippets)))))
20130 (defun org-copy-special ()
20131 "Copy region in table or copy current subtree.
20132 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20133 See the individual commands for more information."
20134 (interactive)
20135 (call-interactively
20136 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20138 (defun org-cut-special ()
20139 "Cut region in table or cut current subtree.
20140 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20141 See the individual commands for more information."
20142 (interactive)
20143 (call-interactively
20144 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20146 (defun org-paste-special (arg)
20147 "Paste rectangular region into table, or past subtree relative to level.
20148 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20149 See the individual commands for more information."
20150 (interactive "P")
20151 (if (org-at-table-p)
20152 (org-table-paste-rectangle)
20153 (org-paste-subtree arg)))
20155 (defsubst org-in-fixed-width-region-p ()
20156 "Is point in a fixed-width region?"
20157 (save-match-data
20158 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20160 (defun org-edit-special (&optional arg)
20161 "Call a special editor for the element at point.
20162 When at a table, call the formula editor with `org-table-edit-formulas'.
20163 When in a source code block, call `org-edit-src-code'.
20164 When in a fixed-width region, call `org-edit-fixed-width-region'.
20165 When at an #+INCLUDE keyword, visit the included file.
20166 On a link, call `ffap' to visit the link at point.
20167 Otherwise, return a user error."
20168 (interactive "P")
20169 (let ((element (org-element-at-point)))
20170 (assert (not buffer-read-only) nil
20171 "Buffer is read-only: %s" (buffer-name))
20172 (case (org-element-type element)
20173 (src-block
20174 (if (not arg) (org-edit-src-code)
20175 (let* ((info (org-babel-get-src-block-info))
20176 (lang (nth 0 info))
20177 (params (nth 2 info))
20178 (session (cdr (assq :session params))))
20179 (if (not session) (org-edit-src-code)
20180 ;; At a src-block with a session and function called with
20181 ;; an ARG: switch to the buffer related to the inferior
20182 ;; process.
20183 (switch-to-buffer
20184 (funcall (intern (concat "org-babel-prep-session:" lang))
20185 session params))))))
20186 (keyword
20187 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20188 (find-file
20189 (org-remove-double-quotes
20190 (car (org-split-string (org-element-property :value element)))))
20191 (user-error "No special environment to edit here")))
20192 (table
20193 (if (eq (org-element-property :type element) 'table.el)
20194 (org-edit-src-code)
20195 (call-interactively 'org-table-edit-formulas)))
20196 ;; Only Org tables contain `table-row' type elements.
20197 (table-row (call-interactively 'org-table-edit-formulas))
20198 ((example-block export-block) (org-edit-src-code))
20199 (fixed-width (org-edit-fixed-width-region))
20200 (otherwise
20201 ;; No notable element at point. Though, we may be at a link,
20202 ;; which is an object. Thus, scan deeper.
20203 (if (eq (org-element-type (org-element-context element)) 'link)
20204 (call-interactively 'ffap)
20205 (user-error "No special environment to edit here"))))))
20207 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20208 (defun org-ctrl-c-ctrl-c (&optional arg)
20209 "Set tags in headline, or update according to changed information at point.
20211 This command does many different things, depending on context:
20213 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20214 this is what we do.
20216 - If the cursor is on a statistics cookie, update it.
20218 - If the cursor is in a headline, prompt for tags and insert them
20219 into the current line, aligned to `org-tags-column'. When called
20220 with prefix arg, realign all tags in the current buffer.
20222 - If the cursor is in one of the special #+KEYWORD lines, this
20223 triggers scanning the buffer for these lines and updating the
20224 information.
20226 - If the cursor is inside a table, realign the table. This command
20227 works even if the automatic table editor has been turned off.
20229 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20230 the entire table.
20232 - If the cursor is at a footnote reference or definition, jump to
20233 the corresponding definition or references, respectively.
20235 - If the cursor is a the beginning of a dynamic block, update it.
20237 - If the current buffer is a capture buffer, close note and file it.
20239 - If the cursor is on a <<<target>>>, update radio targets and
20240 corresponding links in this buffer.
20242 - If the cursor is on a numbered item in a plain list, renumber the
20243 ordered list.
20245 - If the cursor is on a checkbox, toggle it.
20247 - If the cursor is on a code block, evaluate it. The variable
20248 `org-confirm-babel-evaluate' can be used to control prompting
20249 before code block evaluation, by default every code block
20250 evaluation requires confirmation. Code block evaluation can be
20251 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20252 (interactive "P")
20253 (cond
20254 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20255 org-occur-highlights
20256 org-latex-fragment-image-overlays)
20257 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20258 (org-remove-occur-highlights)
20259 (org-remove-latex-fragment-image-overlays)
20260 (message "Temporary highlights/overlays removed from current buffer"))
20261 ((and (local-variable-p 'org-finish-function (current-buffer))
20262 (fboundp org-finish-function))
20263 (funcall org-finish-function))
20264 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20266 (let* ((context (org-element-context)) (type (org-element-type context)))
20267 ;; Test if point is within a blank line.
20268 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20269 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20270 (user-error "C-c C-c can do nothing useful at this location"))
20271 (case type
20272 ;; When at a link, act according to the parent instead.
20273 (link (setq context (org-element-property :parent context))
20274 (setq type (org-element-type context)))
20275 ;; Unsupported object types: refer to the first supported
20276 ;; element or object containing it.
20277 ((bold code entity export-snippet inline-babel-call inline-src-block
20278 italic latex-fragment line-break macro strike-through subscript
20279 superscript underline verbatim)
20280 (while (and (setq context (org-element-property :parent context))
20281 (not (memq (setq type (org-element-type context))
20282 '(radio-target paragraph verse-block
20283 table-cell)))))))
20284 ;; For convenience: at the first line of a paragraph on the
20285 ;; same line as an item, apply function on that item instead.
20286 (when (eq type 'paragraph)
20287 (let ((parent (org-element-property :parent context)))
20288 (when (and (eq (org-element-type parent) 'item)
20289 (= (point-at-bol) (org-element-property :begin parent)))
20290 (setq context parent type 'item))))
20291 ;; Act according to type of element or object at point.
20292 (case type
20293 (clock (org-clock-update-time-maybe))
20294 (dynamic-block
20295 (save-excursion
20296 (goto-char (org-element-property :post-affiliated context))
20297 (org-update-dblock)))
20298 (footnote-definition
20299 (goto-char (org-element-property :post-affiliated context))
20300 (call-interactively 'org-footnote-action))
20301 (footnote-reference (call-interactively 'org-footnote-action))
20302 ((headline inlinetask)
20303 (save-excursion (goto-char (org-element-property :begin context))
20304 (call-interactively 'org-set-tags)))
20305 (item
20306 ;; At an item: a double C-u set checkbox to "[-]"
20307 ;; unconditionally, whereas a single one will toggle its
20308 ;; presence. Without an universal argument, if the item
20309 ;; has a checkbox, toggle it. Otherwise repair the list.
20310 (let* ((box (org-element-property :checkbox context))
20311 (struct (org-element-property :structure context))
20312 (old-struct (copy-tree struct))
20313 (parents (org-list-parents-alist struct))
20314 (prevs (org-list-prevs-alist struct))
20315 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20316 (org-list-set-checkbox
20317 (org-element-property :begin context) struct
20318 (cond ((equal arg '(16)) "[-]")
20319 ((and (not box) (equal arg '(4))) "[ ]")
20320 ((or (not box) (equal arg '(4))) nil)
20321 ((eq box 'on) "[ ]")
20322 (t "[X]")))
20323 ;; Mimic `org-list-write-struct' but with grabbing
20324 ;; a return value from `org-list-struct-fix-box'.
20325 (org-list-struct-fix-ind struct parents 2)
20326 (org-list-struct-fix-item-end struct)
20327 (org-list-struct-fix-bul struct prevs)
20328 (org-list-struct-fix-ind struct parents)
20329 (let ((block-item
20330 (org-list-struct-fix-box struct parents prevs orderedp)))
20331 (if (and box (equal struct old-struct))
20332 (if (equal arg '(16))
20333 (message "Checkboxes already reset")
20334 (user-error "Cannot toggle this checkbox: %s"
20335 (if (eq box 'on)
20336 "all subitems checked"
20337 "unchecked subitems")))
20338 (org-list-struct-apply-struct struct old-struct)
20339 (org-update-checkbox-count-maybe))
20340 (when block-item
20341 (message "Checkboxes were removed due to empty box at line %d"
20342 (org-current-line block-item))))))
20343 (keyword
20344 (let ((org-inhibit-startup-visibility-stuff t)
20345 (org-startup-align-all-tables nil))
20346 (when (boundp 'org-table-coordinate-overlays)
20347 (mapc 'delete-overlay org-table-coordinate-overlays)
20348 (setq org-table-coordinate-overlays nil))
20349 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20350 (message "Local setup has been refreshed"))
20351 (plain-list
20352 ;; At a plain list, with a double C-u argument, set
20353 ;; checkboxes of each item to "[-]", whereas a single one
20354 ;; will toggle their presence according to the state of the
20355 ;; first item in the list. Without an argument, repair the
20356 ;; list.
20357 (let* ((begin (org-element-property :contents-begin context))
20358 (beginm (move-marker (make-marker) begin))
20359 (struct (org-element-property :structure context))
20360 (old-struct (copy-tree struct))
20361 (first-box (save-excursion
20362 (goto-char begin)
20363 (looking-at org-list-full-item-re)
20364 (match-string-no-properties 3)))
20365 (new-box (cond ((equal arg '(16)) "[-]")
20366 ((equal arg '(4)) (unless first-box "[ ]"))
20367 ((equal first-box "[X]") "[ ]")
20368 (t "[X]"))))
20369 (cond
20370 (arg
20371 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20372 (org-list-get-all-items
20373 begin struct (org-list-prevs-alist struct))))
20374 ((and first-box (eq (point) begin))
20375 ;; For convenience, when point is at bol on the first
20376 ;; item of the list and no argument is provided, simply
20377 ;; toggle checkbox of that item, if any.
20378 (org-list-set-checkbox begin struct new-box)))
20379 (org-list-write-struct
20380 struct (org-list-parents-alist struct) old-struct)
20381 (org-update-checkbox-count-maybe)
20382 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20383 ((property-drawer node-property)
20384 (call-interactively 'org-property-action))
20385 ((radio-target target)
20386 (call-interactively 'org-update-radio-target-regexp))
20387 (statistics-cookie
20388 (call-interactively 'org-update-statistics-cookies))
20389 ((table table-cell table-row)
20390 ;; At a table, recalculate every field and align it. Also
20391 ;; send the table if necessary. If the table has
20392 ;; a `table.el' type, just give up. At a table row or
20393 ;; cell, maybe recalculate line but always align table.
20394 (if (eq (org-element-property :type context) 'table.el)
20395 (message "Use C-c ' to edit table.el tables")
20396 (let ((org-enable-table-editor t))
20397 (if (or (eq type 'table)
20398 ;; Check if point is at a TBLFM line.
20399 (and (eq type 'table-row)
20400 (= (point) (org-element-property :end context))))
20401 (save-excursion
20402 (if (org-at-TBLFM-p)
20403 (progn (require 'org-table)
20404 (org-table-calc-current-TBLFM))
20405 (goto-char (org-element-property :contents-begin context))
20406 (org-call-with-arg 'org-table-recalculate (or arg t))
20407 (orgtbl-send-table 'maybe)))
20408 (org-table-maybe-eval-formula)
20409 (cond (arg (call-interactively 'org-table-recalculate))
20410 ((org-table-maybe-recalculate-line))
20411 (t (org-table-align)))))))
20412 (timestamp (org-timestamp-change 0 'day))
20413 (otherwise
20414 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20415 (user-error
20416 "C-c C-c can do nothing useful at this location")))))))))
20418 (defun org-mode-restart ()
20419 (interactive)
20420 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20421 (funcall major-mode)
20422 (hack-local-variables)
20423 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20424 (org-indent-mode -1)))
20425 (message "%s restarted" major-mode))
20427 (defun org-kill-note-or-show-branches ()
20428 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20429 (interactive)
20430 (if (not org-finish-function)
20431 (progn
20432 (hide-subtree)
20433 (call-interactively 'show-branches))
20434 (let ((org-note-abort t))
20435 (funcall org-finish-function))))
20437 (defun org-open-line (n)
20438 "Insert a new row in tables, call `open-line' elsewhere.
20439 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20440 (interactive "*p")
20441 (cond
20442 ((not org-special-ctrl-o)
20443 (open-line n))
20444 ((org-at-table-p)
20445 (org-table-insert-row))
20447 (open-line n))))
20449 (defun org-return (&optional indent)
20450 "Goto next table row or insert a newline.
20451 Calls `org-table-next-row' or `newline', depending on context.
20452 See the individual commands for more information."
20453 (interactive)
20454 (let (org-ts-what)
20455 (cond
20456 ((or (bobp) (org-in-src-block-p))
20457 (if indent (newline-and-indent) (newline)))
20458 ((org-at-table-p)
20459 (org-table-justify-field-maybe)
20460 (call-interactively 'org-table-next-row))
20461 ;; when `newline-and-indent' is called within a list, make sure
20462 ;; text moved stays inside the item.
20463 ((and (org-in-item-p) indent)
20464 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20465 (progn
20466 (save-match-data (newline))
20467 (org-indent-line-to (length (match-string 0))))
20468 (let ((ind (org-get-indentation)))
20469 (newline)
20470 (if (org-looking-back org-list-end-re)
20471 (org-indent-line)
20472 (org-indent-line-to ind)))))
20473 ((and org-return-follows-link
20474 (org-at-timestamp-p t)
20475 (not (eq org-ts-what 'after)))
20476 (org-follow-timestamp-link))
20477 ((and org-return-follows-link
20478 (let ((tprop (get-text-property (point) 'face)))
20479 (or (eq tprop 'org-link)
20480 (and (listp tprop) (memq 'org-link tprop)))))
20481 (call-interactively 'org-open-at-point))
20482 ((and (org-at-heading-p)
20483 (looking-at
20484 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20485 (org-show-entry)
20486 (end-of-line 1)
20487 (newline))
20488 (t (if indent (newline-and-indent) (newline))))))
20490 (defun org-return-indent ()
20491 "Goto next table row or insert a newline and indent.
20492 Calls `org-table-next-row' or `newline-and-indent', depending on
20493 context. See the individual commands for more information."
20494 (interactive)
20495 (org-return t))
20497 (defun org-ctrl-c-star ()
20498 "Compute table, or change heading status of lines.
20499 Calls `org-table-recalculate' or `org-toggle-heading',
20500 depending on context."
20501 (interactive)
20502 (cond
20503 ((org-at-table-p)
20504 (call-interactively 'org-table-recalculate))
20506 ;; Convert all lines in region to list items
20507 (call-interactively 'org-toggle-heading))))
20509 (defun org-ctrl-c-minus ()
20510 "Insert separator line in table or modify bullet status of line.
20511 Also turns a plain line or a region of lines into list items.
20512 Calls `org-table-insert-hline', `org-toggle-item', or
20513 `org-cycle-list-bullet', depending on context."
20514 (interactive)
20515 (cond
20516 ((org-at-table-p)
20517 (call-interactively 'org-table-insert-hline))
20518 ((org-region-active-p)
20519 (call-interactively 'org-toggle-item))
20520 ((org-in-item-p)
20521 (call-interactively 'org-cycle-list-bullet))
20523 (call-interactively 'org-toggle-item))))
20525 (defun org-toggle-item (arg)
20526 "Convert headings or normal lines to items, items to normal lines.
20527 If there is no active region, only the current line is considered.
20529 If the first non blank line in the region is a headline, convert
20530 all headlines to items, shifting text accordingly.
20532 If it is an item, convert all items to normal lines.
20534 If it is normal text, change region into a list of items.
20535 With a prefix argument ARG, change the region in a single item."
20536 (interactive "P")
20537 (let ((shift-text
20538 (function
20539 ;; Shift text in current section to IND, from point to END.
20540 ;; The function leaves point to END line.
20541 (lambda (ind end)
20542 (let ((min-i 1000) (end (copy-marker end)))
20543 ;; First determine the minimum indentation (MIN-I) of
20544 ;; the text.
20545 (save-excursion
20546 (catch 'exit
20547 (while (< (point) end)
20548 (let ((i (org-get-indentation)))
20549 (cond
20550 ;; Skip blank lines and inline tasks.
20551 ((looking-at "^[ \t]*$"))
20552 ((looking-at org-outline-regexp-bol))
20553 ;; We can't find less than 0 indentation.
20554 ((zerop i) (throw 'exit (setq min-i 0)))
20555 ((< i min-i) (setq min-i i))))
20556 (forward-line))))
20557 ;; Then indent each line so that a line indented to
20558 ;; MIN-I becomes indented to IND. Ignore blank lines
20559 ;; and inline tasks in the process.
20560 (let ((delta (- ind min-i)))
20561 (while (< (point) end)
20562 (unless (or (looking-at "^[ \t]*$")
20563 (looking-at org-outline-regexp-bol))
20564 (org-indent-line-to (+ (org-get-indentation) delta)))
20565 (forward-line)))))))
20566 (skip-blanks
20567 (function
20568 ;; Return beginning of first non-blank line, starting from
20569 ;; line at POS.
20570 (lambda (pos)
20571 (save-excursion
20572 (goto-char pos)
20573 (skip-chars-forward " \r\t\n")
20574 (point-at-bol)))))
20575 beg end)
20576 ;; Determine boundaries of changes.
20577 (if (org-region-active-p)
20578 (setq beg (funcall skip-blanks (region-beginning))
20579 end (copy-marker (region-end)))
20580 (setq beg (funcall skip-blanks (point-at-bol))
20581 end (copy-marker (point-at-eol))))
20582 ;; Depending on the starting line, choose an action on the text
20583 ;; between BEG and END.
20584 (org-with-limited-levels
20585 (save-excursion
20586 (goto-char beg)
20587 (cond
20588 ;; Case 1. Start at an item: de-itemize. Note that it only
20589 ;; happens when a region is active: `org-ctrl-c-minus'
20590 ;; would call `org-cycle-list-bullet' otherwise.
20591 ((org-at-item-p)
20592 (while (< (point) end)
20593 (when (org-at-item-p)
20594 (skip-chars-forward " \t")
20595 (delete-region (point) (match-end 0)))
20596 (forward-line)))
20597 ;; Case 2. Start at an heading: convert to items.
20598 ((org-at-heading-p)
20599 (let* ((bul (org-list-bullet-string "-"))
20600 (bul-len (length bul))
20601 ;; Indentation of the first heading. It should be
20602 ;; relative to the indentation of its parent, if any.
20603 (start-ind (save-excursion
20604 (cond
20605 ((not org-adapt-indentation) 0)
20606 ((not (outline-previous-heading)) 0)
20607 (t (length (match-string 0))))))
20608 ;; Level of first heading. Further headings will be
20609 ;; compared to it to determine hierarchy in the list.
20610 (ref-level (org-reduced-level (org-outline-level))))
20611 (while (< (point) end)
20612 (let* ((level (org-reduced-level (org-outline-level)))
20613 (delta (max 0 (- level ref-level))))
20614 ;; If current headline is less indented than the first
20615 ;; one, set it as reference, in order to preserve
20616 ;; subtrees.
20617 (when (< level ref-level) (setq ref-level level))
20618 (replace-match bul t t)
20619 (org-indent-line-to (+ start-ind (* delta bul-len)))
20620 ;; Ensure all text down to END (or SECTION-END) belongs
20621 ;; to the newly created item.
20622 (let ((section-end (save-excursion
20623 (or (outline-next-heading) (point)))))
20624 (forward-line)
20625 (funcall shift-text
20626 (+ start-ind (* (1+ delta) bul-len))
20627 (min end section-end)))))))
20628 ;; Case 3. Normal line with ARG: make the first line of region
20629 ;; an item, and shift indentation of others lines to
20630 ;; set them as item's body.
20631 (arg (let* ((bul (org-list-bullet-string "-"))
20632 (bul-len (length bul))
20633 (ref-ind (org-get-indentation)))
20634 (skip-chars-forward " \t")
20635 (insert bul)
20636 (forward-line)
20637 (while (< (point) end)
20638 ;; Ensure that lines less indented than first one
20639 ;; still get included in item body.
20640 (funcall shift-text
20641 (+ ref-ind bul-len)
20642 (min end (save-excursion (or (outline-next-heading)
20643 (point)))))
20644 (forward-line))))
20645 ;; Case 4. Normal line without ARG: turn each non-item line
20646 ;; into an item.
20648 (while (< (point) end)
20649 (unless (or (org-at-heading-p) (org-at-item-p))
20650 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20651 (replace-match
20652 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20653 (forward-line))))))))
20655 (defun org-toggle-heading (&optional nstars)
20656 "Convert headings to normal text, or items or text to headings.
20657 If there is no active region, only convert the current line.
20659 With a \\[universal-argument] prefix, convert the whole list at
20660 point into heading.
20662 In a region:
20664 - If the first non blank line is a headline, remove the stars
20665 from all headlines in the region.
20667 - If it is a normal line, turn each and every normal line (i.e.,
20668 not an heading or an item) in the region into headings. If you
20669 want to convert only the first line of this region, use one
20670 universal prefix argument.
20672 - If it is a plain list item, turn all plain list items into headings.
20674 When converting a line into a heading, the number of stars is chosen
20675 such that the lines become children of the current entry. However,
20676 when a numeric prefix argument is given, its value determines the
20677 number of stars to add."
20678 (interactive "P")
20679 (let ((skip-blanks
20680 (function
20681 ;; Return beginning of first non-blank line, starting from
20682 ;; line at POS.
20683 (lambda (pos)
20684 (save-excursion
20685 (goto-char pos)
20686 (while (org-at-comment-p) (forward-line))
20687 (skip-chars-forward " \r\t\n")
20688 (point-at-bol)))))
20689 beg end toggled)
20690 ;; Determine boundaries of changes. If a universal prefix has
20691 ;; been given, put the list in a region. If region ends at a bol,
20692 ;; do not consider the last line to be in the region.
20694 (when (and current-prefix-arg (org-at-item-p))
20695 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20696 (org-mark-element))
20698 (if (org-region-active-p)
20699 (setq beg (funcall skip-blanks (region-beginning))
20700 end (copy-marker (save-excursion
20701 (goto-char (region-end))
20702 (if (bolp) (point) (point-at-eol)))))
20703 (setq beg (funcall skip-blanks (point-at-bol))
20704 end (copy-marker (point-at-eol))))
20705 ;; Ensure inline tasks don't count as headings.
20706 (org-with-limited-levels
20707 (save-excursion
20708 (goto-char beg)
20709 (cond
20710 ;; Case 1. Started at an heading: de-star headings.
20711 ((org-at-heading-p)
20712 (while (< (point) end)
20713 (when (org-at-heading-p t)
20714 (looking-at org-outline-regexp) (replace-match "")
20715 (setq toggled t))
20716 (forward-line)))
20717 ;; Case 2. Started at an item: change items into headlines.
20718 ;; One star will be added by `org-list-to-subtree'.
20719 ((org-at-item-p)
20720 (let* ((stars (make-string
20721 ;; subtract the star that will be added again by
20722 ;; `org-list-to-subtree'
20723 (if (numberp nstars) (1- nstars)
20724 (or (org-current-level) 0))
20725 ?*))
20726 (add-stars
20727 (cond (nstars "") ; stars from prefix only
20728 ((equal stars "") "") ; before first heading
20729 (org-odd-levels-only "*") ; inside heading, odd
20730 (t "")))) ; inside heading, oddeven
20731 (while (< (point) end)
20732 (when (org-at-item-p)
20733 ;; Pay attention to cases when region ends before list.
20734 (let* ((struct (org-list-struct))
20735 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20736 (save-restriction
20737 (narrow-to-region (point) list-end)
20738 (insert
20739 (org-list-to-subtree
20740 (org-list-parse-list t)
20741 '(:istart (concat stars add-stars (funcall get-stars depth))
20742 :icount (concat stars add-stars (funcall get-stars depth)))))))
20743 (setq toggled t))
20744 (forward-line))))
20745 ;; Case 3. Started at normal text: make every line an heading,
20746 ;; skipping headlines and items.
20747 (t (let* ((stars
20748 (make-string
20749 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20750 (add-stars
20751 (cond (nstars "") ; stars from prefix only
20752 ((equal stars "") "*") ; before first heading
20753 (org-odd-levels-only "**") ; inside heading, odd
20754 (t "*"))) ; inside heading, oddeven
20755 (rpl (concat stars add-stars " "))
20756 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20757 (while (< (point) (if (equal nstars '(4)) lend end))
20758 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20759 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20760 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20761 (forward-line)))))))
20762 (unless toggled (message "Cannot toggle heading from here"))))
20764 (defun org-meta-return (&optional arg)
20765 "Insert a new heading or wrap a region in a table.
20766 Calls `org-insert-heading' or `org-table-wrap-region', depending
20767 on context. See the individual commands for more information."
20768 (interactive "P")
20769 (org-check-before-invisible-edit 'insert)
20770 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20771 (let* ((element (org-element-at-point))
20772 (type (org-element-type element)))
20773 (when (eq type 'table-row)
20774 (setq element (org-element-property :parent element))
20775 (setq type 'table))
20776 (if (and (eq type 'table)
20777 (eq (org-element-property :type element) 'org)
20778 (>= (point) (org-element-property :contents-begin element))
20779 (< (point) (org-element-property :contents-end element)))
20780 (call-interactively 'org-table-wrap-region)
20781 (call-interactively 'org-insert-heading)))))
20783 ;;; Menu entries
20785 (defsubst org-in-subtree-not-table-p ()
20786 "Are we in a subtree and not in a table?"
20787 (and (not (org-before-first-heading-p))
20788 (not (org-at-table-p))))
20790 ;; Define the Org-mode menus
20791 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20792 '("Tbl"
20793 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20794 ["Next Field" org-cycle (org-at-table-p)]
20795 ["Previous Field" org-shifttab (org-at-table-p)]
20796 ["Next Row" org-return (org-at-table-p)]
20797 "--"
20798 ["Blank Field" org-table-blank-field (org-at-table-p)]
20799 ["Edit Field" org-table-edit-field (org-at-table-p)]
20800 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20801 "--"
20802 ("Column"
20803 ["Move Column Left" org-metaleft (org-at-table-p)]
20804 ["Move Column Right" org-metaright (org-at-table-p)]
20805 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20806 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20807 ("Row"
20808 ["Move Row Up" org-metaup (org-at-table-p)]
20809 ["Move Row Down" org-metadown (org-at-table-p)]
20810 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20811 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20812 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20813 "--"
20814 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20815 ("Rectangle"
20816 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20817 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20818 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20819 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20820 "--"
20821 ("Calculate"
20822 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20823 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20824 ["Edit Formulas" org-edit-special (org-at-table-p)]
20825 "--"
20826 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20827 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20828 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20829 "--"
20830 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20831 "--"
20832 ["Sum Column/Rectangle" org-table-sum
20833 (or (org-at-table-p) (org-region-active-p))]
20834 ["Which Column?" org-table-current-column (org-at-table-p)])
20835 ["Debug Formulas"
20836 org-table-toggle-formula-debugger
20837 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20838 ["Show Col/Row Numbers"
20839 org-table-toggle-coordinate-overlays
20840 :style toggle
20841 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20842 "--"
20843 ["Create" org-table-create (and (not (org-at-table-p))
20844 org-enable-table-editor)]
20845 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20846 ["Import from File" org-table-import (not (org-at-table-p))]
20847 ["Export to File" org-table-export (org-at-table-p)]
20848 "--"
20849 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20851 (easy-menu-define org-org-menu org-mode-map "Org menu"
20852 '("Org"
20853 ("Show/Hide"
20854 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20855 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20856 ["Sparse Tree..." org-sparse-tree t]
20857 ["Reveal Context" org-reveal t]
20858 ["Show All" show-all t]
20859 "--"
20860 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20861 "--"
20862 ["New Heading" org-insert-heading t]
20863 ("Navigate Headings"
20864 ["Up" outline-up-heading t]
20865 ["Next" outline-next-visible-heading t]
20866 ["Previous" outline-previous-visible-heading t]
20867 ["Next Same Level" outline-forward-same-level t]
20868 ["Previous Same Level" outline-backward-same-level t]
20869 "--"
20870 ["Jump" org-goto t])
20871 ("Edit Structure"
20872 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20873 "--"
20874 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20875 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20876 "--"
20877 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20878 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20879 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20880 "--"
20881 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20882 "--"
20883 ["Copy visible text" org-copy-visible t]
20884 "--"
20885 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20886 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20887 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20888 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20889 "--"
20890 ["Sort Region/Children" org-sort t]
20891 "--"
20892 ["Convert to odd levels" org-convert-to-odd-levels t]
20893 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20894 ("Editing"
20895 ["Emphasis..." org-emphasize t]
20896 ["Edit Source Example" org-edit-special t]
20897 "--"
20898 ["Footnote new/jump" org-footnote-action t]
20899 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20900 ("Archive"
20901 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20902 "--"
20903 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20904 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20905 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20907 "--"
20908 ("Hyperlinks"
20909 ["Store Link (Global)" org-store-link t]
20910 ["Find existing link to here" org-occur-link-in-agenda-files t]
20911 ["Insert Link" org-insert-link t]
20912 ["Follow Link" org-open-at-point t]
20913 "--"
20914 ["Next link" org-next-link t]
20915 ["Previous link" org-previous-link t]
20916 "--"
20917 ["Descriptive Links"
20918 org-toggle-link-display
20919 :style radio
20920 :selected org-descriptive-links
20922 ["Literal Links"
20923 org-toggle-link-display
20924 :style radio
20925 :selected (not org-descriptive-links)])
20926 "--"
20927 ("TODO Lists"
20928 ["TODO/DONE/-" org-todo t]
20929 ("Select keyword"
20930 ["Next keyword" org-shiftright (org-at-heading-p)]
20931 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20932 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20933 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20934 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20935 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20936 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20937 "--"
20938 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20939 :selected org-enforce-todo-dependencies :style toggle :active t]
20940 "Settings for tree at point"
20941 ["Do Children sequentially" org-toggle-ordered-property :style radio
20942 :selected (org-entry-get nil "ORDERED")
20943 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20944 ["Do Children parallel" org-toggle-ordered-property :style radio
20945 :selected (not (org-entry-get nil "ORDERED"))
20946 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20947 "--"
20948 ["Set Priority" org-priority t]
20949 ["Priority Up" org-shiftup t]
20950 ["Priority Down" org-shiftdown t]
20951 "--"
20952 ["Get news from all feeds" org-feed-update-all t]
20953 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20954 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20955 ("TAGS and Properties"
20956 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20957 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20958 "--"
20959 ["Set property" org-set-property (not (org-before-first-heading-p))]
20960 ["Column view of properties" org-columns t]
20961 ["Insert Column View DBlock" org-insert-columns-dblock t])
20962 ("Dates and Scheduling"
20963 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20964 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20965 ("Change Date"
20966 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20967 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20968 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20969 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20970 ["Compute Time Range" org-evaluate-time-range t]
20971 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20972 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20973 "--"
20974 ["Custom time format" org-toggle-time-stamp-overlays
20975 :style radio :selected org-display-custom-times]
20976 "--"
20977 ["Goto Calendar" org-goto-calendar t]
20978 ["Date from Calendar" org-date-from-calendar t]
20979 "--"
20980 ["Start/Restart Timer" org-timer-start t]
20981 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20982 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20983 ["Insert Timer String" org-timer t]
20984 ["Insert Timer Item" org-timer-item t])
20985 ("Logging work"
20986 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20987 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20988 ["Clock out" org-clock-out t]
20989 ["Clock cancel" org-clock-cancel t]
20990 "--"
20991 ["Mark as default task" org-clock-mark-default-task t]
20992 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20993 ["Goto running clock" org-clock-goto t]
20994 "--"
20995 ["Display times" org-clock-display t]
20996 ["Create clock table" org-clock-report t]
20997 "--"
20998 ["Record DONE time"
20999 (progn (setq org-log-done (not org-log-done))
21000 (message "Switching to %s will %s record a timestamp"
21001 (car org-done-keywords)
21002 (if org-log-done "automatically" "not")))
21003 :style toggle :selected org-log-done])
21004 "--"
21005 ["Agenda Command..." org-agenda t]
21006 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21007 ("File List for Agenda")
21008 ("Special views current file"
21009 ["TODO Tree" org-show-todo-tree t]
21010 ["Check Deadlines" org-check-deadlines t]
21011 ["Timeline" org-timeline t]
21012 ["Tags/Property tree" org-match-sparse-tree t])
21013 "--"
21014 ["Export/Publish..." org-export-dispatch t]
21015 ("LaTeX"
21016 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21017 :selected org-cdlatex-mode]
21018 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21019 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21020 ["Modify math symbol" org-cdlatex-math-modify
21021 (org-inside-LaTeX-fragment-p)]
21022 ["Insert citation" org-reftex-citation t]
21023 "--"
21024 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21025 "--"
21026 ("MobileOrg"
21027 ["Push Files and Views" org-mobile-push t]
21028 ["Get Captured and Flagged" org-mobile-pull t]
21029 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21030 "--"
21031 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21032 "--"
21033 ("Documentation"
21034 ["Show Version" org-version t]
21035 ["Info Documentation" org-info t])
21036 ("Customize"
21037 ["Browse Org Group" org-customize t]
21038 "--"
21039 ["Expand This Menu" org-create-customize-menu
21040 (fboundp 'customize-menu-create)])
21041 ["Send bug report" org-submit-bug-report t]
21042 "--"
21043 ("Refresh/Reload"
21044 ["Refresh setup current buffer" org-mode-restart t]
21045 ["Reload Org (after update)" org-reload t]
21046 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21049 (defun org-info (&optional node)
21050 "Read documentation for Org-mode in the info system.
21051 With optional NODE, go directly to that node."
21052 (interactive)
21053 (info (format "(org)%s" (or node ""))))
21055 ;;;###autoload
21056 (defun org-submit-bug-report ()
21057 "Submit a bug report on Org-mode via mail.
21059 Don't hesitate to report any problems or inaccurate documentation.
21061 If you don't have setup sending mail from (X)Emacs, please copy the
21062 output buffer into your mail program, as it gives us important
21063 information about your Org-mode version and configuration."
21064 (interactive)
21065 (require 'reporter)
21066 (org-load-modules-maybe)
21067 (org-require-autoloaded-modules)
21068 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21069 (reporter-submit-bug-report
21070 "emacs-orgmode@gnu.org"
21071 (org-version nil 'full)
21072 (let (list)
21073 (save-window-excursion
21074 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21075 (delete-other-windows)
21076 (erase-buffer)
21077 (insert "You are about to submit a bug report to the Org-mode mailing list.
21079 We would like to add your full Org-mode and Outline configuration to the
21080 bug report. This greatly simplifies the work of the maintainer and
21081 other experts on the mailing list.
21083 HOWEVER, some variables you have customized may contain private
21084 information. The names of customers, colleagues, or friends, might
21085 appear in the form of file names, tags, todo states, or search strings.
21086 If you answer yes to the prompt, you might want to check and remove
21087 such private information before sending the email.")
21088 (add-text-properties (point-min) (point-max) '(face org-warning))
21089 (when (yes-or-no-p "Include your Org-mode configuration ")
21090 (mapatoms
21091 (lambda (v)
21092 (and (boundp v)
21093 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21094 (or (and (symbol-value v)
21095 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21096 (and
21097 (get v 'custom-type) (get v 'standard-value)
21098 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21099 (push v list)))))
21100 (kill-buffer (get-buffer "*Warn about privacy*"))
21101 list))
21102 nil nil
21103 "Remember to cover the basics, that is, what you expected to happen and
21104 what in fact did happen. You don't know how to make a good report? See
21106 http://orgmode.org/manual/Feedback.html#Feedback
21108 Your bug report will be posted to the Org-mode mailing list.
21109 ------------------------------------------------------------------------")
21110 (save-excursion
21111 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21112 (replace-match "\\1Bug: \\3 [\\2]")))))
21115 (defun org-install-agenda-files-menu ()
21116 (let ((bl (buffer-list)))
21117 (save-excursion
21118 (while bl
21119 (set-buffer (pop bl))
21120 (if (derived-mode-p 'org-mode) (setq bl nil)))
21121 (when (derived-mode-p 'org-mode)
21122 (easy-menu-change
21123 '("Org") "File List for Agenda"
21124 (append
21125 (list
21126 ["Edit File List" (org-edit-agenda-file-list) t]
21127 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21128 ["Remove Current File from List" org-remove-file t]
21129 ["Cycle through agenda files" org-cycle-agenda-files t]
21130 ["Occur in all agenda files" org-occur-in-agenda-files t]
21131 "--")
21132 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21134 ;;;; Documentation
21136 (defun org-require-autoloaded-modules ()
21137 (interactive)
21138 (mapc 'require
21139 '(org-agenda org-archive org-attach org-clock org-colview org-id
21140 org-table org-timer)))
21142 ;;;###autoload
21143 (defun org-reload (&optional uncompiled)
21144 "Reload all org lisp files.
21145 With prefix arg UNCOMPILED, load the uncompiled versions."
21146 (interactive "P")
21147 (require 'loadhist)
21148 (let* ((org-dir (org-find-library-dir "org"))
21149 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21150 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21151 (remove-re (mapconcat 'identity
21152 (mapcar (lambda (f) (concat "^" f "$"))
21153 (list (if (featurep 'xemacs)
21154 "org-colview"
21155 "org-colview-xemacs")
21156 "org" "org-loaddefs" "org-version"))
21157 "\\|"))
21158 (feats (delete-dups
21159 (mapcar 'file-name-sans-extension
21160 (mapcar 'file-name-nondirectory
21161 (delq nil
21162 (mapcar 'feature-file
21163 features))))))
21164 (lfeat (append
21165 (sort
21166 (setq feats
21167 (delq nil (mapcar
21168 (lambda (f)
21169 (if (and (string-match feature-re f)
21170 (not (string-match remove-re f)))
21171 f nil))
21172 feats)))
21173 'string-lessp)
21174 (list "org-version" "org")))
21175 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21176 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21177 load-uncore load-misses)
21178 (setq load-misses
21179 (delq 't
21180 (mapcar (lambda (f)
21181 (or (org-load-noerror-mustsuffix (concat org-dir f))
21182 (and (string= org-dir contrib-dir)
21183 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21184 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21185 (add-to-list 'load-uncore f 'append)
21188 lfeat)))
21189 (if load-uncore
21190 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21191 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21192 (if load-misses
21193 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21194 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21195 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21197 ;;;###autoload
21198 (defun org-customize ()
21199 "Call the customize function with org as argument."
21200 (interactive)
21201 (org-load-modules-maybe)
21202 (org-require-autoloaded-modules)
21203 (customize-browse 'org))
21205 (defun org-create-customize-menu ()
21206 "Create a full customization menu for Org-mode, insert it into the menu."
21207 (interactive)
21208 (org-load-modules-maybe)
21209 (org-require-autoloaded-modules)
21210 (if (fboundp 'customize-menu-create)
21211 (progn
21212 (easy-menu-change
21213 '("Org") "Customize"
21214 `(["Browse Org group" org-customize t]
21215 "--"
21216 ,(customize-menu-create 'org)
21217 ["Set" Custom-set t]
21218 ["Save" Custom-save t]
21219 ["Reset to Current" Custom-reset-current t]
21220 ["Reset to Saved" Custom-reset-saved t]
21221 ["Reset to Standard Settings" Custom-reset-standard t]))
21222 (message "\"Org\"-menu now contains full customization menu"))
21223 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21225 ;;;; Miscellaneous stuff
21227 ;;; Generally useful functions
21229 (defun org-get-at-bol (property)
21230 "Get text property PROPERTY at beginning of line."
21231 (get-text-property (point-at-bol) property))
21233 (defun org-find-text-property-in-string (prop s)
21234 "Return the first non-nil value of property PROP in string S."
21235 (or (get-text-property 0 prop s)
21236 (get-text-property (or (next-single-property-change 0 prop s) 0)
21237 prop s)))
21239 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21240 "Display the given MESSAGE as a warning."
21241 (if (fboundp 'display-warning)
21242 (display-warning 'org message
21243 (if (featurep 'xemacs) 'warning :warning))
21244 (let ((buf (get-buffer-create "*Org warnings*")))
21245 (with-current-buffer buf
21246 (goto-char (point-max))
21247 (insert "Warning (Org): " message)
21248 (unless (bolp)
21249 (newline)))
21250 (display-buffer buf)
21251 (sit-for 0))))
21253 (defun org-eval (form)
21254 "Eval FORM and return result."
21255 (condition-case error
21256 (eval form)
21257 (error (format "%%![Error: %s]" error))))
21259 (defun org-in-clocktable-p ()
21260 "Check if the cursor is in a clocktable."
21261 (let ((pos (point)) start)
21262 (save-excursion
21263 (end-of-line 1)
21264 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21265 (setq start (match-beginning 0))
21266 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21267 (>= (match-end 0) pos)
21268 start))))
21270 (defun org-in-commented-line ()
21271 "Is point in a line starting with `#'?"
21272 (equal (char-after (point-at-bol)) ?#))
21274 (defun org-in-indented-comment-line ()
21275 "Is point in a line starting with `#' after some white space?"
21276 (save-excursion
21277 (save-match-data
21278 (goto-char (point-at-bol))
21279 (looking-at "[ \t]*#"))))
21281 (defun org-in-verbatim-emphasis ()
21282 (save-match-data
21283 (and (org-in-regexp org-emph-re 2)
21284 (>= (point) (match-beginning 3))
21285 (<= (point) (match-end 4))
21286 (member (match-string 3) '("=" "~")))))
21288 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21289 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21290 (if (and marker (marker-buffer marker)
21291 (buffer-live-p (marker-buffer marker)))
21292 (progn
21293 (org-pop-to-buffer-same-window (marker-buffer marker))
21294 (if (or (> marker (point-max)) (< marker (point-min)))
21295 (widen))
21296 (goto-char marker)
21297 (org-show-context 'org-goto))
21298 (if bookmark
21299 (bookmark-jump bookmark)
21300 (error "Cannot find location"))))
21302 (defun org-quote-csv-field (s)
21303 "Quote field for inclusion in CSV material."
21304 (if (string-match "[\",]" s)
21305 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21308 (defun org-force-self-insert (N)
21309 "Needed to enforce self-insert under remapping."
21310 (interactive "p")
21311 (self-insert-command N))
21313 (defun org-string-width (s)
21314 "Compute width of string, ignoring invisible characters.
21315 This ignores character with invisibility property `org-link', and also
21316 characters with property `org-cwidth', because these will become invisible
21317 upon the next fontification round."
21318 (let (b l)
21319 (when (or (eq t buffer-invisibility-spec)
21320 (assq 'org-link buffer-invisibility-spec))
21321 (while (setq b (text-property-any 0 (length s)
21322 'invisible 'org-link s))
21323 (setq s (concat (substring s 0 b)
21324 (substring s (or (next-single-property-change
21325 b 'invisible s) (length s)))))))
21326 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21327 (setq s (concat (substring s 0 b)
21328 (substring s (or (next-single-property-change
21329 b 'org-cwidth s) (length s))))))
21330 (setq l (string-width s) b -1)
21331 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21332 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21335 (defun org-shorten-string (s maxlength)
21336 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21337 If the string is shorter or has length MAXLENGTH, just return the
21338 original string. If it is longer, the functions finds a space in the
21339 string, breaks this string off at that locations and adds three dots
21340 as ellipsis. Including the ellipsis, the string will not be longer
21341 than MAXLENGTH. If finding a good breaking point in the string does
21342 not work, the string is just chopped off in the middle of a word
21343 if necessary."
21344 (if (<= (length s) maxlength)
21346 (let* ((n (max (- maxlength 4) 1))
21347 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21348 (if (string-match re s)
21349 (concat (match-string 1 s) "...")
21350 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21352 (defun org-get-indentation (&optional line)
21353 "Get the indentation of the current line, interpreting tabs.
21354 When LINE is given, assume it represents a line and compute its indentation."
21355 (if line
21356 (if (string-match "^ *" (org-remove-tabs line))
21357 (match-end 0))
21358 (save-excursion
21359 (beginning-of-line 1)
21360 (skip-chars-forward " \t")
21361 (current-column))))
21363 (defun org-get-string-indentation (s)
21364 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21365 (let ((n -1) (i 0) (w tab-width) c)
21366 (catch 'exit
21367 (while (< (setq n (1+ n)) (length s))
21368 (setq c (aref s n))
21369 (cond ((= c ?\ ) (setq i (1+ i)))
21370 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21371 (t (throw 'exit t)))))
21374 (defun org-remove-tabs (s &optional width)
21375 "Replace tabulators in S with spaces.
21376 Assumes that s is a single line, starting in column 0."
21377 (setq width (or width tab-width))
21378 (while (string-match "\t" s)
21379 (setq s (replace-match
21380 (make-string
21381 (- (* width (/ (+ (match-beginning 0) width) width))
21382 (match-beginning 0)) ?\ )
21383 t t s)))
21386 (defun org-fix-indentation (line ind)
21387 "Fix indentation in LINE.
21388 IND is a cons cell with target and minimum indentation.
21389 If the current indentation in LINE is smaller than the minimum,
21390 leave it alone. If it is larger than ind, set it to the target."
21391 (let* ((l (org-remove-tabs line))
21392 (i (org-get-indentation l))
21393 (i1 (car ind)) (i2 (cdr ind)))
21394 (if (>= i i2) (setq l (substring line i2)))
21395 (if (> i1 0)
21396 (concat (make-string i1 ?\ ) l)
21397 l)))
21399 (defun org-remove-indentation (code &optional n)
21400 "Remove the maximum common indentation from the lines in CODE.
21401 N may optionally be the number of spaces to remove."
21402 (with-temp-buffer
21403 (insert code)
21404 (org-do-remove-indentation n)
21405 (buffer-string)))
21407 (defun org-do-remove-indentation (&optional n)
21408 "Remove the maximum common indentation from the buffer."
21409 (untabify (point-min) (point-max))
21410 (let ((min 10000) re)
21411 (if n
21412 (setq min n)
21413 (goto-char (point-min))
21414 (while (re-search-forward "^ *[^ \n]" nil t)
21415 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21416 (unless (or (= min 0) (= min 10000))
21417 (setq re (format "^ \\{%d\\}" min))
21418 (goto-char (point-min))
21419 (while (re-search-forward re nil t)
21420 (replace-match "")
21421 (end-of-line 1))
21422 min)))
21424 (defun org-fill-template (template alist)
21425 "Find each %key of ALIST in TEMPLATE and replace it."
21426 (let ((case-fold-search nil)
21427 entry key value)
21428 (setq alist (sort (copy-sequence alist)
21429 (lambda (a b) (< (length (car a)) (length (car b))))))
21430 (while (setq entry (pop alist))
21431 (setq template
21432 (replace-regexp-in-string
21433 (concat "%" (regexp-quote (car entry)))
21434 (or (cdr entry) "") template t t)))
21435 template))
21437 (defun org-base-buffer (buffer)
21438 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21439 (if (not buffer)
21440 buffer
21441 (or (buffer-base-buffer buffer)
21442 buffer)))
21444 (defun org-trim (s)
21445 "Remove whitespace at beginning and end of string."
21446 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21447 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21450 (defun org-wrap (string &optional width lines)
21451 "Wrap string to either a number of lines, or a width in characters.
21452 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21453 that costs. If there is a word longer than WIDTH, the text is actually
21454 wrapped to the length of that word.
21455 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21456 many lines, whatever width that takes.
21457 The return value is a list of lines, without newlines at the end."
21458 (let* ((words (org-split-string string "[ \t\n]+"))
21459 (maxword (apply 'max (mapcar 'org-string-width words)))
21460 w ll)
21461 (cond (width
21462 (org-do-wrap words (max maxword width)))
21463 (lines
21464 (setq w maxword)
21465 (setq ll (org-do-wrap words maxword))
21466 (if (<= (length ll) lines)
21468 (setq ll words)
21469 (while (> (length ll) lines)
21470 (setq w (1+ w))
21471 (setq ll (org-do-wrap words w)))
21472 ll))
21473 (t (error "Cannot wrap this")))))
21475 (defun org-do-wrap (words width)
21476 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21477 (let (lines line)
21478 (while words
21479 (setq line (pop words))
21480 (while (and words (< (+ (length line) (length (car words))) width))
21481 (setq line (concat line " " (pop words))))
21482 (setq lines (push line lines)))
21483 (nreverse lines)))
21485 (defun org-split-string (string &optional separators)
21486 "Splits STRING into substrings at SEPARATORS.
21487 No empty strings are returned if there are matches at the beginning
21488 and end of string."
21489 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21490 (start 0)
21491 notfirst
21492 (list nil))
21493 (while (and (string-match rexp string
21494 (if (and notfirst
21495 (= start (match-beginning 0))
21496 (< start (length string)))
21497 (1+ start) start))
21498 (< (match-beginning 0) (length string)))
21499 (setq notfirst t)
21500 (or (eq (match-beginning 0) 0)
21501 (and (eq (match-beginning 0) (match-end 0))
21502 (eq (match-beginning 0) start))
21503 (setq list
21504 (cons (substring string start (match-beginning 0))
21505 list)))
21506 (setq start (match-end 0)))
21507 (or (eq start (length string))
21508 (setq list
21509 (cons (substring string start)
21510 list)))
21511 (nreverse list)))
21513 (defun org-quote-vert (s)
21514 "Replace \"|\" with \"\\vert\"."
21515 (while (string-match "|" s)
21516 (setq s (replace-match "\\vert" t t s)))
21519 (defun org-uuidgen-p (s)
21520 "Is S an ID created by UUIDGEN?"
21521 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21523 (defun org-in-src-block-p (&optional inside)
21524 "Whether point is in a code source block.
21525 When INSIDE is non-nil, don't consider we are within a src block
21526 when point is at #+BEGIN_SRC or #+END_SRC."
21527 (let ((case-fold-search t) ov)
21528 (or (and (setq ov (overlays-at (point)))
21529 (memq 'org-block-background
21530 (overlay-properties (car ov))))
21531 (and (not inside)
21532 (save-match-data
21533 (save-excursion
21534 (beginning-of-line)
21535 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21537 (defun org-context ()
21538 "Return a list of contexts of the current cursor position.
21539 If several contexts apply, all are returned.
21540 Each context entry is a list with a symbol naming the context, and
21541 two positions indicating start and end of the context. Possible
21542 contexts are:
21544 :headline anywhere in a headline
21545 :headline-stars on the leading stars in a headline
21546 :todo-keyword on a TODO keyword (including DONE) in a headline
21547 :tags on the TAGS in a headline
21548 :priority on the priority cookie in a headline
21549 :item on the first line of a plain list item
21550 :item-bullet on the bullet/number of a plain list item
21551 :checkbox on the checkbox in a plain list item
21552 :table in an org-mode table
21553 :table-special on a special filed in a table
21554 :table-table in a table.el table
21555 :clocktable in a clocktable
21556 :src-block in a source block
21557 :link on a hyperlink
21558 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21559 :target on a <<target>>
21560 :radio-target on a <<<radio-target>>>
21561 :latex-fragment on a LaTeX fragment
21562 :latex-preview on a LaTeX fragment with overlaid preview image
21564 This function expects the position to be visible because it uses font-lock
21565 faces as a help to recognize the following contexts: :table-special, :link,
21566 and :keyword."
21567 (let* ((f (get-text-property (point) 'face))
21568 (faces (if (listp f) f (list f)))
21569 (case-fold-search t)
21570 (p (point)) clist o)
21571 ;; First the large context
21572 (cond
21573 ((org-at-heading-p t)
21574 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21575 (when (progn
21576 (beginning-of-line 1)
21577 (looking-at org-todo-line-tags-regexp))
21578 (push (org-point-in-group p 1 :headline-stars) clist)
21579 (push (org-point-in-group p 2 :todo-keyword) clist)
21580 (push (org-point-in-group p 4 :tags) clist))
21581 (goto-char p)
21582 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21583 (if (looking-at "\\[#[A-Z0-9]\\]")
21584 (push (org-point-in-group p 0 :priority) clist)))
21586 ((org-at-item-p)
21587 (push (org-point-in-group p 2 :item-bullet) clist)
21588 (push (list :item (point-at-bol)
21589 (save-excursion (org-end-of-item) (point)))
21590 clist)
21591 (and (org-at-item-checkbox-p)
21592 (push (org-point-in-group p 0 :checkbox) clist)))
21594 ((org-at-table-p)
21595 (push (list :table (org-table-begin) (org-table-end)) clist)
21596 (if (memq 'org-formula faces)
21597 (push (list :table-special
21598 (previous-single-property-change p 'face)
21599 (next-single-property-change p 'face)) clist)))
21600 ((org-at-table-p 'any)
21601 (push (list :table-table) clist)))
21602 (goto-char p)
21604 (let ((case-fold-search t))
21605 ;; New the "medium" contexts: clocktables, source blocks
21606 (cond ((org-in-clocktable-p)
21607 (push (list :clocktable
21608 (and (or (looking-at "#\\+BEGIN: clocktable")
21609 (search-backward "#+BEGIN: clocktable" nil t))
21610 (match-beginning 0))
21611 (and (re-search-forward "#\\+END:?" nil t)
21612 (match-end 0))) clist))
21613 ((org-in-src-block-p)
21614 (push (list :src-block
21615 (and (or (looking-at "#\\+BEGIN_SRC")
21616 (search-backward "#+BEGIN_SRC" nil t))
21617 (match-beginning 0))
21618 (and (search-forward "#+END_SRC" nil t)
21619 (match-beginning 0))) clist))))
21620 (goto-char p)
21622 ;; Now the small context
21623 (cond
21624 ((org-at-timestamp-p)
21625 (push (org-point-in-group p 0 :timestamp) clist))
21626 ((memq 'org-link faces)
21627 (push (list :link
21628 (previous-single-property-change p 'face)
21629 (next-single-property-change p 'face)) clist))
21630 ((memq 'org-special-keyword faces)
21631 (push (list :keyword
21632 (previous-single-property-change p 'face)
21633 (next-single-property-change p 'face)) clist))
21634 ((org-at-target-p)
21635 (push (org-point-in-group p 0 :target) clist)
21636 (goto-char (1- (match-beginning 0)))
21637 (if (looking-at org-radio-target-regexp)
21638 (push (org-point-in-group p 0 :radio-target) clist))
21639 (goto-char p))
21640 ((setq o (car (delq nil
21641 (mapcar
21642 (lambda (x)
21643 (if (memq x org-latex-fragment-image-overlays) x))
21644 (overlays-at (point))))))
21645 (push (list :latex-fragment
21646 (overlay-start o) (overlay-end o)) clist)
21647 (push (list :latex-preview
21648 (overlay-start o) (overlay-end o)) clist))
21649 ((org-inside-LaTeX-fragment-p)
21650 ;; FIXME: positions wrong.
21651 (push (list :latex-fragment (point) (point)) clist)))
21653 (setq clist (nreverse (delq nil clist)))
21654 clist))
21656 ;; FIXME: Compare with at-regexp-p Do we need both?
21657 (defun org-in-regexp (re &optional nlines visually)
21658 "Check if point is inside a match of regexp.
21659 Normally only the current line is checked, but you can include NLINES extra
21660 lines both before and after point into the search.
21661 If VISUALLY is set, require that the cursor is not after the match but
21662 really on, so that the block visually is on the match."
21663 (catch 'exit
21664 (let ((pos (point))
21665 (eol (point-at-eol (+ 1 (or nlines 0))))
21666 (inc (if visually 1 0)))
21667 (save-excursion
21668 (beginning-of-line (- 1 (or nlines 0)))
21669 (while (re-search-forward re eol t)
21670 (if (and (<= (match-beginning 0) pos)
21671 (>= (+ inc (match-end 0)) pos))
21672 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21674 (defun org-at-regexp-p (regexp)
21675 "Is point inside a match of REGEXP in the current line?"
21676 (catch 'exit
21677 (save-excursion
21678 (let ((pos (point)) (end (point-at-eol)))
21679 (beginning-of-line 1)
21680 (while (re-search-forward regexp end t)
21681 (if (and (<= (match-beginning 0) pos)
21682 (>= (match-end 0) pos))
21683 (throw 'exit t)))
21684 nil))))
21686 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21687 "Non-nil when point is between matches of START-RE and END-RE.
21689 Also return a non-nil value when point is on one of the matches.
21691 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21692 buffer positions. Default values are the positions of headlines
21693 surrounding the point.
21695 The functions returns a cons cell whose car (resp. cdr) is the
21696 position before START-RE (resp. after END-RE)."
21697 (save-match-data
21698 (let ((pos (point))
21699 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21700 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21701 beg end)
21702 (save-excursion
21703 ;; Point is on a block when on START-RE or if START-RE can be
21704 ;; found before it...
21705 (and (or (org-at-regexp-p start-re)
21706 (re-search-backward start-re limit-up t))
21707 (setq beg (match-beginning 0))
21708 ;; ... and END-RE after it...
21709 (goto-char (match-end 0))
21710 (re-search-forward end-re limit-down t)
21711 (> (setq end (match-end 0)) pos)
21712 ;; ... without another START-RE in-between.
21713 (goto-char (match-beginning 0))
21714 (not (re-search-backward start-re (1+ beg) t))
21715 ;; Return value.
21716 (cons beg end))))))
21718 (defun org-in-block-p (names)
21719 "Non-nil when point belongs to a block whose name belongs to NAMES.
21721 NAMES is a list of strings containing names of blocks.
21723 Return first block name matched, or nil. Beware that in case of
21724 nested blocks, the returned name may not belong to the closest
21725 block from point."
21726 (save-match-data
21727 (catch 'exit
21728 (let ((case-fold-search t)
21729 (lim-up (save-excursion (outline-previous-heading)))
21730 (lim-down (save-excursion (outline-next-heading))))
21731 (mapc (lambda (name)
21732 (let ((n (regexp-quote name)))
21733 (when (org-between-regexps-p
21734 (concat "^[ \t]*#\\+begin_" n)
21735 (concat "^[ \t]*#\\+end_" n)
21736 lim-up lim-down)
21737 (throw 'exit n))))
21738 names))
21739 nil)))
21741 (defun org-in-drawer-p ()
21742 "Is point within a drawer?"
21743 (save-match-data
21744 (let ((case-fold-search t)
21745 (lim-up (save-excursion (outline-previous-heading)))
21746 (lim-down (save-excursion (outline-next-heading))))
21747 (org-between-regexps-p
21748 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21749 "^[ \t]*:end:.*$"
21750 lim-up lim-down))))
21752 (defun org-occur-in-agenda-files (regexp &optional nlines)
21753 "Call `multi-occur' with buffers for all agenda files."
21754 (interactive "sOrg-files matching: \np")
21755 (let* ((files (org-agenda-files))
21756 (tnames (mapcar 'file-truename files))
21757 (extra org-agenda-text-search-extra-files)
21759 (when (eq (car extra) 'agenda-archives)
21760 (setq extra (cdr extra))
21761 (setq files (org-add-archive-files files)))
21762 (while (setq f (pop extra))
21763 (unless (member (file-truename f) tnames)
21764 (add-to-list 'files f 'append)
21765 (add-to-list 'tnames (file-truename f) 'append)))
21766 (multi-occur
21767 (mapcar (lambda (x)
21768 (with-current-buffer
21769 (or (get-file-buffer x) (find-file-noselect x))
21770 (widen)
21771 (current-buffer)))
21772 files)
21773 regexp)))
21775 (if (boundp 'occur-mode-find-occurrence-hook)
21776 ;; Emacs 23
21777 (add-hook 'occur-mode-find-occurrence-hook
21778 (lambda ()
21779 (when (derived-mode-p 'org-mode)
21780 (org-reveal))))
21781 ;; Emacs 22
21782 (defadvice occur-mode-goto-occurrence
21783 (after org-occur-reveal activate)
21784 (and (derived-mode-p 'org-mode) (org-reveal)))
21785 (defadvice occur-mode-goto-occurrence-other-window
21786 (after org-occur-reveal activate)
21787 (and (derived-mode-p 'org-mode) (org-reveal)))
21788 (defadvice occur-mode-display-occurrence
21789 (after org-occur-reveal activate)
21790 (when (derived-mode-p 'org-mode)
21791 (let ((pos (occur-mode-find-occurrence)))
21792 (with-current-buffer (marker-buffer pos)
21793 (save-excursion
21794 (goto-char pos)
21795 (org-reveal)))))))
21797 (defun org-occur-link-in-agenda-files ()
21798 "Create a link and search for it in the agendas.
21799 The link is not stored in `org-stored-links', it is just created
21800 for the search purpose."
21801 (interactive)
21802 (let ((link (condition-case nil
21803 (org-store-link nil)
21804 (error "Unable to create a link to here"))))
21805 (org-occur-in-agenda-files (regexp-quote link))))
21807 (defun org-reverse-string (string)
21808 "Return the reverse of STRING."
21809 (apply 'string (reverse (string-to-list string))))
21811 (defsubst org-uniquify (list)
21812 "Non-destructively remove duplicate elements from LIST."
21813 (let ((res (copy-sequence list))) (delete-dups res)))
21815 (defun org-uniquify-alist (alist)
21816 "Merge elements of ALIST with the same key.
21818 For example, in this alist:
21820 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21821 => '((a 1 3) (b 2))
21823 merge (a 1) and (a 3) into (a 1 3).
21825 The function returns the new ALIST."
21826 (let (rtn)
21827 (mapc
21828 (lambda (e)
21829 (let (n)
21830 (if (not (assoc (car e) rtn))
21831 (push e rtn)
21832 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21833 (setq rtn (assq-delete-all (car e) rtn))
21834 (push n rtn))))
21835 alist)
21836 rtn))
21838 (defun org-delete-all (elts list)
21839 "Remove all elements in ELTS from LIST."
21840 (while elts
21841 (setq list (delete (pop elts) list)))
21842 list)
21844 (defun org-count (cl-item cl-seq)
21845 "Count the number of occurrences of ITEM in SEQ.
21846 Taken from `count' in cl-seq.el with all keyword arguments removed."
21847 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21848 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21849 (while (< cl-start cl-end)
21850 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21851 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21852 (setq cl-start (1+ cl-start)))
21853 cl-count))
21855 (defun org-remove-if (predicate seq)
21856 "Remove everything from SEQ that fulfills PREDICATE."
21857 (let (res e)
21858 (while seq
21859 (setq e (pop seq))
21860 (if (not (funcall predicate e)) (push e res)))
21861 (nreverse res)))
21863 (defun org-remove-if-not (predicate seq)
21864 "Remove everything from SEQ that does not fulfill PREDICATE."
21865 (let (res e)
21866 (while seq
21867 (setq e (pop seq))
21868 (if (funcall predicate e) (push e res)))
21869 (nreverse res)))
21871 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21872 "Reduce two-argument FUNCTION across SEQ.
21873 Taken from `reduce' in cl-seq.el with all keyword arguments but
21874 \":initial-value\" removed."
21875 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21876 (cadr (memq :initial-value cl-keys)))
21877 (cl-seq (pop cl-seq))
21878 (t (funcall cl-func)))))
21879 (while cl-seq
21880 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21881 cl-accum))
21883 (defun org-every (pred seq)
21884 "Return true if PREDICATE is true of every element of SEQ.
21885 Adapted from `every' in cl.el."
21886 (catch 'org-every
21887 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21890 (defun org-some (pred seq)
21891 "Return true if PREDICATE is true of any element of SEQ.
21892 Adapted from `some' in cl.el."
21893 (catch 'org-some
21894 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21895 nil))
21897 (defun org-back-over-empty-lines ()
21898 "Move backwards over whitespace, to the beginning of the first empty line.
21899 Returns the number of empty lines passed."
21900 (let ((pos (point)))
21901 (if (cdr (assoc 'heading org-blank-before-new-entry))
21902 (skip-chars-backward " \t\n\r")
21903 (unless (eobp)
21904 (forward-line -1)))
21905 (beginning-of-line 2)
21906 (goto-char (min (point) pos))
21907 (count-lines (point) pos)))
21909 (defun org-skip-whitespace ()
21910 (skip-chars-forward " \t\n\r"))
21912 (defun org-point-in-group (point group &optional context)
21913 "Check if POINT is in match-group GROUP.
21914 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21915 match. If the match group does not exist or point is not inside it,
21916 return nil."
21917 (and (match-beginning group)
21918 (>= point (match-beginning group))
21919 (<= point (match-end group))
21920 (if context
21921 (list context (match-beginning group) (match-end group))
21922 t)))
21924 (defun org-switch-to-buffer-other-window (&rest args)
21925 "Switch to buffer in a second window on the current frame.
21926 In particular, do not allow pop-up frames.
21927 Returns the newly created buffer."
21928 (org-no-popups
21929 (apply 'switch-to-buffer-other-window args)))
21931 (defun org-combine-plists (&rest plists)
21932 "Create a single property list from all plists in PLISTS.
21933 The process starts by copying the first list, and then setting properties
21934 from the other lists. Settings in the last list are the most significant
21935 ones and overrule settings in the other lists."
21936 (let ((rtn (copy-sequence (pop plists)))
21937 p v ls)
21938 (while plists
21939 (setq ls (pop plists))
21940 (while ls
21941 (setq p (pop ls) v (pop ls))
21942 (setq rtn (plist-put rtn p v))))
21943 rtn))
21945 (defun org-replace-escapes (string table)
21946 "Replace %-escapes in STRING with values in TABLE.
21947 TABLE is an association list with keys like \"%a\" and string values.
21948 The sequences in STRING may contain normal field width and padding information,
21949 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21950 so values can contain further %-escapes if they are define later in TABLE."
21951 (let ((tbl (copy-alist table))
21952 (case-fold-search nil)
21953 (pchg 0)
21954 e re rpl)
21955 (while (setq e (pop tbl))
21956 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21957 (when (and (cdr e) (string-match re (cdr e)))
21958 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21959 (safe "SREF"))
21960 (add-text-properties 0 3 (list 'sref sref) safe)
21961 (setcdr e (replace-match safe t t (cdr e)))))
21962 (while (string-match re string)
21963 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21964 (cdr e)))
21965 (setq string (replace-match rpl t t string))))
21966 (while (setq pchg (next-property-change pchg string))
21967 (let ((sref (get-text-property pchg 'sref string)))
21968 (when (and sref (string-match "SREF" string pchg))
21969 (setq string (replace-match sref t t string)))))
21970 string))
21972 (defun org-sublist (list start end)
21973 "Return a section of LIST, from START to END.
21974 Counting starts at 1."
21975 (let (rtn (c start))
21976 (setq list (nthcdr (1- start) list))
21977 (while (and list (<= c end))
21978 (push (pop list) rtn)
21979 (setq c (1+ c)))
21980 (nreverse rtn)))
21982 (defun org-find-base-buffer-visiting (file)
21983 "Like `find-buffer-visiting' but always return the base buffer and
21984 not an indirect buffer."
21985 (let ((buf (or (get-file-buffer file)
21986 (find-buffer-visiting file))))
21987 (if buf
21988 (or (buffer-base-buffer buf) buf)
21989 nil)))
21991 (defun org-image-file-name-regexp (&optional extensions)
21992 "Return regexp matching the file names of images.
21993 If EXTENSIONS is given, only match these."
21994 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21995 (image-file-name-regexp)
21996 (let ((image-file-name-extensions
21997 (or extensions
21998 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21999 "xbm" "xpm" "pbm" "pgm" "ppm"))))
22000 (concat "\\."
22001 (regexp-opt (nconc (mapcar 'upcase
22002 image-file-name-extensions)
22003 image-file-name-extensions)
22005 "\\'"))))
22007 (defun org-file-image-p (file &optional extensions)
22008 "Return non-nil if FILE is an image."
22009 (save-match-data
22010 (string-match (org-image-file-name-regexp extensions) file)))
22012 (defun org-get-cursor-date (&optional with-time)
22013 "Return the date at cursor in as a time.
22014 This works in the calendar and in the agenda, anywhere else it just
22015 returns the current time.
22016 If WITH-TIME is non-nil, returns the time of the event at point (in
22017 the agenda) or the current time of the day."
22018 (let (date day defd tp tm hod mod)
22019 (when with-time
22020 (setq tp (get-text-property (point) 'time))
22021 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22022 (setq hod (string-to-number (match-string 1 tp))
22023 mod (string-to-number (match-string 2 tp))))
22024 (or tp (setq hod (nth 2 (decode-time (current-time)))
22025 mod (nth 1 (decode-time (current-time))))))
22026 (cond
22027 ((eq major-mode 'calendar-mode)
22028 (setq date (calendar-cursor-to-date)
22029 defd (encode-time 0 (or mod 0) (or hod 0)
22030 (nth 1 date) (nth 0 date) (nth 2 date))))
22031 ((eq major-mode 'org-agenda-mode)
22032 (setq day (get-text-property (point) 'day))
22033 (if day
22034 (setq date (calendar-gregorian-from-absolute day)
22035 defd (encode-time 0 (or mod 0) (or hod 0)
22036 (nth 1 date) (nth 0 date) (nth 2 date))))))
22037 (or defd (current-time))))
22039 (defun org-mark-subtree (&optional up)
22040 "Mark the current subtree.
22041 This puts point at the start of the current subtree, and mark at
22042 the end. If a numeric prefix UP is given, move up into the
22043 hierarchy of headlines by UP levels before marking the subtree."
22044 (interactive "P")
22045 (org-with-limited-levels
22046 (cond ((org-at-heading-p) (beginning-of-line))
22047 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22048 (t (outline-previous-visible-heading 1))))
22049 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22050 (if (org-called-interactively-p 'any)
22051 (call-interactively 'org-mark-element)
22052 (org-mark-element)))
22055 ;;; Indentation
22057 (defun org-indent-line ()
22058 "Indent line depending on context."
22059 (interactive)
22060 (let* ((pos (point))
22061 (itemp (org-at-item-p))
22062 (case-fold-search t)
22063 (org-drawer-regexp (or org-drawer-regexp "\000"))
22064 (inline-task-p (and (featurep 'org-inlinetask)
22065 (org-inlinetask-in-task-p)))
22066 (inline-re (and inline-task-p
22067 (org-inlinetask-outline-regexp)))
22068 column)
22069 (if (and orgstruct-is-++ (eq pos (point)))
22070 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22071 (indent-according-to-mode))
22072 (beginning-of-line 1)
22073 (cond
22074 ;; Headings
22075 ((looking-at org-outline-regexp) (setq column 0))
22076 ;; Footnote definition
22077 ((looking-at org-footnote-definition-re) (setq column 0))
22078 ;; Literal examples
22079 ((looking-at "[ \t]*:\\( \\|$\\)")
22080 (setq column (org-get-indentation))) ; do nothing
22081 ;; Lists
22082 ((ignore-errors (goto-char (org-in-item-p)))
22083 (setq column (if itemp
22084 (org-get-indentation)
22085 (org-list-item-body-column (point))))
22086 (goto-char pos))
22087 ;; Drawers
22088 ((and (looking-at "[ \t]*:END:")
22089 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22090 (save-excursion
22091 (goto-char (1- (match-beginning 1)))
22092 (setq column (current-column))))
22093 ;; Special blocks
22094 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22095 (save-excursion
22096 (re-search-backward
22097 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22098 (setq column (org-get-indentation (match-string 0))))
22099 ((and (not (looking-at "[ \t]*#\\+begin_"))
22100 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22101 (save-excursion
22102 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22103 (setq column
22104 (cond ((equal (downcase (match-string 1)) "src")
22105 ;; src blocks: let `org-edit-src-exit' handle them
22106 (org-get-indentation))
22107 ((equal (downcase (match-string 1)) "example")
22108 (max (org-get-indentation)
22109 (org-get-indentation (match-string 0))))
22111 (org-get-indentation (match-string 0))))))
22112 ;; This line has nothing special, look at the previous relevant
22113 ;; line to compute indentation
22115 (beginning-of-line 0)
22116 (while (and (not (bobp))
22117 (not (looking-at org-table-line-regexp))
22118 (not (looking-at org-drawer-regexp))
22119 ;; When point started in an inline task, do not move
22120 ;; above task starting line.
22121 (not (and inline-task-p (looking-at inline-re)))
22122 ;; Skip drawers, blocks, empty lines, verbatim,
22123 ;; comments, tables, footnotes definitions, lists,
22124 ;; inline tasks.
22125 (or (and (looking-at "[ \t]*:END:")
22126 (re-search-backward org-drawer-regexp nil t))
22127 (and (looking-at "[ \t]*#\\+end_")
22128 (re-search-backward "[ \t]*#\\+begin_"nil t))
22129 (looking-at "[ \t]*[\n:#|]")
22130 (looking-at org-footnote-definition-re)
22131 (and (not inline-task-p)
22132 (featurep 'org-inlinetask)
22133 (org-inlinetask-in-task-p)
22134 (or (org-inlinetask-goto-beginning) t))))
22135 (beginning-of-line 0))
22136 (cond
22137 ;; There was a list item above.
22138 ((ignore-errors (goto-char (org-in-item-p)))
22139 (goto-char (org-list-get-top-point (org-list-struct)))
22140 (setq column (org-get-indentation)))
22141 ;; There was an heading above.
22142 ((looking-at "\\*+[ \t]+")
22143 (if (not org-adapt-indentation)
22144 (setq column 0)
22145 (goto-char (match-end 0))
22146 (setq column (current-column))))
22147 ;; A drawer had started and is unfinished
22148 ((looking-at org-drawer-regexp)
22149 (goto-char (1- (match-beginning 1)))
22150 (setq column (current-column)))
22151 ;; Else, nothing noticeable found: get indentation and go on.
22152 (t (setq column (org-get-indentation))))))
22153 ;; Now apply indentation and move cursor accordingly
22154 (goto-char pos)
22155 (if (<= (current-column) (current-indentation))
22156 (org-indent-line-to column)
22157 (save-excursion (org-indent-line-to column)))
22158 ;; Special polishing for properties, see `org-property-format'
22159 (setq column (current-column))
22160 (beginning-of-line 1)
22161 (if (looking-at org-property-re)
22162 (replace-match (concat (match-string 4)
22163 (format org-property-format
22164 (match-string 1) (match-string 3)))
22165 t t))
22166 (org-move-to-column column))))
22168 (defun org-indent-drawer ()
22169 "Indent the drawer at point."
22170 (interactive)
22171 (let ((p (point))
22172 (e (and (save-excursion (re-search-forward ":END:" nil t))
22173 (match-end 0)))
22174 (folded
22175 (save-excursion
22176 (end-of-line)
22177 (when (overlays-at (point))
22178 (member 'invisible (overlay-properties
22179 (car (overlays-at (point)))))))))
22180 (when folded (org-cycle))
22181 (indent-for-tab-command)
22182 (while (and (move-beginning-of-line 2) (< (point) e))
22183 (indent-for-tab-command))
22184 (goto-char p)
22185 (when folded (org-cycle)))
22186 (message "Drawer at point indented"))
22188 (defun org-indent-block ()
22189 "Indent the block at point."
22190 (interactive)
22191 (let ((p (point))
22192 (case-fold-search t)
22193 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22194 (match-end 0)))
22195 (folded
22196 (save-excursion
22197 (end-of-line)
22198 (when (overlays-at (point))
22199 (member 'invisible (overlay-properties
22200 (car (overlays-at (point)))))))))
22201 (when folded (org-cycle))
22202 (indent-for-tab-command)
22203 (while (and (move-beginning-of-line 2) (< (point) e))
22204 (indent-for-tab-command))
22205 (goto-char p)
22206 (when folded (org-cycle)))
22207 (message "Block at point indented"))
22209 (defun org-indent-region (start end)
22210 "Indent region."
22211 (interactive "r")
22212 (save-excursion
22213 (let ((line-end (org-current-line end)))
22214 (goto-char start)
22215 (while (< (org-current-line) line-end)
22216 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22217 (t (call-interactively 'org-indent-line)))
22218 (move-beginning-of-line 2)))))
22221 ;;; Filling
22223 ;; We use our own fill-paragraph and auto-fill functions.
22225 ;; `org-fill-paragraph' relies on adaptive filling and context
22226 ;; checking. Appropriate `fill-prefix' is computed with
22227 ;; `org-adaptive-fill-function'.
22229 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22230 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22231 ;; `org-adaptive-fill-function' value. Internally,
22232 ;; `org-comment-line-break-function' breaks the line.
22234 ;; `org-setup-filling' installs filling and auto-filling related
22235 ;; variables during `org-mode' initialization.
22237 (defvar org-element-paragraph-separate) ; org-element.el
22238 (defun org-setup-filling ()
22239 (require 'org-element)
22240 ;; Prevent auto-fill from inserting unwanted new items.
22241 (when (boundp 'fill-nobreak-predicate)
22242 (org-set-local
22243 'fill-nobreak-predicate
22244 (org-uniquify
22245 (append fill-nobreak-predicate
22246 '(org-fill-line-break-nobreak-p
22247 org-fill-paragraph-with-timestamp-nobreak-p)))))
22248 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22249 (org-set-local 'paragraph-start paragraph-ending)
22250 (org-set-local 'paragraph-separate paragraph-ending))
22251 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22252 (org-set-local 'auto-fill-inhibit-regexp nil)
22253 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22254 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22255 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22257 (defun org-fill-line-break-nobreak-p ()
22258 "Non-nil when a new line at point would create an Org line break."
22259 (save-excursion
22260 (skip-chars-backward "[ \t]")
22261 (skip-chars-backward "\\\\")
22262 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22264 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22265 "Non-nil when a new line at point would split a timestamp."
22266 (and (org-at-timestamp-p t)
22267 (not (looking-at org-ts-regexp-both))))
22269 (declare-function message-in-body-p "message" ())
22270 (defvar orgtbl-line-start-regexp) ; From org-table.el
22271 (defun org-adaptive-fill-function ()
22272 "Compute a fill prefix for the current line.
22273 Return fill prefix, as a string, or nil if current line isn't
22274 meant to be filled. For convenience, if `adaptive-fill-regexp'
22275 matches in paragraphs or comments, use it."
22276 (catch 'exit
22277 (when (derived-mode-p 'message-mode)
22278 (save-excursion
22279 (beginning-of-line)
22280 (cond ((or (not (message-in-body-p))
22281 (looking-at orgtbl-line-start-regexp))
22282 (throw 'exit nil))
22283 ((looking-at message-cite-prefix-regexp)
22284 (throw 'exit (match-string-no-properties 0)))
22285 ((looking-at org-outline-regexp)
22286 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22287 (org-with-wide-buffer
22288 (let* ((p (line-beginning-position))
22289 (element (save-excursion
22290 (beginning-of-line)
22291 (or (ignore-errors (org-element-at-point))
22292 (user-error "An element cannot be parsed line %d"
22293 (line-number-at-pos (point))))))
22294 (type (org-element-type element))
22295 (post-affiliated (org-element-property :post-affiliated element)))
22296 (unless (and post-affiliated (< p post-affiliated))
22297 (case type
22298 (comment
22299 (save-excursion
22300 (beginning-of-line)
22301 (looking-at "[ \t]*")
22302 (concat (match-string 0) "# ")))
22303 (footnote-definition "")
22304 ((item plain-list)
22305 (make-string (org-list-item-body-column
22306 (or post-affiliated
22307 (org-element-property :begin element)))
22308 ? ))
22309 (paragraph
22310 ;; Fill prefix is usually the same as the current line,
22311 ;; unless the paragraph is at the beginning of an item.
22312 (let ((parent (org-element-property :parent element)))
22313 (save-excursion
22314 (beginning-of-line)
22315 (cond ((eq (org-element-type parent) 'item)
22316 (make-string (org-list-item-body-column
22317 (org-element-property :begin parent))
22318 ? ))
22319 ((and adaptive-fill-regexp
22320 ;; Locally disable
22321 ;; `adaptive-fill-function' to let
22322 ;; `fill-context-prefix' handle
22323 ;; `adaptive-fill-regexp' variable.
22324 (let (adaptive-fill-function)
22325 (fill-context-prefix
22326 post-affiliated
22327 (org-element-property :end element)))))
22328 ((looking-at "[ \t]+") (match-string 0))
22329 (t "")))))
22330 (comment-block
22331 ;; Only fill contents if P is within block boundaries.
22332 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22333 (forward-line)
22334 (point)))
22335 (cend (save-excursion
22336 (goto-char (org-element-property :end element))
22337 (skip-chars-backward " \r\t\n")
22338 (line-beginning-position))))
22339 (when (and (>= p cbeg) (< p cend))
22340 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22341 (match-string 0)
22342 ""))))))))))
22344 (declare-function message-goto-body "message" ())
22345 (defvar message-cite-prefix-regexp) ; From message.el
22346 (defun org-fill-paragraph (&optional justify)
22347 "Fill element at point, when applicable.
22349 This function only applies to comment blocks, comments, example
22350 blocks and paragraphs. Also, as a special case, re-align table
22351 when point is at one.
22353 If JUSTIFY is non-nil (interactively, with prefix argument),
22354 justify as well. If `sentence-end-double-space' is non-nil, then
22355 period followed by one space does not end a sentence, so don't
22356 break a line there. The variable `fill-column' controls the
22357 width for filling.
22359 For convenience, when point is at a plain list, an item or
22360 a footnote definition, try to fill the first paragraph within."
22361 (interactive)
22362 (if (and (derived-mode-p 'message-mode)
22363 (or (not (message-in-body-p))
22364 (save-excursion (move-beginning-of-line 1)
22365 (looking-at message-cite-prefix-regexp))))
22366 ;; First ensure filling is correct in message-mode.
22367 (let ((fill-paragraph-function
22368 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22369 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22370 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22371 (paragraph-separate
22372 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22373 (fill-paragraph nil))
22374 (with-syntax-table org-mode-transpose-word-syntax-table
22375 ;; Move to end of line in order to get the first paragraph
22376 ;; within a plain list or a footnote definition.
22377 (let ((element (save-excursion
22378 (end-of-line)
22379 (or (ignore-errors (org-element-at-point))
22380 (user-error "An element cannot be parsed line %d"
22381 (line-number-at-pos (point)))))))
22382 ;; First check if point is in a blank line at the beginning of
22383 ;; the buffer. In that case, ignore filling.
22384 (case (org-element-type element)
22385 ;; Use major mode filling function is src blocks.
22386 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22387 ;; Align Org tables, leave table.el tables as-is.
22388 (table-row (org-table-align) t)
22389 (table
22390 (when (eq (org-element-property :type element) 'org)
22391 (save-excursion
22392 (goto-char (org-element-property :post-affiliated element))
22393 (org-table-align)))
22395 (paragraph
22396 ;; Paragraphs may contain `line-break' type objects.
22397 (let ((beg (max (point-min)
22398 (org-element-property :contents-begin element)))
22399 (end (min (point-max)
22400 (org-element-property :contents-end element))))
22401 ;; Do nothing if point is at an affiliated keyword.
22402 (if (< (line-end-position) beg) t
22403 (when (derived-mode-p 'message-mode)
22404 ;; In `message-mode', do not fill following citation
22405 ;; in current paragraph nor text before message body.
22406 (let ((body-start (save-excursion (message-goto-body))))
22407 (when body-start (setq beg (max body-start beg))))
22408 (when (save-excursion
22409 (re-search-forward
22410 (concat "^" message-cite-prefix-regexp) end t))
22411 (setq end (match-beginning 0))))
22412 ;; Fill paragraph, taking line breaks into account.
22413 ;; For that, slice the paragraph using line breaks as
22414 ;; separators, and fill the parts in reverse order to
22415 ;; avoid messing with markers.
22416 (save-excursion
22417 (goto-char end)
22418 (mapc
22419 (lambda (pos)
22420 (fill-region-as-paragraph pos (point) justify)
22421 (goto-char pos))
22422 ;; Find the list of ending positions for line breaks
22423 ;; in the current paragraph. Add paragraph
22424 ;; beginning to include first slice.
22425 (nreverse
22426 (cons beg
22427 (org-element-map
22428 (org-element--parse-objects
22429 beg end nil (org-element-restriction 'paragraph))
22430 'line-break
22431 (lambda (lb) (org-element-property :end lb)))))))
22432 t)))
22433 ;; Contents of `comment-block' type elements should be
22434 ;; filled as plain text, but only if point is within block
22435 ;; markers.
22436 (comment-block
22437 (let* ((case-fold-search t)
22438 (beg (save-excursion
22439 (goto-char (org-element-property :begin element))
22440 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22441 (forward-line)
22442 (point)))
22443 (end (save-excursion
22444 (goto-char (org-element-property :end element))
22445 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22446 (line-beginning-position))))
22447 (if (or (< (point) beg) (> (point) end)) t
22448 (fill-region-as-paragraph
22449 (save-excursion (end-of-line)
22450 (re-search-backward "^[ \t]*$" beg 'move)
22451 (line-beginning-position))
22452 (save-excursion (beginning-of-line)
22453 (re-search-forward "^[ \t]*$" end 'move)
22454 (line-beginning-position))
22455 justify))))
22456 ;; Fill comments.
22457 (comment
22458 (let ((begin (org-element-property :post-affiliated element))
22459 (end (org-element-property :end element)))
22460 (when (and (>= (point) begin) (<= (point) end))
22461 (let ((begin (save-excursion
22462 (end-of-line)
22463 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22464 (progn (forward-line) (point))
22465 begin)))
22466 (end (save-excursion
22467 (end-of-line)
22468 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22469 (1- (line-beginning-position))
22470 (skip-chars-backward " \r\t\n")
22471 (line-end-position)))))
22472 ;; Do not fill comments when at a blank line.
22473 (when (> end begin)
22474 (let ((fill-prefix
22475 (save-excursion
22476 (beginning-of-line)
22477 (looking-at "[ \t]*#")
22478 (let ((comment-prefix (match-string 0)))
22479 (goto-char (match-end 0))
22480 (if (looking-at adaptive-fill-regexp)
22481 (concat comment-prefix (match-string 0))
22482 (concat comment-prefix " "))))))
22483 (save-excursion
22484 (fill-region-as-paragraph begin end justify))))))
22486 ;; Ignore every other element.
22487 (otherwise t))))))
22489 (defun org-auto-fill-function ()
22490 "Auto-fill function."
22491 ;; Check if auto-filling is meaningful.
22492 (let ((fc (current-fill-column)))
22493 (when (and fc (> (current-column) fc))
22494 (let* ((fill-prefix (org-adaptive-fill-function))
22495 ;; Enforce empty fill prefix, if required. Otherwise, it
22496 ;; will be computed again.
22497 (adaptive-fill-mode (not (equal fill-prefix ""))))
22498 (when fill-prefix (do-auto-fill))))))
22500 (defun org-comment-line-break-function (&optional soft)
22501 "Break line at point and indent, continuing comment if within one.
22502 The inserted newline is marked hard if variable
22503 `use-hard-newlines' is true, unless optional argument SOFT is
22504 non-nil."
22505 (if soft (insert-and-inherit ?\n) (newline 1))
22506 (save-excursion (forward-char -1) (delete-horizontal-space))
22507 (delete-horizontal-space)
22508 (indent-to-left-margin)
22509 (insert-before-markers-and-inherit fill-prefix))
22512 ;;; Comments
22514 ;; Org comments syntax is quite complex. It requires the entire line
22515 ;; to be just a comment. Also, even with the right syntax at the
22516 ;; beginning of line, some some elements (i.e. verse-block or
22517 ;; example-block) don't accept comments. Usual Emacs comment commands
22518 ;; cannot cope with those requirements. Therefore, Org replaces them.
22520 ;; Org still relies on `comment-dwim', but cannot trust
22521 ;; `comment-only-p'. So, `comment-region-function' and
22522 ;; `uncomment-region-function' both point
22523 ;; to`org-comment-or-uncomment-region'. Eventually,
22524 ;; `org-insert-comment' takes care of insertion of comments at the
22525 ;; beginning of line.
22527 ;; `org-setup-comments-handling' install comments related variables
22528 ;; during `org-mode' initialization.
22530 (defun org-setup-comments-handling ()
22531 (interactive)
22532 (org-set-local 'comment-use-syntax nil)
22533 (org-set-local 'comment-start "# ")
22534 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22535 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22536 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22537 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22539 (defun org-insert-comment ()
22540 "Insert an empty comment above current line.
22541 If the line is empty, insert comment at its beginning."
22542 (beginning-of-line)
22543 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22544 (org-indent-line)
22545 (insert "# "))
22547 (defvar comment-empty-lines) ; From newcomment.el.
22548 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22549 "Comment or uncomment each non-blank line in the region.
22550 Uncomment each non-blank line between BEG and END if it only
22551 contains commented lines. Otherwise, comment them."
22552 (save-restriction
22553 ;; Restrict region
22554 (narrow-to-region (save-excursion (goto-char beg)
22555 (skip-chars-forward " \r\t\n" end)
22556 (line-beginning-position))
22557 (save-excursion (goto-char end)
22558 (skip-chars-backward " \r\t\n" beg)
22559 (line-end-position)))
22560 (let ((uncommentp
22561 ;; UNCOMMENTP is non-nil when every non blank line between
22562 ;; BEG and END is a comment.
22563 (save-excursion
22564 (goto-char (point-min))
22565 (while (and (not (eobp))
22566 (let ((element (org-element-at-point)))
22567 (and (eq (org-element-type element) 'comment)
22568 (goto-char (min (point-max)
22569 (org-element-property
22570 :end element)))))))
22571 (eobp))))
22572 (if uncommentp
22573 ;; Only blank lines and comments in region: uncomment it.
22574 (save-excursion
22575 (goto-char (point-min))
22576 (while (not (eobp))
22577 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22578 (replace-match "" nil nil nil 1))
22579 (forward-line)))
22580 ;; Comment each line in region.
22581 (let ((min-indent (point-max)))
22582 ;; First find the minimum indentation across all lines.
22583 (save-excursion
22584 (goto-char (point-min))
22585 (while (and (not (eobp)) (not (zerop min-indent)))
22586 (unless (looking-at "[ \t]*$")
22587 (setq min-indent (min min-indent (current-indentation))))
22588 (forward-line)))
22589 ;; Then loop over all lines.
22590 (save-excursion
22591 (goto-char (point-min))
22592 (while (not (eobp))
22593 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22594 ;; Don't get fooled by invisible text (e.g. link path)
22595 ;; when moving to column MIN-INDENT.
22596 (let ((buffer-invisibility-spec nil))
22597 (org-move-to-column min-indent t))
22598 (insert comment-start))
22599 (forward-line))))))))
22602 ;;; Planning
22604 ;; This section contains tools to operate on timestamp objects, as
22605 ;; returned by, e.g. `org-element-context'.
22607 (defun org-timestamp-has-time-p (timestamp)
22608 "Non-nil when TIMESTAMP has a time specified."
22609 (org-element-property :hour-start timestamp))
22611 (defun org-timestamp-format (timestamp format &optional end utc)
22612 "Format a TIMESTAMP element into a string.
22614 FORMAT is a format specifier to be passed to
22615 `format-time-string'.
22617 When optional argument END is non-nil, use end of date-range or
22618 time-range, if possible.
22620 When optional argument UTC is non-nil, time will be expressed as
22621 Universal Time."
22622 (format-time-string
22623 format
22624 (apply 'encode-time
22625 (cons 0
22626 (mapcar
22627 (lambda (prop) (or (org-element-property prop timestamp) 0))
22628 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22629 '(:minute-start :hour-start :day-start :month-start
22630 :year-start)))))
22631 utc))
22633 (defun org-timestamp-split-range (timestamp &optional end)
22634 "Extract a timestamp object from a date or time range.
22636 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22637 the end of the range. Otherwise, extract its start.
22639 Return a new timestamp object sharing the same parent as
22640 TIMESTAMP."
22641 (let ((type (org-element-property :type timestamp)))
22642 (if (memq type '(active inactive diary)) timestamp
22643 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22644 ;; Set new type.
22645 (org-element-put-property
22646 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22647 ;; Copy start properties over end properties if END is
22648 ;; non-nil. Otherwise, copy end properties over `start' ones.
22649 (let ((p-alist '((:minute-start . :minute-end)
22650 (:hour-start . :hour-end)
22651 (:day-start . :day-end)
22652 (:month-start . :month-end)
22653 (:year-start . :year-end))))
22654 (dolist (p-cell p-alist)
22655 (org-element-put-property
22656 split-ts
22657 (funcall (if end 'car 'cdr) p-cell)
22658 (org-element-property
22659 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22660 ;; Eventually refresh `:raw-value'.
22661 (org-element-put-property split-ts :raw-value nil)
22662 (org-element-put-property
22663 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22665 (defun org-timestamp-translate (timestamp &optional boundary)
22666 "Apply `org-translate-time' on a TIMESTAMP object.
22667 When optional argument BOUNDARY is non-nil, it is either the
22668 symbol `start' or `end'. In this case, only translate the
22669 starting or ending part of TIMESTAMP if it is a date or time
22670 range. Otherwise, translate both parts."
22671 (if (and (not boundary)
22672 (memq (org-element-property :type timestamp)
22673 '(active-range inactive-range)))
22674 (concat
22675 (org-translate-time
22676 (org-element-property :raw-value
22677 (org-timestamp-split-range timestamp)))
22678 "--"
22679 (org-translate-time
22680 (org-element-property :raw-value
22681 (org-timestamp-split-range timestamp t))))
22682 (org-translate-time
22683 (org-element-property
22684 :raw-value
22685 (if (not boundary) timestamp
22686 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22690 ;;; Other stuff.
22692 (defun org-toggle-fixed-width-section (arg)
22693 "Toggle the fixed-width export.
22694 If there is no active region, the QUOTE keyword at the current headline is
22695 inserted or removed. When present, it causes the text between this headline
22696 and the next to be exported as fixed-width text, and unmodified.
22697 If there is an active region, this command adds or removes a colon as the
22698 first character of this line. If the first character of a line is a colon,
22699 this line is also exported in fixed-width font."
22700 (interactive "P")
22701 (let* ((cc 0)
22702 (regionp (org-region-active-p))
22703 (beg (if regionp (region-beginning) (point)))
22704 (end (if regionp (region-end)))
22705 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22706 (case-fold-search nil)
22707 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22708 off)
22709 (if regionp
22710 (save-excursion
22711 (goto-char beg)
22712 (setq cc (current-column))
22713 (beginning-of-line 1)
22714 (setq off (looking-at re))
22715 (while (> nlines 0)
22716 (setq nlines (1- nlines))
22717 (beginning-of-line 1)
22718 (cond
22719 (arg
22720 (org-move-to-column cc t)
22721 (insert ": \n")
22722 (forward-line -1))
22723 ((and off (looking-at re))
22724 (replace-match "" t t nil 1))
22725 ((not off) (org-move-to-column cc t) (insert ": ")))
22726 (forward-line 1)))
22727 (save-excursion
22728 (org-back-to-heading)
22729 (cond
22730 ((looking-at (format org-heading-keyword-regexp-format
22731 org-quote-string))
22732 (goto-char (match-end 1))
22733 (looking-at (concat " +" org-quote-string))
22734 (replace-match "" t t)
22735 (when (eolp) (insert " ")))
22736 ((looking-at org-outline-regexp)
22737 (goto-char (match-end 0))
22738 (insert org-quote-string " ")))))))
22740 (defun org-reftex-citation ()
22741 "Use reftex-citation to insert a citation into the buffer.
22742 This looks for a line like
22744 #+BIBLIOGRAPHY: foo plain option:-d
22746 and derives from it that foo.bib is the bibliography file relevant
22747 for this document. It then installs the necessary environment for RefTeX
22748 to work in this buffer and calls `reftex-citation' to insert a citation
22749 into the buffer.
22751 Export of such citations to both LaTeX and HTML is handled by the contributed
22752 package ox-bibtex by Taru Karttunen."
22753 (interactive)
22754 (let ((reftex-docstruct-symbol 'rds)
22755 (reftex-cite-format "\\cite{%l}")
22756 rds bib)
22757 (save-excursion
22758 (save-restriction
22759 (widen)
22760 (let ((case-fold-search t)
22761 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22762 (if (not (save-excursion
22763 (or (re-search-forward re nil t)
22764 (re-search-backward re nil t))))
22765 (error "No bibliography defined in file")
22766 (setq bib (concat (match-string 1) ".bib")
22767 rds (list (list 'bib bib)))))))
22768 (call-interactively 'reftex-citation)))
22770 ;;;; Functions extending outline functionality
22772 (defun org-beginning-of-line (&optional arg)
22773 "Go to the beginning of the current line. If that is invisible, continue
22774 to a visible line beginning. This makes the function of C-a more intuitive.
22775 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22776 first attempt, and only move to after the tags when the cursor is already
22777 beyond the end of the headline."
22778 (interactive "P")
22779 (let ((pos (point))
22780 (special (if (consp org-special-ctrl-a/e)
22781 (car org-special-ctrl-a/e)
22782 org-special-ctrl-a/e))
22783 deactivate-mark refpos)
22784 (if (org-bound-and-true-p visual-line-mode)
22785 (beginning-of-visual-line 1)
22786 (beginning-of-line 1))
22787 (if (and arg (fboundp 'move-beginning-of-line))
22788 (call-interactively 'move-beginning-of-line)
22789 (if (bobp)
22791 (backward-char 1)
22792 (if (org-truely-invisible-p)
22793 (while (and (not (bobp)) (org-truely-invisible-p))
22794 (backward-char 1)
22795 (beginning-of-line 1))
22796 (forward-char 1))))
22797 (when special
22798 (cond
22799 ((and (looking-at org-complex-heading-regexp)
22800 (= (char-after (match-end 1)) ?\ ))
22801 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22802 (point-at-eol)))
22803 (goto-char
22804 (if (eq special t)
22805 (cond ((> pos refpos) refpos)
22806 ((= pos (point)) refpos)
22807 (t (point)))
22808 (cond ((> pos (point)) (point))
22809 ((not (eq last-command this-command)) (point))
22810 (t refpos)))))
22811 ((org-at-item-p)
22812 ;; Being at an item and not looking at an the item means point
22813 ;; was previously moved to beginning of a visual line, which
22814 ;; doesn't contain the item. Therefore, do nothing special,
22815 ;; just stay here.
22816 (when (looking-at org-list-full-item-re)
22817 ;; Set special position at first white space character after
22818 ;; bullet, and check-box, if any.
22819 (let ((after-bullet
22820 (let ((box (match-end 3)))
22821 (if (not box) (match-end 1)
22822 (let ((after (char-after box)))
22823 (if (and after (= after ? )) (1+ box) box))))))
22824 ;; Special case: Move point to special position when
22825 ;; currently after it or at beginning of line.
22826 (if (eq special t)
22827 (when (or (> pos after-bullet) (= (point) pos))
22828 (goto-char after-bullet))
22829 ;; Reversed case: Move point to special position when
22830 ;; point was already at beginning of line and command is
22831 ;; repeated.
22832 (when (and (= (point) pos) (eq last-command this-command))
22833 (goto-char after-bullet))))))))
22834 (org-no-warnings
22835 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22836 (setq disable-point-adjustment
22837 (or (not (invisible-p (point)))
22838 (not (invisible-p (max (point-min) (1- (point))))))))
22840 (defun org-end-of-line (&optional arg)
22841 "Go to the end of the line.
22842 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22843 tags on the first attempt, and only move to after the tags when
22844 the cursor is already beyond the end of the headline."
22845 (interactive "P")
22846 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22847 org-special-ctrl-a/e))
22848 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22849 'end-of-visual-line)
22850 ((fboundp 'move-end-of-line) 'move-end-of-line)
22851 (t 'end-of-line)))
22852 deactivate-mark)
22853 (if (or (not special) arg) (call-interactively move-fun)
22854 (let* ((element (save-excursion (beginning-of-line)
22855 (org-element-at-point)))
22856 (type (org-element-type element)))
22857 (cond
22858 ((memq type '(headline inlinetask))
22859 (let ((pos (point)))
22860 (beginning-of-line 1)
22861 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22862 (if (eq special t)
22863 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22864 (goto-char (match-beginning 1))
22865 (goto-char (match-end 0)))
22866 (if (or (< pos (match-end 0))
22867 (not (eq this-command last-command)))
22868 (goto-char (match-end 0))
22869 (goto-char (match-beginning 1))))
22870 (call-interactively move-fun))))
22871 ((org-element-property :hiddenp element)
22872 ;; If element is hidden, `move-end-of-line' would put point
22873 ;; after it. Use `end-of-line' to stay on current line.
22874 (call-interactively 'end-of-line))
22875 (t (call-interactively move-fun)))))
22876 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22877 (setq disable-point-adjustment
22878 (or (not (invisible-p (point)))
22879 (not (invisible-p (max (point-min) (1- (point))))))))
22881 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22882 (define-key org-mode-map "\C-e" 'org-end-of-line)
22884 (defun org-backward-sentence (&optional arg)
22885 "Go to beginning of sentence, or beginning of table field.
22886 This will call `backward-sentence' or `org-table-beginning-of-field',
22887 depending on context."
22888 (interactive "P")
22889 (cond
22890 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22891 (t (call-interactively 'backward-sentence))))
22893 (defun org-forward-sentence (&optional arg)
22894 "Go to end of sentence, or end of table field.
22895 This will call `forward-sentence' or `org-table-end-of-field',
22896 depending on context."
22897 (interactive "P")
22898 (cond
22899 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22900 (t (call-interactively 'forward-sentence))))
22902 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22903 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22905 (defun org-kill-line (&optional arg)
22906 "Kill line, to tags or end of line."
22907 (interactive "P")
22908 (cond
22909 ((or (not org-special-ctrl-k)
22910 (bolp)
22911 (not (org-at-heading-p)))
22912 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22913 org-ctrl-k-protect-subtree)
22914 (if (or (eq org-ctrl-k-protect-subtree 'error)
22915 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22916 (user-error "C-k aborted as it would kill a hidden subtree")))
22917 (call-interactively
22918 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22919 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22920 (kill-region (point) (match-beginning 1))
22921 (org-set-tags nil t))
22922 (t (kill-region (point) (point-at-eol)))))
22924 (define-key org-mode-map "\C-k" 'org-kill-line)
22926 (defun org-yank (&optional arg)
22927 "Yank. If the kill is a subtree, treat it specially.
22928 This command will look at the current kill and check if is a single
22929 subtree, or a series of subtrees[1]. If it passes the test, and if the
22930 cursor is at the beginning of a line or after the stars of a currently
22931 empty headline, then the yank is handled specially. How exactly depends
22932 on the value of the following variables, both set by default.
22934 org-yank-folded-subtrees
22935 When set, the subtree(s) will be folded after insertion, but only
22936 if doing so would now swallow text after the yanked text.
22938 org-yank-adjusted-subtrees
22939 When set, the subtree will be promoted or demoted in order to
22940 fit into the local outline tree structure, which means that the level
22941 will be adjusted so that it becomes the smaller one of the two
22942 *visible* surrounding headings.
22944 Any prefix to this command will cause `yank' to be called directly with
22945 no special treatment. In particular, a simple \\[universal-argument] prefix \
22946 will just
22947 plainly yank the text as it is.
22949 \[1] The test checks if the first non-white line is a heading
22950 and if there are no other headings with fewer stars."
22951 (interactive "P")
22952 (org-yank-generic 'yank arg))
22954 (defun org-yank-generic (command arg)
22955 "Perform some yank-like command.
22957 This function implements the behavior described in the `org-yank'
22958 documentation. However, it has been generalized to work for any
22959 interactive command with similar behavior."
22961 ;; pretend to be command COMMAND
22962 (setq this-command command)
22964 (if arg
22965 (call-interactively command)
22967 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22968 (and (org-kill-is-subtree-p)
22969 (or (bolp)
22970 (and (looking-at "[ \t]*$")
22971 (string-match
22972 "\\`\\*+\\'"
22973 (buffer-substring (point-at-bol) (point)))))))
22974 swallowp)
22975 (cond
22976 ((and subtreep org-yank-folded-subtrees)
22977 (let ((beg (point))
22978 end)
22979 (if (and subtreep org-yank-adjusted-subtrees)
22980 (org-paste-subtree nil nil 'for-yank)
22981 (call-interactively command))
22983 (setq end (point))
22984 (goto-char beg)
22985 (when (and (bolp) subtreep
22986 (not (setq swallowp
22987 (org-yank-folding-would-swallow-text beg end))))
22988 (org-with-limited-levels
22989 (or (looking-at org-outline-regexp)
22990 (re-search-forward org-outline-regexp-bol end t))
22991 (while (and (< (point) end) (looking-at org-outline-regexp))
22992 (hide-subtree)
22993 (org-cycle-show-empty-lines 'folded)
22994 (condition-case nil
22995 (outline-forward-same-level 1)
22996 (error (goto-char end))))))
22997 (when swallowp
22998 (message
22999 "Inserted text not folded because that would swallow text"))
23001 (goto-char end)
23002 (skip-chars-forward " \t\n\r")
23003 (beginning-of-line 1)
23004 (push-mark beg 'nomsg)))
23005 ((and subtreep org-yank-adjusted-subtrees)
23006 (let ((beg (point-at-bol)))
23007 (org-paste-subtree nil nil 'for-yank)
23008 (push-mark beg 'nomsg)))
23010 (call-interactively command))))))
23012 (defun org-yank-folding-would-swallow-text (beg end)
23013 "Would hide-subtree at BEG swallow any text after END?"
23014 (let (level)
23015 (org-with-limited-levels
23016 (save-excursion
23017 (goto-char beg)
23018 (when (or (looking-at org-outline-regexp)
23019 (re-search-forward org-outline-regexp-bol end t))
23020 (setq level (org-outline-level)))
23021 (goto-char end)
23022 (skip-chars-forward " \t\r\n\v\f")
23023 (if (or (eobp)
23024 (and (bolp) (looking-at org-outline-regexp)
23025 (<= (org-outline-level) level)))
23026 nil ; Nothing would be swallowed
23027 t))))) ; something would swallow
23029 (define-key org-mode-map "\C-y" 'org-yank)
23031 (defun org-truely-invisible-p ()
23032 "Check if point is at a character currently not visible.
23033 This version does not only check the character property, but also
23034 `visible-mode'."
23035 ;; Early versions of noutline don't have `outline-invisible-p'.
23036 (if (org-bound-and-true-p visible-mode)
23038 (outline-invisible-p)))
23040 (defun org-invisible-p2 ()
23041 "Check if point is at a character currently not visible."
23042 (save-excursion
23043 (if (and (eolp) (not (bobp))) (backward-char 1))
23044 ;; Early versions of noutline don't have `outline-invisible-p'.
23045 (outline-invisible-p)))
23047 (defun org-back-to-heading (&optional invisible-ok)
23048 "Call `outline-back-to-heading', but provide a better error message."
23049 (condition-case nil
23050 (outline-back-to-heading invisible-ok)
23051 (error (error "Before first headline at position %d in buffer %s"
23052 (point) (current-buffer)))))
23054 (defun org-before-first-heading-p ()
23055 "Before first heading?"
23056 (save-excursion
23057 (end-of-line)
23058 (null (re-search-backward org-outline-regexp-bol nil t))))
23060 (defun org-at-heading-p (&optional ignored)
23061 (outline-on-heading-p t))
23062 ;; Compatibility alias with Org versions < 7.8.03
23063 (defalias 'org-on-heading-p 'org-at-heading-p)
23065 (defun org-at-comment-p nil
23066 "Is cursor in a line starting with a # character?"
23067 (save-excursion
23068 (beginning-of-line)
23069 (looking-at "^#")))
23071 (defun org-at-drawer-p nil
23072 "Is cursor at a drawer keyword?"
23073 (save-excursion
23074 (move-beginning-of-line 1)
23075 (looking-at org-drawer-regexp)))
23077 (defun org-at-block-p nil
23078 "Is cursor at a block keyword?"
23079 (save-excursion
23080 (move-beginning-of-line 1)
23081 (looking-at org-block-regexp)))
23083 (defun org-point-at-end-of-empty-headline ()
23084 "If point is at the end of an empty headline, return t, else nil.
23085 If the heading only contains a TODO keyword, it is still still considered
23086 empty."
23087 (and (looking-at "[ \t]*$")
23088 (when org-todo-line-regexp
23089 (save-excursion
23090 (beginning-of-line 1)
23091 (let ((case-fold-search nil))
23092 (looking-at org-todo-line-regexp)
23093 (string= (match-string 3) ""))))))
23095 (defun org-at-heading-or-item-p ()
23096 (or (org-at-heading-p) (org-at-item-p)))
23098 (defun org-at-target-p ()
23099 (or (org-in-regexp org-radio-target-regexp)
23100 (org-in-regexp org-target-regexp)))
23101 ;; Compatibility alias with Org versions < 7.8.03
23102 (defalias 'org-on-target-p 'org-at-target-p)
23104 (defun org-up-heading-all (arg)
23105 "Move to the heading line of which the present line is a subheading.
23106 This function considers both visible and invisible heading lines.
23107 With argument, move up ARG levels."
23108 (if (fboundp 'outline-up-heading-all)
23109 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23110 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23112 (defun org-up-heading-safe ()
23113 "Move to the heading line of which the present line is a subheading.
23114 This version will not throw an error. It will return the level of the
23115 headline found, or nil if no higher level is found.
23117 Also, this function will be a lot faster than `outline-up-heading',
23118 because it relies on stars being the outline starters. This can really
23119 make a significant difference in outlines with very many siblings."
23120 (let (start-level re)
23121 (org-back-to-heading t)
23122 (setq start-level (funcall outline-level))
23123 (if (equal start-level 1)
23125 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23126 (if (re-search-backward re nil t)
23127 (funcall outline-level)))))
23129 (defun org-first-sibling-p ()
23130 "Is this heading the first child of its parents?"
23131 (interactive)
23132 (let ((re org-outline-regexp-bol)
23133 level l)
23134 (unless (org-at-heading-p t)
23135 (user-error "Not at a heading"))
23136 (setq level (funcall outline-level))
23137 (save-excursion
23138 (if (not (re-search-backward re nil t))
23140 (setq l (funcall outline-level))
23141 (< l level)))))
23143 (defun org-goto-sibling (&optional previous)
23144 "Goto the next sibling, even if it is invisible.
23145 When PREVIOUS is set, go to the previous sibling instead. Returns t
23146 when a sibling was found. When none is found, return nil and don't
23147 move point."
23148 (let ((fun (if previous 're-search-backward 're-search-forward))
23149 (pos (point))
23150 (re org-outline-regexp-bol)
23151 level l)
23152 (when (condition-case nil (org-back-to-heading t) (error nil))
23153 (setq level (funcall outline-level))
23154 (catch 'exit
23155 (or previous (forward-char 1))
23156 (while (funcall fun re nil t)
23157 (setq l (funcall outline-level))
23158 (when (< l level) (goto-char pos) (throw 'exit nil))
23159 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23160 (goto-char pos)
23161 nil))))
23163 (defun org-show-siblings ()
23164 "Show all siblings of the current headline."
23165 (save-excursion
23166 (while (org-goto-sibling) (org-flag-heading nil)))
23167 (save-excursion
23168 (while (org-goto-sibling 'previous)
23169 (org-flag-heading nil))))
23171 (defun org-goto-first-child ()
23172 "Goto the first child, even if it is invisible.
23173 Return t when a child was found. Otherwise don't move point and
23174 return nil."
23175 (let (level (pos (point)) (re org-outline-regexp-bol))
23176 (when (condition-case nil (org-back-to-heading t) (error nil))
23177 (setq level (outline-level))
23178 (forward-char 1)
23179 (if (and (re-search-forward re nil t) (> (outline-level) level))
23180 (progn (goto-char (match-beginning 0)) t)
23181 (goto-char pos) nil))))
23183 (defun org-show-hidden-entry ()
23184 "Show an entry where even the heading is hidden."
23185 (save-excursion
23186 (org-show-entry)))
23188 (defun org-flag-heading (flag &optional entry)
23189 "Flag the current heading. FLAG non-nil means make invisible.
23190 When ENTRY is non-nil, show the entire entry."
23191 (save-excursion
23192 (org-back-to-heading t)
23193 ;; Check if we should show the entire entry
23194 (if entry
23195 (progn
23196 (org-show-entry)
23197 (save-excursion
23198 (and (outline-next-heading)
23199 (org-flag-heading nil))))
23200 (outline-flag-region (max (point-min) (1- (point)))
23201 (save-excursion (outline-end-of-heading) (point))
23202 flag))))
23204 (defun org-get-next-sibling ()
23205 "Move to next heading of the same level, and return point.
23206 If there is no such heading, return nil.
23207 This is like outline-next-sibling, but invisible headings are ok."
23208 (let ((level (funcall outline-level)))
23209 (outline-next-heading)
23210 (while (and (not (eobp)) (> (funcall outline-level) level))
23211 (outline-next-heading))
23212 (if (or (eobp) (< (funcall outline-level) level))
23214 (point))))
23216 (defun org-get-last-sibling ()
23217 "Move to previous heading of the same level, and return point.
23218 If there is no such heading, return nil."
23219 (let ((opoint (point))
23220 (level (funcall outline-level)))
23221 (outline-previous-heading)
23222 (when (and (/= (point) opoint) (outline-on-heading-p t))
23223 (while (and (> (funcall outline-level) level)
23224 (not (bobp)))
23225 (outline-previous-heading))
23226 (if (< (funcall outline-level) level)
23228 (point)))))
23230 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23231 "Goto to the end of a subtree."
23232 ;; This contains an exact copy of the original function, but it uses
23233 ;; `org-back-to-heading', to make it work also in invisible
23234 ;; trees. And is uses an invisible-ok argument.
23235 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23236 ;; Furthermore, when used inside Org, finding the end of a large subtree
23237 ;; with many children and grandchildren etc, this can be much faster
23238 ;; than the outline version.
23239 (org-back-to-heading invisible-ok)
23240 (let ((first t)
23241 (level (funcall outline-level)))
23242 (if (and (derived-mode-p 'org-mode) (< level 1000))
23243 ;; A true heading (not a plain list item), in Org-mode
23244 ;; This means we can easily find the end by looking
23245 ;; only for the right number of stars. Using a regexp to do
23246 ;; this is so much faster than using a Lisp loop.
23247 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23248 (forward-char 1)
23249 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23250 ;; something else, do it the slow way
23251 (while (and (not (eobp))
23252 (or first (> (funcall outline-level) level)))
23253 (setq first nil)
23254 (outline-next-heading)))
23255 (unless to-heading
23256 (if (memq (preceding-char) '(?\n ?\^M))
23257 (progn
23258 ;; Go to end of line before heading
23259 (forward-char -1)
23260 (if (memq (preceding-char) '(?\n ?\^M))
23261 ;; leave blank line before heading
23262 (forward-char -1))))))
23263 (point))
23265 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23266 "Use Org version in org-mode, for dramatic speed-up."
23267 (if (derived-mode-p 'org-mode)
23268 (progn
23269 (org-end-of-subtree nil t)
23270 (unless (eobp) (backward-char 1)))
23271 ad-do-it))
23273 (defun org-end-of-meta-data-and-drawers ()
23274 "Jump to the first text after meta data and drawers in the current entry.
23275 This will move over empty lines, lines with planning time stamps,
23276 clocking lines, and drawers."
23277 (org-back-to-heading t)
23278 (let ((end (save-excursion (outline-next-heading) (point)))
23279 (re (concat "\\(" org-drawer-regexp "\\)"
23280 "\\|" "[ \t]*" org-keyword-time-regexp)))
23281 (forward-line 1)
23282 (while (re-search-forward re end t)
23283 (if (not (match-end 1))
23284 ;; empty or planning line
23285 (forward-line 1)
23286 ;; a drawer, find the end
23287 (re-search-forward "^[ \t]*:END:" end 'move)
23288 (forward-line 1)))
23289 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23290 (point)))
23292 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23293 "Move forward to the ARG'th subheading at same level as this one.
23294 Stop at the first and last subheadings of a superior heading.
23295 Normally this only looks at visible headings, but when INVISIBLE-OK is
23296 non-nil it will also look at invisible ones."
23297 (interactive "p")
23298 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23299 (if (and arg (< arg 0))
23300 (goto-char (point-min))
23301 (outline-next-heading))
23302 (org-at-heading-p)
23303 (let ((level (- (match-end 0) (match-beginning 0) 1))
23304 (f (if (and arg (< arg 0))
23305 're-search-backward
23306 're-search-forward))
23307 (count (if arg (abs arg) 1))
23308 (result (point)))
23309 (while (and (prog1 (> count 0)
23310 (forward-char (if (and arg (< arg 0)) -1 1)))
23311 (funcall f org-outline-regexp-bol nil 'move))
23312 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23313 (cond ((< l level) (setq count 0))
23314 ((and (= l level)
23315 (or invisible-ok
23316 (progn
23317 (goto-char (line-beginning-position))
23318 (not (outline-invisible-p)))))
23319 (setq count (1- count))
23320 (when (eq l level)
23321 (setq result (point)))))))
23322 (goto-char result))
23323 (beginning-of-line 1)))
23325 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23326 "Move backward to the ARG'th subheading at same level as this one.
23327 Stop at the first and last subheadings of a superior heading."
23328 (interactive "p")
23329 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23331 (defun org-next-block (arg &optional backward block-regexp)
23332 "Jump to the next block.
23333 With a prefix argument ARG, jump forward ARG many source blocks.
23334 When BACKWARD is non-nil, jump to the previous block.
23335 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23336 (interactive "p")
23337 (let ((re (or block-regexp org-block-regexp))
23338 (re-search-fn (or (and backward 're-search-backward)
23339 're-search-forward)))
23340 (if (looking-at re) (forward-char 1))
23341 (condition-case nil
23342 (funcall re-search-fn re nil nil arg)
23343 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23344 (goto-char (match-beginning 0)) (org-show-context)))
23346 (defun org-previous-block (arg &optional block-regexp)
23347 "Jump to the previous block.
23348 With a prefix argument ARG, jump backward ARG many source blocks.
23349 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23350 (interactive "p")
23351 (org-next-block arg t block-regexp))
23353 (defun org-forward-paragraph ()
23354 "Move forward to beginning of next paragraph or equivalent.
23356 The function moves point to the beginning of the next visible
23357 structural element, which can be a paragraph, a table, a list
23358 item, etc. It also provides some special moves for convenience:
23360 - On an affiliated keyword, jump to the beginning of the
23361 relative element.
23362 - On an item or a footnote definition, move to the second
23363 element inside, if any.
23364 - On a table or a property drawer, jump after it.
23365 - On a verse or source block, stop after blank lines."
23366 (interactive)
23367 (when (eobp) (user-error "Cannot move further down"))
23368 (let* ((deactivate-mark nil)
23369 (element (org-element-at-point))
23370 (type (org-element-type element))
23371 (post-affiliated (org-element-property :post-affiliated element))
23372 (contents-begin (org-element-property :contents-begin element))
23373 (contents-end (org-element-property :contents-end element))
23374 (end (let ((end (org-element-property :end element)) (parent element))
23375 (while (and (setq parent (org-element-property :parent parent))
23376 (= (org-element-property :contents-end parent) end))
23377 (setq end (org-element-property :end parent)))
23378 end)))
23379 (cond ((not element)
23380 (skip-chars-forward " \r\t\n")
23381 (or (eobp) (beginning-of-line)))
23382 ;; On affiliated keywords, move to element's beginning.
23383 ((and post-affiliated (< (point) post-affiliated))
23384 (goto-char post-affiliated))
23385 ;; At a table row, move to the end of the table. Similarly,
23386 ;; at a node property, move to the end of the property
23387 ;; drawer.
23388 ((memq type '(node-property table-row))
23389 (goto-char (org-element-property
23390 :end (org-element-property :parent element))))
23391 ((memq type '(property-drawer table)) (goto-char end))
23392 ;; Consider blank lines as separators in verse and source
23393 ;; blocks to ease editing.
23394 ((memq type '(src-block verse-block))
23395 (when (eq type 'src-block)
23396 (setq contents-end
23397 (save-excursion (goto-char end)
23398 (skip-chars-backward " \r\t\n")
23399 (line-beginning-position))))
23400 (beginning-of-line)
23401 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23402 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23403 (goto-char end)
23404 (skip-chars-forward " \r\t\n")
23405 (if (= (point) contents-end) (goto-char end)
23406 (beginning-of-line))))
23407 ;; With no contents, just skip element.
23408 ((not contents-begin) (goto-char end))
23409 ;; If contents are invisible, skip the element altogether.
23410 ((outline-invisible-p (line-end-position))
23411 (case type
23412 (headline
23413 (org-with-limited-levels (outline-next-visible-heading 1)))
23414 ;; At a plain list, make sure we move to the next item
23415 ;; instead of skipping the whole list.
23416 (plain-list (forward-char)
23417 (org-forward-paragraph))
23418 (otherwise (goto-char end))))
23419 ((>= (point) contents-end) (goto-char end))
23420 ((>= (point) contents-begin)
23421 ;; This can only happen on paragraphs and plain lists.
23422 (case type
23423 (paragraph (goto-char end))
23424 ;; At a plain list, try to move to second element in
23425 ;; first item, if possible.
23426 (plain-list (end-of-line)
23427 (org-forward-paragraph))))
23428 ;; When contents start on the middle of a line (e.g. in
23429 ;; items and footnote definitions), try to reach first
23430 ;; element starting after current line.
23431 ((> (line-end-position) contents-begin)
23432 (end-of-line)
23433 (org-forward-paragraph))
23434 (t (goto-char contents-begin)))))
23436 (defun org-backward-paragraph ()
23437 "Move backward to start of previous paragraph or equivalent.
23439 The function moves point to the beginning of the current
23440 structural element, which can be a paragraph, a table, a list
23441 item, etc., or to the beginning of the previous visible one if
23442 point is already there. It also provides some special moves for
23443 convenience:
23445 - On an affiliated keyword, jump to the first one.
23446 - On a table or a property drawer, move to its beginning.
23447 - On a verse or source block, stop before blank lines."
23448 (interactive)
23449 (when (bobp) (user-error "Cannot move further up"))
23450 (let* ((deactivate-mark nil)
23451 (element (org-element-at-point))
23452 (type (org-element-type element))
23453 (contents-begin (org-element-property :contents-begin element))
23454 (contents-end (org-element-property :contents-end element))
23455 (post-affiliated (org-element-property :post-affiliated element))
23456 (begin (org-element-property :begin element)))
23457 (cond
23458 ((not element) (goto-char (point-min)))
23459 ((= (point) begin)
23460 (backward-char)
23461 (org-backward-paragraph))
23462 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23463 ((memq type '(node-property table-row))
23464 (goto-char (org-element-property
23465 :post-affiliated (org-element-property :parent element))))
23466 ((memq type '(property-drawer table)) (goto-char begin))
23467 ((memq type '(src-block verse-block))
23468 (when (eq type 'src-block)
23469 (setq contents-begin
23470 (save-excursion (goto-char begin) (forward-line) (point))))
23471 (if (= (point) contents-begin) (goto-char post-affiliated)
23472 ;; Inside a verse block, see blank lines as paragraph
23473 ;; separators.
23474 (let ((origin (point)))
23475 (skip-chars-backward " \r\t\n" contents-begin)
23476 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23477 (skip-chars-forward " \r\t\n" origin)
23478 (if (= (point) origin) (goto-char contents-begin)
23479 (beginning-of-line))))))
23480 ((not contents-begin) (goto-char (or post-affiliated begin)))
23481 ((eq type 'paragraph)
23482 (goto-char contents-begin)
23483 ;; When at first paragraph in an item or a footnote definition,
23484 ;; move directly to beginning of line.
23485 (let ((parent-contents
23486 (org-element-property
23487 :contents-begin (org-element-property :parent element))))
23488 (when (and parent-contents (= parent-contents contents-begin))
23489 (beginning-of-line))))
23490 ;; At the end of a greater element, move to the beginning of the
23491 ;; last element within.
23492 ((>= (point) contents-end)
23493 (goto-char (1- contents-end))
23494 (org-backward-paragraph))
23495 (t (goto-char (or post-affiliated begin))))
23496 ;; Ensure we never leave point invisible.
23497 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23499 (defun org-forward-element ()
23500 "Move forward by one element.
23501 Move to the next element at the same level, when possible."
23502 (interactive)
23503 (cond ((eobp) (user-error "Cannot move further down"))
23504 ((org-with-limited-levels (org-at-heading-p))
23505 (let ((origin (point)))
23506 (goto-char (org-end-of-subtree nil t))
23507 (unless (org-with-limited-levels (org-at-heading-p))
23508 (goto-char origin)
23509 (user-error "Cannot move further down"))))
23511 (let* ((elem (org-element-at-point))
23512 (end (org-element-property :end elem))
23513 (parent (org-element-property :parent elem)))
23514 (cond ((and parent (= (org-element-property :contents-end parent) end))
23515 (goto-char (org-element-property :end parent)))
23516 ((integer-or-marker-p end) (goto-char end))
23517 (t (message "No element at point")))))))
23519 (defun org-backward-element ()
23520 "Move backward by one element.
23521 Move to the previous element at the same level, when possible."
23522 (interactive)
23523 (cond ((bobp) (user-error "Cannot move further up"))
23524 ((org-with-limited-levels (org-at-heading-p))
23525 ;; At a headline, move to the previous one, if any, or stay
23526 ;; here.
23527 (let ((origin (point)))
23528 (org-with-limited-levels (org-backward-heading-same-level 1))
23529 ;; When current headline has no sibling above, move to its
23530 ;; parent.
23531 (when (= (point) origin)
23532 (or (org-with-limited-levels (org-up-heading-safe))
23533 (progn (goto-char origin)
23534 (user-error "Cannot move further up"))))))
23536 (let* ((trail (org-element-at-point 'keep-trail))
23537 (elem (car trail))
23538 (prev-elem (nth 1 trail))
23539 (beg (org-element-property :begin elem)))
23540 (cond
23541 ;; Move to beginning of current element if point isn't
23542 ;; there already.
23543 ((null beg) (message "No element at point"))
23544 ((/= (point) beg) (goto-char beg))
23545 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23546 ((org-before-first-heading-p) (goto-char (point-min)))
23547 (t (org-back-to-heading)))))))
23549 (defun org-up-element ()
23550 "Move to upper element."
23551 (interactive)
23552 (if (org-with-limited-levels (org-at-heading-p))
23553 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23554 (let* ((elem (org-element-at-point))
23555 (parent (org-element-property :parent elem)))
23556 (if parent (goto-char (org-element-property :begin parent))
23557 (if (org-with-limited-levels (org-before-first-heading-p))
23558 (user-error "No surrounding element")
23559 (org-with-limited-levels (org-back-to-heading)))))))
23561 (defvar org-element-greater-elements)
23562 (defun org-down-element ()
23563 "Move to inner element."
23564 (interactive)
23565 (let ((element (org-element-at-point)))
23566 (cond
23567 ((memq (org-element-type element) '(plain-list table))
23568 (goto-char (org-element-property :contents-begin element))
23569 (forward-char))
23570 ((memq (org-element-type element) org-element-greater-elements)
23571 ;; If contents are hidden, first disclose them.
23572 (when (org-element-property :hiddenp element) (org-cycle))
23573 (goto-char (or (org-element-property :contents-begin element)
23574 (user-error "No content for this element"))))
23575 (t (user-error "No inner element")))))
23577 (defun org-drag-element-backward ()
23578 "Move backward element at point."
23579 (interactive)
23580 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23581 (let* ((trail (org-element-at-point 'keep-trail))
23582 (elem (car trail))
23583 (prev-elem (nth 1 trail)))
23584 ;; Error out if no previous element or previous element is
23585 ;; a parent of the current one.
23586 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23587 (user-error "Cannot drag element backward")
23588 (let ((pos (point)))
23589 (org-element-swap-A-B prev-elem elem)
23590 (goto-char (+ (org-element-property :begin prev-elem)
23591 (- pos (org-element-property :begin elem)))))))))
23593 (defun org-drag-element-forward ()
23594 "Move forward element at point."
23595 (interactive)
23596 (let* ((pos (point))
23597 (elem (org-element-at-point)))
23598 (when (= (point-max) (org-element-property :end elem))
23599 (user-error "Cannot drag element forward"))
23600 (goto-char (org-element-property :end elem))
23601 (let ((next-elem (org-element-at-point)))
23602 (when (or (org-element-nested-p elem next-elem)
23603 (and (eq (org-element-type next-elem) 'headline)
23604 (not (eq (org-element-type elem) 'headline))))
23605 (goto-char pos)
23606 (user-error "Cannot drag element forward"))
23607 ;; Compute new position of point: it's shifted by NEXT-ELEM
23608 ;; body's length (without final blanks) and by the length of
23609 ;; blanks between ELEM and NEXT-ELEM.
23610 (let ((size-next (- (save-excursion
23611 (goto-char (org-element-property :end next-elem))
23612 (skip-chars-backward " \r\t\n")
23613 (forward-line)
23614 ;; Small correction if buffer doesn't end
23615 ;; with a newline character.
23616 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23617 (org-element-property :begin next-elem)))
23618 (size-blank (- (org-element-property :end elem)
23619 (save-excursion
23620 (goto-char (org-element-property :end elem))
23621 (skip-chars-backward " \r\t\n")
23622 (forward-line)
23623 (point)))))
23624 (org-element-swap-A-B elem next-elem)
23625 (goto-char (+ pos size-next size-blank))))))
23627 (defun org-drag-line-forward (arg)
23628 "Drag the line at point ARG lines forward."
23629 (interactive "p")
23630 (dotimes (n (abs arg))
23631 (let ((c (current-column)))
23632 (if (< 0 arg)
23633 (progn
23634 (beginning-of-line 2)
23635 (transpose-lines 1)
23636 (beginning-of-line 0))
23637 (transpose-lines 1)
23638 (beginning-of-line -1))
23639 (org-move-to-column c))))
23641 (defun org-drag-line-backward (arg)
23642 "Drag the line at point ARG lines backward."
23643 (interactive "p")
23644 (org-drag-line-forward (- arg)))
23646 (defun org-mark-element ()
23647 "Put point at beginning of this element, mark at end.
23649 Interactively, if this command is repeated or (in Transient Mark
23650 mode) if the mark is active, it marks the next element after the
23651 ones already marked."
23652 (interactive)
23653 (let (deactivate-mark)
23654 (if (and (org-called-interactively-p 'any)
23655 (or (and (eq last-command this-command) (mark t))
23656 (and transient-mark-mode mark-active)))
23657 (set-mark
23658 (save-excursion
23659 (goto-char (mark))
23660 (goto-char (org-element-property :end (org-element-at-point)))))
23661 (let ((element (org-element-at-point)))
23662 (end-of-line)
23663 (push-mark (org-element-property :end element) t t)
23664 (goto-char (org-element-property :begin element))))))
23666 (defun org-narrow-to-element ()
23667 "Narrow buffer to current element."
23668 (interactive)
23669 (let ((elem (org-element-at-point)))
23670 (cond
23671 ((eq (car elem) 'headline)
23672 (narrow-to-region
23673 (org-element-property :begin elem)
23674 (org-element-property :end elem)))
23675 ((memq (car elem) org-element-greater-elements)
23676 (narrow-to-region
23677 (org-element-property :contents-begin elem)
23678 (org-element-property :contents-end elem)))
23680 (narrow-to-region
23681 (org-element-property :begin elem)
23682 (org-element-property :end elem))))))
23684 (defun org-transpose-element ()
23685 "Transpose current and previous elements, keeping blank lines between.
23686 Point is moved after both elements."
23687 (interactive)
23688 (org-skip-whitespace)
23689 (let ((end (org-element-property :end (org-element-at-point))))
23690 (org-drag-element-backward)
23691 (goto-char end)))
23693 (defun org-unindent-buffer ()
23694 "Un-indent the visible part of the buffer.
23695 Relative indentation (between items, inside blocks, etc.) isn't
23696 modified."
23697 (interactive)
23698 (unless (eq major-mode 'org-mode)
23699 (user-error "Cannot un-indent a buffer not in Org mode"))
23700 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23701 unindent-tree ; For byte-compiler.
23702 (unindent-tree
23703 (function
23704 (lambda (contents)
23705 (mapc
23706 (lambda (element)
23707 (if (memq (org-element-type element) '(headline section))
23708 (funcall unindent-tree (org-element-contents element))
23709 (save-excursion
23710 (save-restriction
23711 (narrow-to-region
23712 (org-element-property :begin element)
23713 (org-element-property :end element))
23714 (org-do-remove-indentation)))))
23715 (reverse contents))))))
23716 (funcall unindent-tree (org-element-contents parse-tree))))
23718 (defun org-show-subtree ()
23719 "Show everything after this heading at deeper levels."
23720 (interactive)
23721 (outline-flag-region
23722 (point)
23723 (save-excursion
23724 (org-end-of-subtree t t))
23725 nil))
23727 (defun org-show-entry ()
23728 "Show the body directly following this heading.
23729 Show the heading too, if it is currently invisible."
23730 (interactive)
23731 (save-excursion
23732 (condition-case nil
23733 (progn
23734 (org-back-to-heading t)
23735 (outline-flag-region
23736 (max (point-min) (1- (point)))
23737 (save-excursion
23738 (if (re-search-forward
23739 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23740 (match-beginning 1)
23741 (point-max)))
23742 nil)
23743 (org-cycle-hide-drawers 'children))
23744 (error nil))))
23746 (defun org-make-options-regexp (kwds &optional extra)
23747 "Make a regular expression for keyword lines."
23748 (concat
23749 "^#\\+\\("
23750 (mapconcat 'regexp-quote kwds "\\|")
23751 (if extra (concat "\\|" extra))
23752 "\\):[ \t]*\\(.*\\)"))
23754 ;; Make isearch reveal the necessary context
23755 (defun org-isearch-end ()
23756 "Reveal context after isearch exits."
23757 (when isearch-success ; only if search was successful
23758 (if (featurep 'xemacs)
23759 ;; Under XEmacs, the hook is run in the correct place,
23760 ;; we directly show the context.
23761 (org-show-context 'isearch)
23762 ;; In Emacs the hook runs *before* restoring the overlays.
23763 ;; So we have to use a one-time post-command-hook to do this.
23764 ;; (Emacs 22 has a special variable, see function `org-mode')
23765 (unless (and (boundp 'isearch-mode-end-hook-quit)
23766 isearch-mode-end-hook-quit)
23767 ;; Only when the isearch was not quitted.
23768 (org-add-hook 'post-command-hook 'org-isearch-post-command
23769 'append 'local)))
23770 (org-fix-ellipsis-at-bol)))
23772 (defun org-isearch-post-command ()
23773 "Remove self from hook, and show context."
23774 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23775 (org-show-context 'isearch))
23778 ;;;; Integration with and fixes for other packages
23780 ;;; Imenu support
23782 (defvar org-imenu-markers nil
23783 "All markers currently used by Imenu.")
23784 (make-variable-buffer-local 'org-imenu-markers)
23786 (defun org-imenu-new-marker (&optional pos)
23787 "Return a new marker for use by Imenu, and remember the marker."
23788 (let ((m (make-marker)))
23789 (move-marker m (or pos (point)))
23790 (push m org-imenu-markers)
23793 (defun org-imenu-get-tree ()
23794 "Produce the index for Imenu."
23795 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23796 (setq org-imenu-markers nil)
23797 (let* ((n org-imenu-depth)
23798 (re (concat "^" (org-get-limited-outline-regexp)))
23799 (subs (make-vector (1+ n) nil))
23800 (last-level 0)
23801 m level head0 head)
23802 (save-excursion
23803 (save-restriction
23804 (widen)
23805 (goto-char (point-max))
23806 (while (re-search-backward re nil t)
23807 (setq level (org-reduced-level (funcall outline-level)))
23808 (when (and (<= level n)
23809 (looking-at org-complex-heading-regexp)
23810 (setq head0 (org-match-string-no-properties 4)))
23811 (setq head (org-link-display-format head0)
23812 m (org-imenu-new-marker))
23813 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23814 (if (>= level last-level)
23815 (push (cons head m) (aref subs level))
23816 (push (cons head (aref subs (1+ level))) (aref subs level))
23817 (loop for i from (1+ level) to n do (aset subs i nil)))
23818 (setq last-level level)))))
23819 (aref subs 1)))
23821 (eval-after-load "imenu"
23822 '(progn
23823 (add-hook 'imenu-after-jump-hook
23824 (lambda ()
23825 (if (derived-mode-p 'org-mode)
23826 (org-show-context 'org-goto))))))
23828 (defun org-link-display-format (link)
23829 "Replace a link with its the description.
23830 If there is no description, use the link target."
23831 (save-match-data
23832 (if (string-match org-bracket-link-analytic-regexp link)
23833 (replace-match (if (match-end 5)
23834 (match-string 5 link)
23835 (concat (match-string 1 link)
23836 (match-string 3 link)))
23837 nil t link)
23838 link)))
23840 (defun org-toggle-link-display ()
23841 "Toggle the literal or descriptive display of links."
23842 (interactive)
23843 (if org-descriptive-links
23844 (progn (org-remove-from-invisibility-spec '(org-link))
23845 (org-restart-font-lock)
23846 (setq org-descriptive-links nil))
23847 (progn (add-to-invisibility-spec '(org-link))
23848 (org-restart-font-lock)
23849 (setq org-descriptive-links t))))
23851 ;; Speedbar support
23853 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23854 "Overlay marking the agenda restriction line in speedbar.")
23855 (overlay-put org-speedbar-restriction-lock-overlay
23856 'face 'org-agenda-restriction-lock)
23857 (overlay-put org-speedbar-restriction-lock-overlay
23858 'help-echo "Agendas are currently limited to this item.")
23859 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23861 (defun org-speedbar-set-agenda-restriction ()
23862 "Restrict future agenda commands to the location at point in speedbar.
23863 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23864 (interactive)
23865 (require 'org-agenda)
23866 (let (p m tp np dir txt)
23867 (cond
23868 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23869 'org-imenu t))
23870 (setq m (get-text-property p 'org-imenu-marker))
23871 (with-current-buffer (marker-buffer m)
23872 (goto-char m)
23873 (org-agenda-set-restriction-lock 'subtree)))
23874 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23875 'speedbar-function 'speedbar-find-file))
23876 (setq tp (previous-single-property-change
23877 (1+ p) 'speedbar-function)
23878 np (next-single-property-change
23879 tp 'speedbar-function)
23880 dir (speedbar-line-directory)
23881 txt (buffer-substring-no-properties (or tp (point-min))
23882 (or np (point-max))))
23883 (with-current-buffer (find-file-noselect
23884 (let ((default-directory dir))
23885 (expand-file-name txt)))
23886 (unless (derived-mode-p 'org-mode)
23887 (user-error "Cannot restrict to non-Org-mode file"))
23888 (org-agenda-set-restriction-lock 'file)))
23889 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23890 (move-overlay org-speedbar-restriction-lock-overlay
23891 (point-at-bol) (point-at-eol))
23892 (setq current-prefix-arg nil)
23893 (org-agenda-maybe-redo)))
23895 (defvar speedbar-file-key-map)
23896 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23897 (eval-after-load "speedbar"
23898 '(progn
23899 (speedbar-add-supported-extension ".org")
23900 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23901 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23902 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23903 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23904 (add-hook 'speedbar-visiting-tag-hook
23905 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23907 ;;; Fixes and Hacks for problems with other packages
23909 ;; Make flyspell not check words in links, to not mess up our keymap
23910 (defvar org-element-affiliated-keywords) ; From org-element.el
23911 (defvar org-element-block-name-alist) ; From org-element.el
23912 (defun org-mode-flyspell-verify ()
23913 "Don't let flyspell put overlays at active buttons, or on
23914 {todo,all-time,additional-option-like}-keywords."
23915 (require 'org-element) ; For `org-element-affiliated-keywords'
23916 (let ((pos (max (1- (point)) (point-min)))
23917 (word (thing-at-point 'word)))
23918 (and (not (get-text-property pos 'keymap))
23919 (not (get-text-property pos 'org-no-flyspell))
23920 (not (member word org-todo-keywords-1))
23921 (not (member word org-all-time-keywords))
23922 (not (member word org-options-keywords))
23923 (not (member word (mapcar 'car org-startup-options)))
23924 (not (member-ignore-case word org-element-affiliated-keywords))
23925 (not (member-ignore-case word (org-get-export-keywords)))
23926 (not (member-ignore-case
23927 word (mapcar 'car org-element-block-name-alist)))
23928 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23929 (not (org-in-src-block-p)))))
23931 (defun org-remove-flyspell-overlays-in (beg end)
23932 "Remove flyspell overlays in region."
23933 (and (org-bound-and-true-p flyspell-mode)
23934 (fboundp 'flyspell-delete-region-overlays)
23935 (flyspell-delete-region-overlays beg end))
23936 (add-text-properties beg end '(org-no-flyspell t)))
23938 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23939 (eval-after-load "bookmark"
23940 '(if (boundp 'bookmark-after-jump-hook)
23941 ;; We can use the hook
23942 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23943 ;; Hook not available, use advice
23944 (defadvice bookmark-jump (after org-make-visible activate)
23945 "Make the position visible."
23946 (org-bookmark-jump-unhide))))
23948 ;; Make sure saveplace shows the location if it was hidden
23949 (eval-after-load "saveplace"
23950 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23951 "Make the position visible."
23952 (org-bookmark-jump-unhide)))
23954 ;; Make sure ecb shows the location if it was hidden
23955 (eval-after-load "ecb"
23956 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23957 "Make hierarchy visible when jumping into location from ECB tree buffer."
23958 (if (derived-mode-p 'org-mode)
23959 (org-show-context))))
23961 (defun org-bookmark-jump-unhide ()
23962 "Unhide the current position, to show the bookmark location."
23963 (and (derived-mode-p 'org-mode)
23964 (or (outline-invisible-p)
23965 (save-excursion (goto-char (max (point-min) (1- (point))))
23966 (outline-invisible-p)))
23967 (org-show-context 'bookmark-jump)))
23969 ;; Make session.el ignore our circular variable
23970 (defvar session-globals-exclude)
23971 (eval-after-load "session"
23972 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23974 ;;;; Finish up
23976 (provide 'org)
23978 (run-hooks 'org-load-hook)
23980 ;;; org.el ends here