LaTeX: Use \ul (from the "soul" package) instead of \uline
[org-mode/org-kjn.git] / lisp / org.el
blob4bddb7cf28c90bb2d4142a966e6a445b33973eac
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 ("" "soul" t)
3847 ("" "amsmath" t)
3848 ("" "textcomp" t)
3849 ("" "marvosym" t)
3850 ("" "wasysym" t)
3851 ("" "amssymb" t)
3852 ("" "hyperref" nil)
3853 "\\tolerance=1000")
3854 "Alist of default packages to be inserted in the header.
3856 Change this only if one of the packages here causes an
3857 incompatibility with another package you are using.
3859 The packages in this list are needed by one part or another of
3860 Org mode to function properly:
3862 - inputenc, fontenc: for basic font and character selection
3863 - fixltx2e: Important patches of LaTeX itself
3864 - graphicx: for including images
3865 - longtable: For multipage tables
3866 - float, wrapfig: for figure placement
3867 - rotating: for sideways figures and tables
3868 - ulem: for underline and strike-through
3869 - amsmath: for subscript and superscript and math environments
3870 - textcomp, marvosymb, wasysym, amssymb: for various symbols used
3871 for interpreting the entities in `org-entities'. You can skip
3872 some of these packages if you don't use any of their symbols.
3873 - hyperref: for cross references
3875 Therefore you should not modify this variable unless you know
3876 what you are doing. The one reason to change it anyway is that
3877 you might be loading some other package that conflicts with one
3878 of the default packages. Each cell is of the format
3879 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3880 the package also needs to be included when compiling LaTeX
3881 snippets into images for inclusion into non-LaTeX output."
3882 :group 'org-latex
3883 :group 'org-export-latex
3884 :set 'org-set-packages-alist
3885 :get 'org-get-packages-alist
3886 :version "24.1"
3887 :type '(repeat
3888 (choice
3889 (list :tag "options/package pair"
3890 (string :tag "options")
3891 (string :tag "package")
3892 (boolean :tag "Snippet"))
3893 (string :tag "A line of LaTeX"))))
3895 (defcustom org-latex-packages-alist nil
3896 "Alist of packages to be inserted in every LaTeX header.
3898 These will be inserted after `org-latex-default-packages-alist'.
3899 Each cell is of the format:
3901 \(\"options\" \"package\" snippet-flag)
3903 SNIPPET-FLAG, when t, indicates that this package is also needed
3904 when turning LaTeX snippets into images for inclusion into
3905 non-LaTeX output.
3907 Make sure that you only list packages here which:
3909 - you want in every file
3910 - do not conflict with the setup in `org-format-latex-header'.
3911 - do not conflict with the default packages in
3912 `org-latex-default-packages-alist'."
3913 :group 'org-latex
3914 :group 'org-export-latex
3915 :set 'org-set-packages-alist
3916 :get 'org-get-packages-alist
3917 :type '(repeat
3918 (choice
3919 (list :tag "options/package pair"
3920 (string :tag "options")
3921 (string :tag "package")
3922 (boolean :tag "Snippet"))
3923 (string :tag "A line of LaTeX"))))
3925 (defgroup org-appearance nil
3926 "Settings for Org-mode appearance."
3927 :tag "Org Appearance"
3928 :group 'org)
3930 (defcustom org-level-color-stars-only nil
3931 "Non-nil means fontify only the stars in each headline.
3932 When nil, the entire headline is fontified.
3933 Changing it requires restart of `font-lock-mode' to become effective
3934 also in regions already fontified."
3935 :group 'org-appearance
3936 :type 'boolean)
3938 (defcustom org-hide-leading-stars nil
3939 "Non-nil means hide the first N-1 stars in a headline.
3940 This works by using the face `org-hide' for these stars. This
3941 face is white for a light background, and black for a dark
3942 background. You may have to customize the face `org-hide' to
3943 make this work.
3944 Changing it requires restart of `font-lock-mode' to become effective
3945 also in regions already fontified.
3946 You may also set this on a per-file basis by adding one of the following
3947 lines to the buffer:
3949 #+STARTUP: hidestars
3950 #+STARTUP: showstars"
3951 :group 'org-appearance
3952 :type 'boolean)
3954 (defcustom org-hidden-keywords nil
3955 "List of symbols corresponding to keywords to be hidden the org buffer.
3956 For example, a value '(title) for this list will make the document's title
3957 appear in the buffer without the initial #+TITLE: keyword."
3958 :group 'org-appearance
3959 :version "24.1"
3960 :type '(set (const :tag "#+AUTHOR" author)
3961 (const :tag "#+DATE" date)
3962 (const :tag "#+EMAIL" email)
3963 (const :tag "#+TITLE" title)))
3965 (defcustom org-custom-properties nil
3966 "List of properties (as strings) with a special meaning.
3967 The default use of these custom properties is to let the user
3968 hide them with `org-toggle-custom-properties-visibility'."
3969 :group 'org-properties
3970 :group 'org-appearance
3971 :version "24.3"
3972 :type '(repeat (string :tag "Property Name")))
3974 (defcustom org-fontify-done-headline nil
3975 "Non-nil means change the face of a headline if it is marked DONE.
3976 Normally, only the TODO/DONE keyword indicates the state of a headline.
3977 When this is non-nil, the headline after the keyword is set to the
3978 `org-headline-done' as an additional indication."
3979 :group 'org-appearance
3980 :type 'boolean)
3982 (defcustom org-fontify-emphasized-text t
3983 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3984 Changing this variable requires a restart of Emacs to take effect."
3985 :group 'org-appearance
3986 :type 'boolean)
3988 (defcustom org-fontify-whole-heading-line nil
3989 "Non-nil means fontify the whole line for headings.
3990 This is useful when setting a background color for the
3991 org-level-* faces."
3992 :group 'org-appearance
3993 :type 'boolean)
3995 (defcustom org-highlight-latex-and-related nil
3996 "Non-nil means highlight LaTeX related syntax in the buffer.
3997 When non nil, the value should be a list containing any of the
3998 following symbols:
3999 `latex' Highlight LaTeX snippets and environments.
4000 `script' Highlight subscript and superscript.
4001 `entities' Highlight entities."
4002 :group 'org-appearance
4003 :version "24.4"
4004 :package-version '(Org . "8.0")
4005 :type '(choice
4006 (const :tag "No highlighting" nil)
4007 (set :greedy t :tag "Highlight"
4008 (const :tag "LaTeX snippets and environments" latex)
4009 (const :tag "Subscript and superscript" script)
4010 (const :tag "Entities" entities))))
4012 (defcustom org-hide-emphasis-markers nil
4013 "Non-nil mean font-lock should hide the emphasis marker characters."
4014 :group 'org-appearance
4015 :type 'boolean)
4017 (defcustom org-pretty-entities nil
4018 "Non-nil means show entities as UTF8 characters.
4019 When nil, the \\name form remains in the buffer."
4020 :group 'org-appearance
4021 :version "24.1"
4022 :type 'boolean)
4024 (defcustom org-pretty-entities-include-sub-superscripts t
4025 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4026 :group 'org-appearance
4027 :version "24.1"
4028 :type 'boolean)
4030 (defvar org-emph-re nil
4031 "Regular expression for matching emphasis.
4032 After a match, the match groups contain these elements:
4033 0 The match of the full regular expression, including the characters
4034 before and after the proper match
4035 1 The character before the proper match, or empty at beginning of line
4036 2 The proper match, including the leading and trailing markers
4037 3 The leading marker like * or /, indicating the type of highlighting
4038 4 The text between the emphasis markers, not including the markers
4039 5 The character after the match, empty at the end of a line")
4040 (defvar org-verbatim-re nil
4041 "Regular expression for matching verbatim text.")
4042 (defvar org-emphasis-regexp-components) ; defined just below
4043 (defvar org-emphasis-alist) ; defined just below
4044 (defun org-set-emph-re (var val)
4045 "Set variable and compute the emphasis regular expression."
4046 (set var val)
4047 (when (and (boundp 'org-emphasis-alist)
4048 (boundp 'org-emphasis-regexp-components)
4049 org-emphasis-alist org-emphasis-regexp-components)
4050 (let* ((e org-emphasis-regexp-components)
4051 (pre (car e))
4052 (post (nth 1 e))
4053 (border (nth 2 e))
4054 (body (nth 3 e))
4055 (nl (nth 4 e))
4056 (body1 (concat body "*?"))
4057 (markers (mapconcat 'car org-emphasis-alist ""))
4058 (vmarkers (mapconcat
4059 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4060 org-emphasis-alist "")))
4061 ;; make sure special characters appear at the right position in the class
4062 (if (string-match "\\^" markers)
4063 (setq markers (concat (replace-match "" t t markers) "^")))
4064 (if (string-match "-" markers)
4065 (setq markers (concat (replace-match "" t t markers) "-")))
4066 (if (string-match "\\^" vmarkers)
4067 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4068 (if (string-match "-" vmarkers)
4069 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4070 (if (> nl 0)
4071 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4072 (int-to-string nl) "\\}")))
4073 ;; Make the regexp
4074 (setq org-emph-re
4075 (concat "\\([" pre "]\\|^\\)"
4076 "\\("
4077 "\\([" markers "]\\)"
4078 "\\("
4079 "[^" border "]\\|"
4080 "[^" border "]"
4081 body1
4082 "[^" border "]"
4083 "\\)"
4084 "\\3\\)"
4085 "\\([" post "]\\|$\\)"))
4086 (setq org-verbatim-re
4087 (concat "\\([" pre "]\\|^\\)"
4088 "\\("
4089 "\\([" vmarkers "]\\)"
4090 "\\("
4091 "[^" border "]\\|"
4092 "[^" border "]"
4093 body1
4094 "[^" border "]"
4095 "\\)"
4096 "\\3\\)"
4097 "\\([" post "]\\|$\\)")))))
4099 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4100 ;; set this option proved cumbersome. See this message/thread:
4101 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4102 (defvar org-emphasis-regexp-components
4103 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4104 "Components used to build the regular expression for emphasis.
4105 This is a list with five entries. Terminology: In an emphasis string
4106 like \" *strong word* \", we call the initial space PREMATCH, the final
4107 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4108 and \"trong wor\" is the body. The different components in this variable
4109 specify what is allowed/forbidden in each part:
4111 pre Chars allowed as prematch. Beginning of line will be allowed too.
4112 post Chars allowed as postmatch. End of line will be allowed too.
4113 border The chars *forbidden* as border characters.
4114 body-regexp A regexp like \".\" to match a body character. Don't use
4115 non-shy groups here, and don't allow newline here.
4116 newline The maximum number of newlines allowed in an emphasis exp.
4118 You need to reload Org or to restart Emacs after customizing this.")
4120 (defcustom org-emphasis-alist
4121 `(("*" bold)
4122 ("/" italic)
4123 ("_" underline)
4124 ("=" org-verbatim verbatim)
4125 ("~" org-code verbatim)
4126 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4127 "Alist of characters and faces to emphasize text.
4128 Text starting and ending with a special character will be emphasized,
4129 for example *bold*, _underlined_ and /italic/. This variable sets the
4130 marker characters and the face to be used by font-lock for highlighting
4131 in Org-mode Emacs buffers.
4133 You need to reload Org or to restart Emacs after customizing this."
4134 :group 'org-appearance
4135 :set 'org-set-emph-re
4136 :version "24.4"
4137 :package-version '(Org . "8.0")
4138 :type '(repeat
4139 (list
4140 (string :tag "Marker character")
4141 (choice
4142 (face :tag "Font-lock-face")
4143 (plist :tag "Face property list"))
4144 (option (const verbatim)))))
4146 (defvar org-protecting-blocks
4147 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4148 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4149 This is needed for font-lock setup.")
4151 ;;; Miscellaneous options
4153 (defgroup org-completion nil
4154 "Completion in Org-mode."
4155 :tag "Org Completion"
4156 :group 'org)
4158 (defcustom org-completion-use-ido nil
4159 "Non-nil means use ido completion wherever possible.
4160 Note that `ido-mode' must be active for this variable to be relevant.
4161 If you decide to turn this variable on, you might well want to turn off
4162 `org-outline-path-complete-in-steps'.
4163 See also `org-completion-use-iswitchb'."
4164 :group 'org-completion
4165 :type 'boolean)
4167 (defcustom org-completion-use-iswitchb nil
4168 "Non-nil means use iswitchb completion wherever possible.
4169 Note that `iswitchb-mode' must be active for this variable to be relevant.
4170 If you decide to turn this variable on, you might well want to turn off
4171 `org-outline-path-complete-in-steps'.
4172 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4173 :group 'org-completion
4174 :type 'boolean)
4176 (defcustom org-completion-fallback-command 'hippie-expand
4177 "The expansion command called by \\[pcomplete] in normal context.
4178 Normal means, no org-mode-specific context."
4179 :group 'org-completion
4180 :type 'function)
4182 ;;; Functions and variables from their packages
4183 ;; Declared here to avoid compiler warnings
4185 ;; XEmacs only
4186 (defvar outline-mode-menu-heading)
4187 (defvar outline-mode-menu-show)
4188 (defvar outline-mode-menu-hide)
4189 (defvar zmacs-regions) ; XEmacs regions
4191 ;; Emacs only
4192 (defvar mark-active)
4194 ;; Various packages
4195 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4196 (declare-function calendar-forward-day "cal-move" (arg))
4197 (declare-function calendar-goto-date "cal-move" (date))
4198 (declare-function calendar-goto-today "cal-move" ())
4199 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4200 (defvar calc-embedded-close-formula)
4201 (defvar calc-embedded-open-formula)
4202 (declare-function cdlatex-tab "ext:cdlatex" ())
4203 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4204 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4205 (defvar font-lock-unfontify-region-function)
4206 (declare-function iswitchb-read-buffer "iswitchb"
4207 (prompt &optional default require-match start matches-set))
4208 (defvar iswitchb-temp-buflist)
4209 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4210 (defvar org-agenda-tags-todo-honor-ignore-options)
4211 (declare-function org-agenda-skip "org-agenda" ())
4212 (declare-function
4213 org-agenda-format-item "org-agenda"
4214 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4215 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4216 (declare-function org-agenda-change-all-lines "org-agenda"
4217 (newhead hdmarker &optional fixface just-this))
4218 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4219 (declare-function org-agenda-maybe-redo "org-agenda" ())
4220 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4221 (beg end))
4222 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4223 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4224 "org-agenda" (&optional end))
4225 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4226 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4227 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4228 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4229 (declare-function org-indent-mode "org-indent" (&optional arg))
4230 (declare-function parse-time-string "parse-time" (string))
4231 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4232 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4233 (defvar remember-data-file)
4234 (defvar texmathp-why)
4235 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4236 (declare-function table--at-cell-p "table" (position &optional object at-column))
4238 (defvar org-latex-regexps)
4240 ;;; Autoload and prepare some org modules
4242 ;; Some table stuff that needs to be defined here, because it is used
4243 ;; by the functions setting up org-mode or checking for table context.
4245 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4246 "Detect an org-type or table-type table.")
4247 (defconst org-table-line-regexp "^[ \t]*|"
4248 "Detect an org-type table line.")
4249 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4250 "Detect an org-type table line.")
4251 (defconst org-table-hline-regexp "^[ \t]*|-"
4252 "Detect an org-type table hline.")
4253 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4254 "Detect a table-type table hline.")
4255 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4256 "Detect the first line outside a table when searching from within it.
4257 This works for both table types.")
4259 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4260 "Detect a #+TBLFM line.")
4262 ;;;###autoload
4263 (defun turn-on-orgtbl ()
4264 "Unconditionally turn on `orgtbl-mode'."
4265 (require 'org-table)
4266 (orgtbl-mode 1))
4268 (defun org-at-table-p (&optional table-type)
4269 "Return t if the cursor is inside an org-type table.
4270 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4271 (if org-enable-table-editor
4272 (save-excursion
4273 (beginning-of-line 1)
4274 (looking-at (if table-type org-table-any-line-regexp
4275 org-table-line-regexp)))
4276 nil))
4277 (defsubst org-table-p () (org-at-table-p))
4279 (defun org-at-table.el-p ()
4280 "Return t if and only if we are at a table.el table."
4281 (and (org-at-table-p 'any)
4282 (save-excursion
4283 (goto-char (org-table-begin 'any))
4284 (looking-at org-table1-hline-regexp))))
4286 (defun org-table-recognize-table.el ()
4287 "If there is a table.el table nearby, recognize it and move into it."
4288 (if org-table-tab-recognizes-table.el
4289 (if (org-at-table.el-p)
4290 (progn
4291 (beginning-of-line 1)
4292 (if (looking-at org-table-dataline-regexp)
4294 (if (looking-at org-table1-hline-regexp)
4295 (progn
4296 (beginning-of-line 2)
4297 (if (looking-at org-table-any-border-regexp)
4298 (beginning-of-line -1)))))
4299 (if (re-search-forward "|" (org-table-end t) t)
4300 (progn
4301 (require 'table)
4302 (if (table--at-cell-p (point))
4304 (message "recognizing table.el table...")
4305 (table-recognize-table)
4306 (message "recognizing table.el table...done")))
4307 (error "This should not happen"))
4309 nil)
4310 nil))
4312 (defun org-at-table-hline-p ()
4313 "Return t if the cursor is inside a hline in a table."
4314 (if org-enable-table-editor
4315 (save-excursion
4316 (beginning-of-line 1)
4317 (looking-at org-table-hline-regexp))
4318 nil))
4320 (defun org-table-map-tables (function &optional quietly)
4321 "Apply FUNCTION to the start of all tables in the buffer."
4322 (save-excursion
4323 (save-restriction
4324 (widen)
4325 (goto-char (point-min))
4326 (while (re-search-forward org-table-any-line-regexp nil t)
4327 (unless quietly
4328 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4329 (beginning-of-line 1)
4330 (when (and (looking-at org-table-line-regexp)
4331 ;; Exclude tables in src/example/verbatim/clocktable blocks
4332 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4333 (save-excursion (funcall function))
4334 (or (looking-at org-table-line-regexp)
4335 (forward-char 1)))
4336 (re-search-forward org-table-any-border-regexp nil 1))))
4337 (unless quietly (message "Mapping tables: done")))
4339 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4340 (declare-function org-clock-update-mode-line "org-clock" ())
4341 (declare-function org-resolve-clocks "org-clock"
4342 (&optional also-non-dangling-p prompt last-valid))
4344 (defun org-at-TBLFM-p (&optional pos)
4345 "Return t when point (or POS) is in #+TBLFM line."
4346 (save-excursion
4347 (let ((pos pos)))
4348 (goto-char (or pos (point)))
4349 (beginning-of-line 1)
4350 (looking-at org-TBLFM-regexp)))
4352 (defvar org-clock-start-time)
4353 (defvar org-clock-marker (make-marker)
4354 "Marker recording the last clock-in.")
4355 (defvar org-clock-hd-marker (make-marker)
4356 "Marker recording the last clock-in, but the headline position.")
4357 (defvar org-clock-heading ""
4358 "The heading of the current clock entry.")
4359 (defun org-clock-is-active ()
4360 "Return the buffer where the clock is currently running.
4361 Return nil if no clock is running."
4362 (marker-buffer org-clock-marker))
4364 (defun org-check-running-clock ()
4365 "Check if the current buffer contains the running clock.
4366 If yes, offer to stop it and to save the buffer with the changes."
4367 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4368 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4369 (buffer-name))))
4370 (org-clock-out)
4371 (when (y-or-n-p "Save changed buffer?")
4372 (save-buffer))))
4374 (defun org-clocktable-try-shift (dir n)
4375 "Check if this line starts a clock table, if yes, shift the time block."
4376 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4377 (org-clocktable-shift dir n)))
4379 ;;;###autoload
4380 (defun org-clock-persistence-insinuate ()
4381 "Set up hooks for clock persistence."
4382 (require 'org-clock)
4383 (add-hook 'org-mode-hook 'org-clock-load)
4384 (add-hook 'kill-emacs-hook 'org-clock-save))
4386 (defgroup org-archive nil
4387 "Options concerning archiving in Org-mode."
4388 :tag "Org Archive"
4389 :group 'org-structure)
4391 (defcustom org-archive-location "%s_archive::"
4392 "The location where subtrees should be archived.
4394 The value of this variable is a string, consisting of two parts,
4395 separated by a double-colon. The first part is a filename and
4396 the second part is a headline.
4398 When the filename is omitted, archiving happens in the same file.
4399 %s in the filename will be replaced by the current file
4400 name (without the directory part). Archiving to a different file
4401 is useful to keep archived entries from contributing to the
4402 Org-mode Agenda.
4404 The archived entries will be filed as subtrees of the specified
4405 headline. When the headline is omitted, the subtrees are simply
4406 filed away at the end of the file, as top-level entries. Also in
4407 the heading you can use %s to represent the file name, this can be
4408 useful when using the same archive for a number of different files.
4410 Here are a few examples:
4411 \"%s_archive::\"
4412 If the current file is Projects.org, archive in file
4413 Projects.org_archive, as top-level trees. This is the default.
4415 \"::* Archived Tasks\"
4416 Archive in the current file, under the top-level headline
4417 \"* Archived Tasks\".
4419 \"~/org/archive.org::\"
4420 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4422 \"~/org/archive.org::* From %s\"
4423 Archive in file ~/org/archive.org (absolute path), under headlines
4424 \"From FILENAME\" where file name is the current file name.
4426 \"~/org/datetree.org::datetree/* Finished Tasks\"
4427 The \"datetree/\" string is special, signifying to archive
4428 items to the datetree. Items are placed in either the CLOSED
4429 date of the item, or the current date if there is no CLOSED date.
4430 The heading will be a subentry to the current date. There doesn't
4431 need to be a heading, but there always needs to be a slash after
4432 datetree. For example, to store archived items directly in the
4433 datetree, use \"~/org/datetree.org::datetree/\".
4435 \"basement::** Finished Tasks\"
4436 Archive in file ./basement (relative path), as level 3 trees
4437 below the level 2 heading \"** Finished Tasks\".
4439 You may set this option on a per-file basis by adding to the buffer a
4440 line like
4442 #+ARCHIVE: basement::** Finished Tasks
4444 You may also define it locally for a subtree by setting an ARCHIVE property
4445 in the entry. If such a property is found in an entry, or anywhere up
4446 the hierarchy, it will be used."
4447 :group 'org-archive
4448 :type 'string)
4450 (defcustom org-archive-tag "ARCHIVE"
4451 "The tag that marks a subtree as archived.
4452 An archived subtree does not open during visibility cycling, and does
4453 not contribute to the agenda listings.
4454 After changing this, font-lock must be restarted in the relevant buffers to
4455 get the proper fontification."
4456 :group 'org-archive
4457 :group 'org-keywords
4458 :type 'string)
4460 (defcustom org-agenda-skip-archived-trees t
4461 "Non-nil means the agenda will skip any items located in archived trees.
4462 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4463 variable is no longer recommended, you should leave it at the value t.
4464 Instead, use the key `v' to cycle the archives-mode in the agenda."
4465 :group 'org-archive
4466 :group 'org-agenda-skip
4467 :type 'boolean)
4469 (defcustom org-columns-skip-archived-trees t
4470 "Non-nil means ignore archived trees when creating column view."
4471 :group 'org-archive
4472 :group 'org-properties
4473 :type 'boolean)
4475 (defcustom org-cycle-open-archived-trees nil
4476 "Non-nil means `org-cycle' will open archived trees.
4477 An archived tree is a tree marked with the tag ARCHIVE.
4478 When nil, archived trees will stay folded. You can still open them with
4479 normal outline commands like `show-all', but not with the cycling commands."
4480 :group 'org-archive
4481 :group 'org-cycle
4482 :type 'boolean)
4484 (defcustom org-sparse-tree-open-archived-trees nil
4485 "Non-nil means sparse tree construction shows matches in archived trees.
4486 When nil, matches in these trees are highlighted, but the trees are kept in
4487 collapsed state."
4488 :group 'org-archive
4489 :group 'org-sparse-trees
4490 :type 'boolean)
4492 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4493 "The default date type when building a sparse tree.
4494 When this is nil, a date is a scheduled or a deadline timestamp.
4495 Otherwise, these types are allowed:
4497 all: all timestamps
4498 active: only active timestamps (<...>)
4499 inactive: only inactive timestamps (<...)
4500 scheduled: only scheduled timestamps
4501 deadline: only deadline timestamps"
4502 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4503 (const :tag "All timestamps" all)
4504 (const :tag "Only active timestamps" active)
4505 (const :tag "Only inactive timestamps" inactive)
4506 (const :tag "Only scheduled timestamps" scheduled)
4507 (const :tag "Only deadline timestamps" deadline)
4508 (const :tag "Only closed timestamps" closed))
4509 :version "24.3"
4510 :group 'org-sparse-trees)
4512 (defun org-cycle-hide-archived-subtrees (state)
4513 "Re-hide all archived subtrees after a visibility state change."
4514 (when (and (not org-cycle-open-archived-trees)
4515 (not (memq state '(overview folded))))
4516 (save-excursion
4517 (let* ((globalp (memq state '(contents all)))
4518 (beg (if globalp (point-min) (point)))
4519 (end (if globalp (point-max) (org-end-of-subtree t))))
4520 (org-hide-archived-subtrees beg end)
4521 (goto-char beg)
4522 (if (looking-at (concat ".*:" org-archive-tag ":"))
4523 (message "%s" (substitute-command-keys
4524 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4526 (defun org-force-cycle-archived ()
4527 "Cycle subtree even if it is archived."
4528 (interactive)
4529 (setq this-command 'org-cycle)
4530 (let ((org-cycle-open-archived-trees t))
4531 (call-interactively 'org-cycle)))
4533 (defun org-hide-archived-subtrees (beg end)
4534 "Re-hide all archived subtrees after a visibility state change."
4535 (save-excursion
4536 (let* ((re (concat ":" org-archive-tag ":")))
4537 (goto-char beg)
4538 (while (re-search-forward re end t)
4539 (when (org-at-heading-p)
4540 (org-flag-subtree t)
4541 (org-end-of-subtree t))))))
4543 (declare-function outline-end-of-heading "outline" ())
4544 (declare-function outline-flag-region "outline" (from to flag))
4545 (defun org-flag-subtree (flag)
4546 (save-excursion
4547 (org-back-to-heading t)
4548 (outline-end-of-heading)
4549 (outline-flag-region (point)
4550 (progn (org-end-of-subtree t) (point))
4551 flag)))
4553 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4555 ;; Declare Column View Code
4557 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4558 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4559 (declare-function org-columns-compute "org-colview" (property))
4561 ;; Declare ID code
4563 (declare-function org-id-store-link "org-id")
4564 (declare-function org-id-locations-load "org-id")
4565 (declare-function org-id-locations-save "org-id")
4566 (defvar org-id-track-globally)
4568 ;;; Variables for pre-computed regular expressions, all buffer local
4570 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4571 "Matches first line of a hidden block.")
4572 (make-variable-buffer-local 'org-drawer-regexp)
4573 (defvar org-todo-regexp nil
4574 "Matches any of the TODO state keywords.")
4575 (make-variable-buffer-local 'org-todo-regexp)
4576 (defvar org-not-done-regexp nil
4577 "Matches any of the TODO state keywords except the last one.")
4578 (make-variable-buffer-local 'org-not-done-regexp)
4579 (defvar org-not-done-heading-regexp nil
4580 "Matches a TODO headline that is not done.")
4581 (make-variable-buffer-local 'org-not-done-regexp)
4582 (defvar org-todo-line-regexp nil
4583 "Matches a headline and puts TODO state into group 2 if present.")
4584 (make-variable-buffer-local 'org-todo-line-regexp)
4585 (defvar org-complex-heading-regexp nil
4586 "Matches a headline and puts everything into groups:
4587 group 1: the stars
4588 group 2: The todo keyword, maybe
4589 group 3: Priority cookie
4590 group 4: True headline
4591 group 5: Tags")
4592 (make-variable-buffer-local 'org-complex-heading-regexp)
4593 (defvar org-complex-heading-regexp-format nil
4594 "Printf format to make regexp to match an exact headline.
4595 This regexp will match the headline of any node which has the
4596 exact headline text that is put into the format, but may have any
4597 TODO state, priority and tags.")
4598 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4599 (defvar org-todo-line-tags-regexp nil
4600 "Matches a headline and puts TODO state into group 2 if present.
4601 Also put tags into group 4 if tags are present.")
4602 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4603 (defvar org-ds-keyword-length 12
4604 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4605 (make-variable-buffer-local 'org-ds-keyword-length)
4606 (defvar org-deadline-regexp nil
4607 "Matches the DEADLINE keyword.")
4608 (make-variable-buffer-local 'org-deadline-regexp)
4609 (defvar org-deadline-time-regexp nil
4610 "Matches the DEADLINE keyword together with a time stamp.")
4611 (make-variable-buffer-local 'org-deadline-time-regexp)
4612 (defvar org-deadline-time-hour-regexp nil
4613 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4614 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4615 (defvar org-deadline-line-regexp nil
4616 "Matches the DEADLINE keyword and the rest of the line.")
4617 (make-variable-buffer-local 'org-deadline-line-regexp)
4618 (defvar org-scheduled-regexp nil
4619 "Matches the SCHEDULED keyword.")
4620 (make-variable-buffer-local 'org-scheduled-regexp)
4621 (defvar org-scheduled-time-regexp nil
4622 "Matches the SCHEDULED keyword together with a time stamp.")
4623 (make-variable-buffer-local 'org-scheduled-time-regexp)
4624 (defvar org-scheduled-time-hour-regexp nil
4625 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4626 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4627 (defvar org-closed-time-regexp nil
4628 "Matches the CLOSED keyword together with a time stamp.")
4629 (make-variable-buffer-local 'org-closed-time-regexp)
4631 (defvar org-keyword-time-regexp nil
4632 "Matches any of the 4 keywords, together with the time stamp.")
4633 (make-variable-buffer-local 'org-keyword-time-regexp)
4634 (defvar org-keyword-time-not-clock-regexp nil
4635 "Matches any of the 3 keywords, together with the time stamp.")
4636 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4637 (defvar org-maybe-keyword-time-regexp nil
4638 "Matches a timestamp, possibly preceded by a keyword.")
4639 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4640 (defvar org-all-time-keywords nil
4641 "List of time keywords.")
4642 (make-variable-buffer-local 'org-all-time-keywords)
4644 (defconst org-plain-time-of-day-regexp
4645 (concat
4646 "\\(\\<[012]?[0-9]"
4647 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4648 "\\(--?"
4649 "\\(\\<[012]?[0-9]"
4650 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4651 "\\)?")
4652 "Regular expression to match a plain time or time range.
4653 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4654 groups carry important information:
4655 0 the full match
4656 1 the first time, range or not
4657 8 the second time, if it is a range.")
4659 (defconst org-plain-time-extension-regexp
4660 (concat
4661 "\\(\\<[012]?[0-9]"
4662 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4663 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4664 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4665 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4666 groups carry important information:
4667 0 the full match
4668 7 hours of duration
4669 9 minutes of duration")
4671 (defconst org-stamp-time-of-day-regexp
4672 (concat
4673 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4674 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4675 "\\(--?"
4676 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4677 "Regular expression to match a timestamp time or time range.
4678 After a match, the following groups carry important information:
4679 0 the full match
4680 1 date plus weekday, for back referencing to make sure both times are on the same day
4681 2 the first time, range or not
4682 4 the second time, if it is a range.")
4684 (defconst org-startup-options
4685 '(("fold" org-startup-folded t)
4686 ("overview" org-startup-folded t)
4687 ("nofold" org-startup-folded nil)
4688 ("showall" org-startup-folded nil)
4689 ("showeverything" org-startup-folded showeverything)
4690 ("content" org-startup-folded content)
4691 ("indent" org-startup-indented t)
4692 ("noindent" org-startup-indented nil)
4693 ("hidestars" org-hide-leading-stars t)
4694 ("showstars" org-hide-leading-stars nil)
4695 ("odd" org-odd-levels-only t)
4696 ("oddeven" org-odd-levels-only nil)
4697 ("align" org-startup-align-all-tables t)
4698 ("noalign" org-startup-align-all-tables nil)
4699 ("inlineimages" org-startup-with-inline-images t)
4700 ("noinlineimages" org-startup-with-inline-images nil)
4701 ("latexpreview" org-startup-with-latex-preview t)
4702 ("nolatexpreview" org-startup-with-latex-preview nil)
4703 ("customtime" org-display-custom-times t)
4704 ("logdone" org-log-done time)
4705 ("lognotedone" org-log-done note)
4706 ("nologdone" org-log-done nil)
4707 ("lognoteclock-out" org-log-note-clock-out t)
4708 ("nolognoteclock-out" org-log-note-clock-out nil)
4709 ("logrepeat" org-log-repeat state)
4710 ("lognoterepeat" org-log-repeat note)
4711 ("logdrawer" org-log-into-drawer t)
4712 ("nologdrawer" org-log-into-drawer nil)
4713 ("logstatesreversed" org-log-states-order-reversed t)
4714 ("nologstatesreversed" org-log-states-order-reversed nil)
4715 ("nologrepeat" org-log-repeat nil)
4716 ("logreschedule" org-log-reschedule time)
4717 ("lognotereschedule" org-log-reschedule note)
4718 ("nologreschedule" org-log-reschedule nil)
4719 ("logredeadline" org-log-redeadline time)
4720 ("lognoteredeadline" org-log-redeadline note)
4721 ("nologredeadline" org-log-redeadline nil)
4722 ("logrefile" org-log-refile time)
4723 ("lognoterefile" org-log-refile note)
4724 ("nologrefile" org-log-refile nil)
4725 ("fninline" org-footnote-define-inline t)
4726 ("nofninline" org-footnote-define-inline nil)
4727 ("fnlocal" org-footnote-section nil)
4728 ("fnauto" org-footnote-auto-label t)
4729 ("fnprompt" org-footnote-auto-label nil)
4730 ("fnconfirm" org-footnote-auto-label confirm)
4731 ("fnplain" org-footnote-auto-label plain)
4732 ("fnadjust" org-footnote-auto-adjust t)
4733 ("nofnadjust" org-footnote-auto-adjust nil)
4734 ("constcgs" constants-unit-system cgs)
4735 ("constSI" constants-unit-system SI)
4736 ("noptag" org-tag-persistent-alist nil)
4737 ("hideblocks" org-hide-block-startup t)
4738 ("nohideblocks" org-hide-block-startup nil)
4739 ("beamer" org-startup-with-beamer-mode t)
4740 ("entitiespretty" org-pretty-entities t)
4741 ("entitiesplain" org-pretty-entities nil))
4742 "Variable associated with STARTUP options for org-mode.
4743 Each element is a list of three items: the startup options (as written
4744 in the #+STARTUP line), the corresponding variable, and the value to set
4745 this variable to if the option is found. An optional forth element PUSH
4746 means to push this value onto the list in the variable.")
4748 (defun org-update-property-plist (key val props)
4749 "Update PROPS with KEY and VAL."
4750 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4751 (key (if appending (substring key 0 (- (length key) 1)) key))
4752 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4753 (previous (cdr (assoc key props))))
4754 (if appending
4755 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4756 (cons (cons key val) remainder))))
4758 (defconst org-block-regexp
4759 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4760 "Regular expression for hiding blocks.")
4761 (defconst org-heading-keyword-regexp-format
4762 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4763 "Printf format for a regexp matching a headline with some keyword.
4764 This regexp will match the headline of any node which has the
4765 exact keyword that is put into the format. The keyword isn't in
4766 any group by default, but the stars and the body are.")
4767 (defconst org-heading-keyword-maybe-regexp-format
4768 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4769 "Printf format for a regexp matching a headline, possibly with some keyword.
4770 This regexp can match any headline with the specified keyword, or
4771 without a keyword. The keyword isn't in any group by default,
4772 but the stars and the body are.")
4774 (defcustom org-group-tags t
4775 "When non-nil (the default), use group tags.
4776 This can be turned on/off through `org-toggle-tags-groups'."
4777 :group 'org-tags
4778 :group 'org-startup
4779 :type 'boolean)
4781 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4783 (defun org-toggle-tags-groups ()
4784 "Toggle support for group tags.
4785 Support for group tags is controlled by the option
4786 `org-group-tags', which is non-nil by default."
4787 (interactive)
4788 (setq org-group-tags (not org-group-tags))
4789 (cond ((and (derived-mode-p 'org-agenda-mode)
4790 org-group-tags)
4791 (org-agenda-redo))
4792 ((derived-mode-p 'org-mode)
4793 (let ((org-inhibit-startup t)) (org-mode))))
4794 (message "Groups tags support has been turned %s"
4795 (if org-group-tags "on" "off")))
4797 (defun org-set-regexps-and-options-for-tags ()
4798 "Precompute variables used for tags."
4799 (when (derived-mode-p 'org-mode)
4800 (org-set-local 'org-file-tags nil)
4801 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4802 (splitre "[ \t]+")
4803 (start 0)
4804 tags ftags key value)
4805 (save-excursion
4806 (save-restriction
4807 (widen)
4808 (goto-char (point-min))
4809 (while (re-search-forward re nil t)
4810 (setq key (upcase (org-match-string-no-properties 1))
4811 value (org-match-string-no-properties 2))
4812 (if (stringp value) (setq value (org-trim value)))
4813 (cond
4814 ((equal key "TAGS")
4815 (setq tags (append tags (if tags '("\\n") nil)
4816 (org-split-string value splitre))))
4817 ((equal key "FILETAGS")
4818 (when (string-match "\\S-" value)
4819 (setq ftags
4820 (append
4821 ftags
4822 (apply 'append
4823 (mapcar (lambda (x) (org-split-string x ":"))
4824 (org-split-string value)))))))))))
4825 ;; Process the file tags.
4826 (and ftags (org-set-local 'org-file-tags
4827 (mapcar 'org-add-prop-inherited ftags)))
4828 (org-set-local 'org-tag-groups-alist nil)
4829 ;; Process the tags.
4830 (when (and (not tags) org-tag-alist)
4831 (setq tags
4832 (mapcar
4833 (lambda (tg) (cond ((eq (car tg) :startgroup) "{")
4834 ((eq (car tg) :endgroup) "}")
4835 ((eq (car tg) :grouptags) ":")
4836 ((eq (car tg) :newline) "\n")
4837 (t (concat (car tg)
4838 (if (characterp (cdr tg))
4839 (format "(%s)" (char-to-string (cdr tg))) "")))))
4840 org-tag-alist)))
4841 (let (e tgs g)
4842 (while (setq e (pop tags))
4843 (cond
4844 ((equal e "{")
4845 (progn (push '(:startgroup) tgs)
4846 (when (equal (nth 1 tags) ":")
4847 (push (list (replace-regexp-in-string
4848 "(.+)$" "" (nth 0 tags)))
4849 org-tag-groups-alist)
4850 (setq g 0))))
4851 ((equal e ":") (push '(:grouptags) tgs))
4852 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4853 ((equal e "\\n") (push '(:newline) tgs))
4854 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4855 (push (cons (match-string 1 e)
4856 (string-to-char (match-string 2 e))) tgs)
4857 (if (and g (> g 0))
4858 (setcar org-tag-groups-alist
4859 (append (car org-tag-groups-alist)
4860 (list (match-string 1 e)))))
4861 (if g (setq g (1+ g))))
4862 (t (push (list e) tgs)
4863 (if (and g (> g 0))
4864 (setcar org-tag-groups-alist
4865 (append (car org-tag-groups-alist) (list e))))
4866 (if g (setq g (1+ g))))))
4867 (org-set-local 'org-tag-alist nil)
4868 (while (setq e (pop tgs))
4869 (or (and (stringp (car e))
4870 (assoc (car e) org-tag-alist))
4871 (push e org-tag-alist)))
4872 ;; Return a list with tag variables
4873 (list org-file-tags org-tag-alist org-tag-groups-alist)))))
4875 (defvar org-ota nil)
4876 (defun org-set-regexps-and-options ()
4877 "Precompute regular expressions used in the current buffer."
4878 (when (derived-mode-p 'org-mode)
4879 (org-set-local 'org-todo-kwd-alist nil)
4880 (org-set-local 'org-todo-key-alist nil)
4881 (org-set-local 'org-todo-key-trigger nil)
4882 (org-set-local 'org-todo-keywords-1 nil)
4883 (org-set-local 'org-done-keywords nil)
4884 (org-set-local 'org-todo-heads nil)
4885 (org-set-local 'org-todo-sets nil)
4886 (org-set-local 'org-todo-log-states nil)
4887 (org-set-local 'org-file-properties nil)
4888 (let ((re (org-make-options-regexp
4889 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4890 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4891 "SETUPFILE" "OPTIONS")
4892 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4893 (splitre "[ \t]+")
4894 (scripts org-use-sub-superscripts)
4895 kwds kws0 kwsa key log value cat arch const links hw dws
4896 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4897 (start 0))
4898 (save-excursion
4899 (save-restriction
4900 (widen)
4901 (goto-char (point-min))
4902 (while
4903 (or (and
4904 ext-setup-or-nil
4905 (not org-ota)
4906 (let (ret)
4907 (with-temp-buffer
4908 (insert ext-setup-or-nil)
4909 (let ((major-mode 'org-mode) org-ota)
4910 (setq ret (save-match-data
4911 (org-set-regexps-and-options-for-tags)))))
4912 ;; Append setupfile tags to existing tags
4913 (setq org-ota t)
4914 (setq org-file-tags
4915 (delq nil (append org-file-tags (nth 0 ret)))
4916 org-tag-alist
4917 (delq nil (append org-tag-alist (nth 1 ret)))
4918 org-tag-groups-alist
4919 (delq nil (append org-tag-groups-alist (nth 2 ret))))))
4920 (and ext-setup-or-nil
4921 (string-match re ext-setup-or-nil start)
4922 (setq start (match-end 0)))
4923 (and (setq ext-setup-or-nil nil start 0)
4924 (re-search-forward re nil t)))
4925 (setq key (upcase (match-string 1 ext-setup-or-nil))
4926 value (org-match-string-no-properties 2 ext-setup-or-nil))
4927 (if (stringp value) (setq value (org-trim value)))
4928 (cond
4929 ((equal key "CATEGORY")
4930 (setq cat value))
4931 ((member key '("SEQ_TODO" "TODO"))
4932 (push (cons 'sequence (org-split-string value splitre)) kwds))
4933 ((equal key "TYP_TODO")
4934 (push (cons 'type (org-split-string value splitre)) kwds))
4935 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4936 ;; general TODO-like setup
4937 (push (cons (intern (downcase (match-string 1 key)))
4938 (org-split-string value splitre)) kwds))
4939 ((equal key "COLUMNS")
4940 (org-set-local 'org-columns-default-format value))
4941 ((equal key "LINK")
4942 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4943 (push (cons (match-string 1 value)
4944 (org-trim (match-string 2 value)))
4945 links)))
4946 ((equal key "PRIORITIES")
4947 (setq prio (org-split-string value " +")))
4948 ((equal key "PROPERTY")
4949 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4950 (setq props (org-update-property-plist (match-string 1 value)
4951 (match-string 2 value)
4952 props))))
4953 ((equal key "DRAWERS")
4954 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4955 ((equal key "CONSTANTS")
4956 (org-table-set-constants))
4957 ((equal key "STARTUP")
4958 (let ((opts (org-split-string value splitre))
4959 l var val)
4960 (while (setq l (pop opts))
4961 (when (setq l (assoc l org-startup-options))
4962 (setq var (nth 1 l) val (nth 2 l))
4963 (if (not (nth 3 l))
4964 (set (make-local-variable var) val)
4965 (if (not (listp (symbol-value var)))
4966 (set (make-local-variable var) nil))
4967 (set (make-local-variable var) (symbol-value var))
4968 (add-to-list var val))))))
4969 ((equal key "ARCHIVE")
4970 (setq arch value)
4971 (remove-text-properties 0 (length arch)
4972 '(face t fontified t) arch))
4973 ((equal key "OPTIONS")
4974 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4975 (setq scripts (read (match-string 2 value)))))
4976 ((and (equal key "SETUPFILE")
4977 ;; Prevent checking in Gnus messages
4978 (not buffer-read-only))
4979 (setq setup-contents (org-file-contents
4980 (expand-file-name
4981 (org-remove-double-quotes value))
4982 'noerror))
4983 (if (not ext-setup-or-nil)
4984 (setq ext-setup-or-nil setup-contents start 0)
4985 (setq ext-setup-or-nil
4986 (concat (substring ext-setup-or-nil 0 start)
4987 "\n" setup-contents "\n"
4988 (substring ext-setup-or-nil start)))))))
4989 ;; search for property blocks
4990 (goto-char (point-min))
4991 (while (re-search-forward org-block-regexp nil t)
4992 (when (equal "PROPERTY" (upcase (match-string 1)))
4993 (setq value (replace-regexp-in-string
4994 "[\n\r]" " " (match-string 4)))
4995 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4996 (setq props (org-update-property-plist (match-string 1 value)
4997 (match-string 2 value)
4998 props)))))))
4999 (org-set-local 'org-use-sub-superscripts scripts)
5000 (when cat
5001 (org-set-local 'org-category (intern cat))
5002 (push (cons "CATEGORY" cat) props))
5003 (when prio
5004 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5005 (setq prio (mapcar 'string-to-char prio))
5006 (org-set-local 'org-highest-priority (nth 0 prio))
5007 (org-set-local 'org-lowest-priority (nth 1 prio))
5008 (org-set-local 'org-default-priority (nth 2 prio)))
5009 (and props (org-set-local 'org-file-properties (nreverse props)))
5010 (and drawers (org-set-local 'org-drawers drawers))
5011 (and arch (org-set-local 'org-archive-location arch))
5012 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5013 ;; Process the TODO keywords
5014 (unless kwds
5015 ;; Use the global values as if they had been given locally.
5016 (setq kwds (default-value 'org-todo-keywords))
5017 (if (stringp (car kwds))
5018 (setq kwds (list (cons org-todo-interpretation
5019 (default-value 'org-todo-keywords)))))
5020 (setq kwds (reverse kwds)))
5021 (setq kwds (nreverse kwds))
5022 (let (inter kws kw)
5023 (while (setq kws (pop kwds))
5024 (let ((kws (or
5025 (run-hook-with-args-until-success
5026 'org-todo-setup-filter-hook kws)
5027 kws)))
5028 (setq inter (pop kws) sep (member "|" kws)
5029 kws0 (delete "|" (copy-sequence kws))
5030 kwsa nil
5031 kws1 (mapcar
5032 (lambda (x)
5033 ;; 1 2
5034 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5035 (progn
5036 (setq kw (match-string 1 x)
5037 key (and (match-end 2) (match-string 2 x))
5038 log (org-extract-log-state-settings x))
5039 (push (cons kw (and key (string-to-char key))) kwsa)
5040 (and log (push log org-todo-log-states))
5042 (error "Invalid TODO keyword %s" x)))
5043 kws0)
5044 kwsa (if kwsa (append '((:startgroup))
5045 (nreverse kwsa)
5046 '((:endgroup))))
5047 hw (car kws1)
5048 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5049 tail (list inter hw (car dws) (org-last dws))))
5050 (add-to-list 'org-todo-heads hw 'append)
5051 (push kws1 org-todo-sets)
5052 (setq org-done-keywords (append org-done-keywords dws nil))
5053 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5054 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5055 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5056 (setq org-todo-sets (nreverse org-todo-sets)
5057 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5058 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5059 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5060 ;; Compute the regular expressions and other local variables.
5061 ;; Using `org-outline-regexp-bol' would complicate them much,
5062 ;; because of the fixed white space at the end of that string.
5063 (if (not org-done-keywords)
5064 (setq org-done-keywords (and org-todo-keywords-1
5065 (list (org-last org-todo-keywords-1)))))
5066 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5067 (length org-scheduled-string)
5068 (length org-clock-string)
5069 (length org-closed-string)))
5070 org-drawer-regexp
5071 (concat "^[ \t]*:\\("
5072 (mapconcat 'regexp-quote org-drawers "\\|")
5073 "\\):[ \t]*$")
5074 org-not-done-keywords
5075 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5076 org-todo-regexp
5077 (concat "\\("
5078 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5079 "\\)")
5080 org-not-done-regexp
5081 (concat "\\("
5082 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5083 "\\)")
5084 org-not-done-heading-regexp
5085 (format org-heading-keyword-regexp-format org-not-done-regexp)
5086 org-todo-line-regexp
5087 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5088 org-complex-heading-regexp
5089 (concat "^\\(\\*+\\)"
5090 "\\(?: +" org-todo-regexp "\\)?"
5091 "\\(?: +\\(\\[#.\\]\\)\\)?"
5092 "\\(?: +\\(.*?\\)\\)??"
5093 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5094 "[ \t]*$")
5095 org-complex-heading-regexp-format
5096 (concat "^\\(\\*+\\)"
5097 "\\(?: +" org-todo-regexp "\\)?"
5098 "\\(?: +\\(\\[#.\\]\\)\\)?"
5099 "\\(?: +"
5100 ;; Stats cookies can be stuck to body.
5101 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5102 "\\(%s\\)"
5103 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5104 "\\)"
5105 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5106 "[ \t]*$")
5107 org-todo-line-tags-regexp
5108 (concat "^\\(\\*+\\)"
5109 "\\(?: +" org-todo-regexp "\\)?"
5110 "\\(?: +\\(.*?\\)\\)??"
5111 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5112 "[ \t]*$")
5113 org-deadline-regexp (concat "\\<" org-deadline-string)
5114 org-deadline-time-regexp
5115 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5116 org-deadline-time-hour-regexp
5117 (concat "\\<" org-deadline-string
5118 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5119 org-deadline-line-regexp
5120 (concat "\\<\\(" org-deadline-string "\\).*")
5121 org-scheduled-regexp
5122 (concat "\\<" org-scheduled-string)
5123 org-scheduled-time-regexp
5124 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5125 org-scheduled-time-hour-regexp
5126 (concat "\\<" org-scheduled-string
5127 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
5128 org-closed-time-regexp
5129 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5130 org-keyword-time-regexp
5131 (concat "\\<\\(" org-scheduled-string
5132 "\\|" org-deadline-string
5133 "\\|" org-closed-string
5134 "\\|" org-clock-string "\\)"
5135 " *[[<]\\([^]>]+\\)[]>]")
5136 org-keyword-time-not-clock-regexp
5137 (concat "\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\)"
5141 " *[[<]\\([^]>]+\\)[]>]")
5142 org-maybe-keyword-time-regexp
5143 (concat "\\(\\<\\(" org-scheduled-string
5144 "\\|" org-deadline-string
5145 "\\|" org-closed-string
5146 "\\|" org-clock-string "\\)\\)?"
5147 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5148 org-all-time-keywords
5149 (mapcar (lambda (w) (substring w 0 -1))
5150 (list org-scheduled-string org-deadline-string
5151 org-clock-string org-closed-string)))
5152 (setq org-ota nil)
5153 (org-compute-latex-and-related-regexp))))
5155 (defun org-file-contents (file &optional noerror)
5156 "Return the contents of FILE, as a string."
5157 (if (or (not file) (not (file-readable-p file)))
5158 (if (not noerror)
5159 (error "Cannot read file \"%s\"" file)
5160 (message "Cannot read file \"%s\"" file)
5162 (with-temp-buffer
5163 (insert-file-contents file)
5164 (buffer-string))))
5166 (defun org-extract-log-state-settings (x)
5167 "Extract the log state setting from a TODO keyword string.
5168 This will extract info from a string like \"WAIT(w@/!)\"."
5169 (let (kw key log1 log2)
5170 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5171 (setq kw (match-string 1 x)
5172 key (and (match-end 2) (match-string 2 x))
5173 log1 (and (match-end 3) (match-string 3 x))
5174 log2 (and (match-end 4) (match-string 4 x)))
5175 (and (or log1 log2)
5176 (list kw
5177 (and log1 (if (equal log1 "!") 'time 'note))
5178 (and log2 (if (equal log2 "!") 'time 'note)))))))
5180 (defun org-remove-keyword-keys (list)
5181 "Remove a pair of parenthesis at the end of each string in LIST."
5182 (mapcar (lambda (x)
5183 (if (string-match "(.*)$" x)
5184 (substring x 0 (match-beginning 0))
5186 list))
5188 (defun org-assign-fast-keys (alist)
5189 "Assign fast keys to a keyword-key alist.
5190 Respect keys that are already there."
5191 (let (new e (alt ?0))
5192 (while (setq e (pop alist))
5193 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5194 (cdr e)) ;; Key already assigned.
5195 (push e new)
5196 (let ((clist (string-to-list (downcase (car e))))
5197 (used (append new alist)))
5198 (when (= (car clist) ?@)
5199 (pop clist))
5200 (while (and clist (rassoc (car clist) used))
5201 (pop clist))
5202 (unless clist
5203 (while (rassoc alt used)
5204 (incf alt)))
5205 (push (cons (car e) (or (car clist) alt)) new))))
5206 (nreverse new)))
5208 ;;; Some variables used in various places
5210 (defvar org-window-configuration nil
5211 "Used in various places to store a window configuration.")
5212 (defvar org-selected-window nil
5213 "Used in various places to store a window configuration.")
5214 (defvar org-finish-function nil
5215 "Function to be called when `C-c C-c' is used.
5216 This is for getting out of special buffers like capture.")
5219 ;; FIXME: Occasionally check by commenting these, to make sure
5220 ;; no other functions uses these, forgetting to let-bind them.
5221 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5222 (defvar org-last-state)
5223 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5225 ;; Defined somewhere in this file, but used before definition.
5226 (defvar org-entities) ;; defined in org-entities.el
5227 (defvar org-struct-menu)
5228 (defvar org-org-menu)
5229 (defvar org-tbl-menu)
5231 ;;;; Define the Org-mode
5233 ;; We use a before-change function to check if a table might need
5234 ;; an update.
5235 (defvar org-table-may-need-update t
5236 "Indicates that a table might need an update.
5237 This variable is set by `org-before-change-function'.
5238 `org-table-align' sets it back to nil.")
5239 (defun org-before-change-function (beg end)
5240 "Every change indicates that a table might need an update."
5241 (setq org-table-may-need-update t))
5242 (defvar org-mode-map)
5243 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5244 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5245 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5246 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5247 (defvar org-table-buffer-is-an nil)
5249 (defvar bidi-paragraph-direction)
5250 (defvar buffer-face-mode-face)
5252 (require 'outline)
5253 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5254 (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"))
5255 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5257 ;; Other stuff we need.
5258 (require 'time-date)
5259 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5260 (require 'easymenu)
5261 (require 'overlay)
5263 ;; (require 'org-macs) moved higher up in the file before it is first used
5264 (require 'org-entities)
5265 ;; (require 'org-compat) moved higher up in the file before it is first used
5266 (require 'org-faces)
5267 (require 'org-list)
5268 (require 'org-pcomplete)
5269 (require 'org-src)
5270 (require 'org-footnote)
5271 (require 'org-macro)
5273 ;; babel
5274 (require 'ob)
5276 ;;;###autoload
5277 (define-derived-mode org-mode outline-mode "Org"
5278 "Outline-based notes management and organizer, alias
5279 \"Carsten's outline-mode for keeping track of everything.\"
5281 Org-mode develops organizational tasks around a NOTES file which
5282 contains information about projects as plain text. Org-mode is
5283 implemented on top of outline-mode, which is ideal to keep the content
5284 of large files well structured. It supports ToDo items, deadlines and
5285 time stamps, which magically appear in the diary listing of the Emacs
5286 calendar. Tables are easily created with a built-in table editor.
5287 Plain text URL-like links connect to websites, emails (VM), Usenet
5288 messages (Gnus), BBDB entries, and any files related to the project.
5289 For printing and sharing of notes, an Org-mode file (or a part of it)
5290 can be exported as a structured ASCII or HTML file.
5292 The following commands are available:
5294 \\{org-mode-map}"
5296 ;; Get rid of Outline menus, they are not needed
5297 ;; Need to do this here because define-derived-mode sets up
5298 ;; the keymap so late. Still, it is a waste to call this each time
5299 ;; we switch another buffer into org-mode.
5300 (if (featurep 'xemacs)
5301 (when (boundp 'outline-mode-menu-heading)
5302 ;; Assume this is Greg's port, it uses easymenu
5303 (easy-menu-remove outline-mode-menu-heading)
5304 (easy-menu-remove outline-mode-menu-show)
5305 (easy-menu-remove outline-mode-menu-hide))
5306 (define-key org-mode-map [menu-bar headings] 'undefined)
5307 (define-key org-mode-map [menu-bar hide] 'undefined)
5308 (define-key org-mode-map [menu-bar show] 'undefined))
5310 (org-load-modules-maybe)
5311 (easy-menu-add org-org-menu)
5312 (easy-menu-add org-tbl-menu)
5313 (org-install-agenda-files-menu)
5314 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5315 (add-to-invisibility-spec '(org-cwidth))
5316 (add-to-invisibility-spec '(org-hide-block . t))
5317 (when (featurep 'xemacs)
5318 (org-set-local 'line-move-ignore-invisible t))
5319 (org-set-local 'outline-regexp org-outline-regexp)
5320 (org-set-local 'outline-level 'org-outline-level)
5321 (setq bidi-paragraph-direction 'left-to-right)
5322 (when (and org-ellipsis
5323 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5324 (fboundp 'make-glyph-code))
5325 (unless org-display-table
5326 (setq org-display-table (make-display-table)))
5327 (set-display-table-slot
5328 org-display-table 4
5329 (vconcat (mapcar
5330 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5331 org-ellipsis)))
5332 (if (stringp org-ellipsis) org-ellipsis "..."))))
5333 (setq buffer-display-table org-display-table))
5334 (org-set-regexps-and-options-for-tags)
5335 (org-set-regexps-and-options)
5336 (org-set-font-lock-defaults)
5337 (when (and org-tag-faces (not org-tags-special-faces-re))
5338 ;; tag faces set outside customize.... force initialization.
5339 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5340 ;; Calc embedded
5341 (org-set-local 'calc-embedded-open-mode "# ")
5342 ;; Modify a few syntax entries
5343 (modify-syntax-entry ?@ "w")
5344 (modify-syntax-entry ?\" "\"")
5345 (if org-startup-truncated (setq truncate-lines t))
5346 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5347 (org-set-local 'font-lock-unfontify-region-function
5348 'org-unfontify-region)
5349 ;; Activate before-change-function
5350 (org-set-local 'org-table-may-need-update t)
5351 (org-add-hook 'before-change-functions 'org-before-change-function nil
5352 'local)
5353 ;; Check for running clock before killing a buffer
5354 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5355 ;; Initialize macros templates.
5356 (org-macro-initialize-templates)
5357 ;; Initialize radio targets.
5358 (org-update-radio-target-regexp)
5359 ;; Indentation.
5360 (org-set-local 'indent-line-function 'org-indent-line)
5361 (org-set-local 'indent-region-function 'org-indent-region)
5362 ;; Filling and auto-filling.
5363 (org-setup-filling)
5364 ;; Comments.
5365 (org-setup-comments-handling)
5366 ;; Beginning/end of defun
5367 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5368 (org-set-local 'end-of-defun-function 'org-forward-element)
5369 ;; Next error for sparse trees
5370 (org-set-local 'next-error-function 'org-occur-next-match)
5371 ;; Make sure dependence stuff works reliably, even for users who set it
5372 ;; too late :-(
5373 (if org-enforce-todo-dependencies
5374 (add-hook 'org-blocker-hook
5375 'org-block-todo-from-children-or-siblings-or-parent)
5376 (remove-hook 'org-blocker-hook
5377 'org-block-todo-from-children-or-siblings-or-parent))
5378 (if org-enforce-todo-checkbox-dependencies
5379 (add-hook 'org-blocker-hook
5380 'org-block-todo-from-checkboxes)
5381 (remove-hook 'org-blocker-hook
5382 'org-block-todo-from-checkboxes))
5384 ;; Align options lines
5385 (org-set-local
5386 'align-mode-rules-list
5387 '((org-in-buffer-settings
5388 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5389 (modes . '(org-mode)))))
5391 ;; Imenu
5392 (org-set-local 'imenu-create-index-function
5393 'org-imenu-get-tree)
5395 ;; Make isearch reveal context
5396 (if (or (featurep 'xemacs)
5397 (not (boundp 'outline-isearch-open-invisible-function)))
5398 ;; Emacs 21 and XEmacs make use of the hook
5399 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5400 ;; Emacs 22 deals with this through a special variable
5401 (org-set-local 'outline-isearch-open-invisible-function
5402 (lambda (&rest ignore) (org-show-context 'isearch)))
5403 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5405 ;; Setup the pcomplete hooks
5406 (set (make-local-variable 'pcomplete-command-completion-function)
5407 'org-pcomplete-initial)
5408 (set (make-local-variable 'pcomplete-command-name-function)
5409 'org-command-at-point)
5410 (set (make-local-variable 'pcomplete-default-completion-function)
5411 'ignore)
5412 (set (make-local-variable 'pcomplete-parse-arguments-function)
5413 'org-parse-arguments)
5414 (set (make-local-variable 'pcomplete-termination-string) "")
5415 (when (>= emacs-major-version 23)
5416 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5418 ;; If empty file that did not turn on org-mode automatically, make it to.
5419 (if (and org-insert-mode-line-in-empty-file
5420 (org-called-interactively-p 'any)
5421 (= (point-min) (point-max)))
5422 (insert "# -*- mode: org -*-\n\n"))
5423 (unless org-inhibit-startup
5424 (org-unmodified
5425 (and org-startup-with-beamer-mode (org-beamer-mode))
5426 (when org-startup-align-all-tables
5427 (org-table-map-tables 'org-table-align 'quietly))
5428 (when org-startup-with-inline-images
5429 (org-display-inline-images))
5430 (when org-startup-with-latex-preview
5431 (org-preview-latex-fragment))
5432 (unless org-inhibit-startup-visibility-stuff
5433 (org-set-startup-visibility))))
5434 ;; Try to set org-hide correctly
5435 (let ((foreground (org-find-invisible-foreground)))
5436 (if foreground
5437 (set-face-foreground 'org-hide foreground))))
5439 ;; Update `customize-package-emacs-version-alist'
5440 (add-to-list 'customize-package-emacs-version-alist
5441 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5442 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5443 ("8.2.6" . "24.4")))
5445 (defvar org-mode-transpose-word-syntax-table
5446 (let ((st (make-syntax-table)))
5447 (mapc (lambda(c) (modify-syntax-entry
5448 (string-to-char (car c)) "w p" st))
5449 org-emphasis-alist)
5450 st))
5452 (when (fboundp 'abbrev-table-put)
5453 (abbrev-table-put org-mode-abbrev-table
5454 :parents (list text-mode-abbrev-table)))
5456 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5458 (defsubst org-fix-ellipsis-at-bol ()
5459 (save-excursion (goto-char (window-start)) (recenter 0)))
5461 (defun org-find-invisible-foreground ()
5462 (let ((candidates (remove
5463 "unspecified-bg"
5464 (nconc
5465 (list (face-background 'default)
5466 (face-background 'org-default))
5467 (mapcar
5468 (lambda (alist)
5469 (when (boundp alist)
5470 (cdr (assoc 'background-color (symbol-value alist)))))
5471 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5472 (list (face-foreground 'org-hide))))))
5473 (car (remove nil candidates))))
5475 (defun org-current-time (&optional rounding-minutes past)
5476 "Current time, possibly rounded to ROUNDING-MINUTES.
5477 When ROUNDING-MINUTES is not an integer, fall back on the car of
5478 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5479 the rounding returns a past time."
5480 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5481 (car org-time-stamp-rounding-minutes)))
5482 (time (decode-time)) res)
5483 (if (< r 1)
5484 (current-time)
5485 (setq res
5486 (apply 'encode-time
5487 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5488 (nthcdr 2 time))))
5489 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5490 (seconds-to-time (- (org-float-time res) (* r 60)))
5491 res))))
5493 (defun org-today ()
5494 "Return today date, considering `org-extend-today-until'."
5495 (time-to-days
5496 (time-subtract (current-time)
5497 (list 0 (* 3600 org-extend-today-until) 0))))
5499 ;;;; Font-Lock stuff, including the activators
5501 (defvar org-mouse-map (make-sparse-keymap))
5502 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5503 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5504 (when org-mouse-1-follows-link
5505 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5506 (when org-tab-follows-link
5507 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5508 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5510 (require 'font-lock)
5512 (defconst org-non-link-chars "]\t\n\r<>")
5513 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5514 "shell" "elisp" "doi" "message"))
5515 (defvar org-link-types-re nil
5516 "Matches a link that has a url-like prefix like \"http:\"")
5517 (defvar org-link-re-with-space nil
5518 "Matches a link with spaces, optional angular brackets around it.")
5519 (defvar org-link-re-with-space2 nil
5520 "Matches a link with spaces, optional angular brackets around it.")
5521 (defvar org-link-re-with-space3 nil
5522 "Matches a link with spaces, only for internal part in bracket links.")
5523 (defvar org-angle-link-re nil
5524 "Matches link with angular brackets, spaces are allowed.")
5525 (defvar org-plain-link-re nil
5526 "Matches plain link, without spaces.")
5527 (defvar org-bracket-link-regexp nil
5528 "Matches a link in double brackets.")
5529 (defvar org-bracket-link-analytic-regexp nil
5530 "Regular expression used to analyze links.
5531 Here is what the match groups contain after a match:
5532 1: http:
5533 2: http
5534 3: path
5535 4: [desc]
5536 5: desc")
5537 (defvar org-bracket-link-analytic-regexp++ nil
5538 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5539 (defvar org-any-link-re nil
5540 "Regular expression matching any link.")
5542 (defconst org-match-sexp-depth 3
5543 "Number of stacked braces for sub/superscript matching.")
5545 (defun org-create-multibrace-regexp (left right n)
5546 "Create a regular expression which will match a balanced sexp.
5547 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5548 as single character strings.
5549 The regexp returned will match the entire expression including the
5550 delimiters. It will also define a single group which contains the
5551 match except for the outermost delimiters. The maximum depth of
5552 stacked delimiters is N. Escaping delimiters is not possible."
5553 (let* ((nothing (concat "[^" left right "]*?"))
5554 (or "\\|")
5555 (re nothing)
5556 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5557 (while (> n 1)
5558 (setq n (1- n)
5559 re (concat re or next)
5560 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5561 (concat left "\\(" re "\\)" right)))
5563 (defvar org-match-substring-regexp
5564 (concat
5565 "\\(\\S-\\)\\([_^]\\)\\("
5566 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5567 "\\|"
5568 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5569 "\\|"
5570 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5571 "The regular expression matching a sub- or superscript.")
5573 (defvar org-match-substring-with-braces-regexp
5574 (concat
5575 "\\(\\S-\\)\\([_^]\\)\\("
5576 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5577 "\\)")
5578 "The regular expression matching a sub- or superscript, forcing braces.")
5580 (defun org-make-link-regexps ()
5581 "Update the link regular expressions.
5582 This should be called after the variable `org-link-types' has changed."
5583 (setq org-link-types-re
5584 (concat
5585 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5586 org-link-re-with-space
5587 (concat
5588 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5589 "\\([^" org-non-link-chars " ]"
5590 "[^" org-non-link-chars "]*"
5591 "[^" org-non-link-chars " ]\\)>?")
5592 org-link-re-with-space2
5593 (concat
5594 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^\t\n\r]*"
5597 "[^" org-non-link-chars " ]\\)>?")
5598 org-link-re-with-space3
5599 (concat
5600 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 "\\([^" org-non-link-chars " ]"
5602 "[^\t\n\r]*\\)")
5603 org-angle-link-re
5604 (concat
5605 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5606 "\\([^" org-non-link-chars " ]"
5607 "[^" org-non-link-chars "]*"
5608 "\\)>")
5609 org-plain-link-re
5610 (concat
5611 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5612 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5613 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5614 org-bracket-link-regexp
5615 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5616 org-bracket-link-analytic-regexp
5617 (concat
5618 "\\[\\["
5619 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5620 "\\([^]]+\\)"
5621 "\\]"
5622 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5623 "\\]")
5624 org-bracket-link-analytic-regexp++
5625 (concat
5626 "\\[\\["
5627 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5628 "\\([^]]+\\)"
5629 "\\]"
5630 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5631 "\\]")
5632 org-any-link-re
5633 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5634 org-angle-link-re "\\)\\|\\("
5635 org-plain-link-re "\\)")))
5637 (org-make-link-regexps)
5639 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5640 "Regular expression for fast time stamp matching.")
5641 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5642 "Regular expression for fast time stamp matching.")
5643 (defconst org-ts-regexp0
5644 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5645 "Regular expression matching time strings for analysis.
5646 This one does not require the space after the date, so it can be used
5647 on a string that terminates immediately after the date.")
5648 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5649 "Regular expression matching time strings for analysis.")
5650 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5651 "Regular expression matching time stamps, with groups.")
5652 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5653 "Regular expression matching time stamps (also [..]), with groups.")
5654 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5655 "Regular expression matching a time stamp range.")
5656 (defconst org-tr-regexp-both
5657 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5658 "Regular expression matching a time stamp range.")
5659 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5660 org-ts-regexp "\\)?")
5661 "Regular expression matching a time stamp or time stamp range.")
5662 (defconst org-tsr-regexp-both
5663 (concat org-ts-regexp-both "\\(--?-?"
5664 org-ts-regexp-both "\\)?")
5665 "Regular expression matching a time stamp or time stamp range.
5666 The time stamps may be either active or inactive.")
5668 (defvar org-emph-face nil)
5670 (defun org-do-emphasis-faces (limit)
5671 "Run through the buffer and add overlays to emphasized strings."
5672 (let (rtn a)
5673 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5674 (let* ((border (char-after (match-beginning 3)))
5675 (bre (regexp-quote (char-to-string border))))
5676 (if (and (not (= border (char-after (match-beginning 4))))
5677 (not (save-match-data
5678 (string-match (concat bre ".*" bre)
5679 (replace-regexp-in-string
5680 "\n" " "
5681 (substring (match-string 2) 1 -1))))))
5682 (progn
5683 (setq rtn t)
5684 (setq a (assoc (match-string 3) org-emphasis-alist))
5685 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5686 'face
5687 (nth 1 a))
5688 (and (nth 2 a)
5689 (org-remove-flyspell-overlays-in
5690 (match-beginning 0) (match-end 0)))
5691 (add-text-properties (match-beginning 2) (match-end 2)
5692 '(font-lock-multiline t org-emphasis t))
5693 (when org-hide-emphasis-markers
5694 (add-text-properties (match-end 4) (match-beginning 5)
5695 '(invisible org-link))
5696 (add-text-properties (match-beginning 3) (match-end 3)
5697 '(invisible org-link))))))
5698 (goto-char (1+ (match-beginning 0))))
5699 rtn))
5701 (defun org-emphasize (&optional char)
5702 "Insert or change an emphasis, i.e. a font like bold or italic.
5703 If there is an active region, change that region to a new emphasis.
5704 If there is no region, just insert the marker characters and position
5705 the cursor between them.
5706 CHAR should be the marker character. If it is a space, it means to
5707 remove the emphasis of the selected region.
5708 If CHAR is not given (for example in an interactive call) it will be
5709 prompted for."
5710 (interactive)
5711 (let ((erc org-emphasis-regexp-components)
5712 (prompt "")
5713 (string "") beg end move c s)
5714 (if (org-region-active-p)
5715 (setq beg (region-beginning) end (region-end)
5716 string (buffer-substring beg end))
5717 (setq move t))
5719 (unless char
5720 (message "Emphasis marker or tag: [%s]"
5721 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5722 (setq char (read-char-exclusive)))
5723 (if (equal char ?\ )
5724 (setq s "" move nil)
5725 (unless (assoc (char-to-string char) org-emphasis-alist)
5726 (user-error "No such emphasis marker: \"%c\"" char))
5727 (setq s (char-to-string char)))
5728 (while (and (> (length string) 1)
5729 (equal (substring string 0 1) (substring string -1))
5730 (assoc (substring string 0 1) org-emphasis-alist))
5731 (setq string (substring string 1 -1)))
5732 (setq string (concat s string s))
5733 (if beg (delete-region beg end))
5734 (unless (or (bolp)
5735 (string-match (concat "[" (nth 0 erc) "\n]")
5736 (char-to-string (char-before (point)))))
5737 (insert " "))
5738 (unless (or (eobp)
5739 (string-match (concat "[" (nth 1 erc) "\n]")
5740 (char-to-string (char-after (point)))))
5741 (insert " ") (backward-char 1))
5742 (insert string)
5743 (and move (backward-char 1))))
5745 (defconst org-nonsticky-props
5746 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5748 (defsubst org-rear-nonsticky-at (pos)
5749 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5751 (defun org-activate-plain-links (limit)
5752 "Run through the buffer and add overlays to links."
5753 (let (f hl)
5754 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5755 (not (org-in-src-block-p)))
5756 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5757 (setq f (get-text-property (match-beginning 0) 'face))
5758 (setq hl (org-match-string-no-properties 0))
5759 (if (or (eq f 'org-tag)
5760 (and (listp f) (memq 'org-tag f)))
5762 (add-text-properties (match-beginning 0) (match-end 0)
5763 (list 'mouse-face 'highlight
5764 'face 'org-link
5765 'htmlize-link `(:uri ,hl)
5766 'keymap org-mouse-map))
5767 (org-rear-nonsticky-at (match-end 0)))
5768 t)))
5770 (defun org-activate-code (limit)
5771 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5772 (progn
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (remove-text-properties (match-beginning 0) (match-end 0)
5775 '(display t invisible t intangible t))
5776 t)))
5778 (defcustom org-src-fontify-natively nil
5779 "When non-nil, fontify code in code blocks."
5780 :type 'boolean
5781 :version "24.1"
5782 :group 'org-appearance
5783 :group 'org-babel)
5785 (defcustom org-allow-promoting-top-level-subtree nil
5786 "When non-nil, allow promoting a top level subtree.
5787 The leading star of the top level headline will be replaced
5788 by a #."
5789 :type 'boolean
5790 :version "24.1"
5791 :group 'org-appearance)
5793 (defun org-fontify-meta-lines-and-blocks (limit)
5794 (condition-case nil
5795 (org-fontify-meta-lines-and-blocks-1 limit)
5796 (error (message "org-mode fontification error"))))
5798 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5799 "Fontify #+ lines and blocks."
5800 (let ((case-fold-search t))
5801 (if (re-search-forward
5802 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5803 limit t)
5804 (let ((beg (match-beginning 0))
5805 (block-start (match-end 0))
5806 (block-end nil)
5807 (lang (match-string 7))
5808 (beg1 (line-beginning-position 2))
5809 (dc1 (downcase (match-string 2)))
5810 (dc3 (downcase (match-string 3)))
5811 end end1 quoting block-type ovl)
5812 (cond
5813 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5814 ;; a single line of backend-specific content
5815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5816 (remove-text-properties (match-beginning 0) (match-end 0)
5817 '(display t invisible t intangible t))
5818 (add-text-properties (match-beginning 1) (match-end 3)
5819 '(font-lock-fontified t face org-meta-line))
5820 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5821 '(font-lock-fontified t face org-block))
5822 ; for backend-specific code
5824 ((and (match-end 4) (equal dc3 "+begin"))
5825 ;; Truly a block
5826 (setq block-type (downcase (match-string 5))
5827 quoting (member block-type org-protecting-blocks))
5828 (when (re-search-forward
5829 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5830 nil t) ;; on purpose, we look further than LIMIT
5831 (setq end (min (point-max) (match-end 0))
5832 end1 (min (point-max) (1- (match-beginning 0))))
5833 (setq block-end (match-beginning 0))
5834 (when quoting
5835 (remove-text-properties beg end
5836 '(display t invisible t intangible t)))
5837 (add-text-properties
5838 beg end
5839 '(font-lock-fontified t font-lock-multiline t))
5840 (add-text-properties beg beg1 '(face org-meta-line))
5841 (add-text-properties end1 (min (point-max) (1+ end))
5842 '(face org-meta-line)) ; for end_src
5843 (cond
5844 ((and lang (not (string= lang "")) org-src-fontify-natively)
5845 (org-src-font-lock-fontify-block lang block-start block-end)
5846 ;; remove old background overlays
5847 (mapc (lambda (ov)
5848 (if (eq (overlay-get ov 'face) 'org-block-background)
5849 (delete-overlay ov)))
5850 (overlays-at (/ (+ beg1 block-end) 2)))
5851 ;; add a background overlay
5852 (setq ovl (make-overlay beg1 block-end))
5853 (overlay-put ovl 'face 'org-block-background)
5854 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5855 (quoting
5856 (add-text-properties beg1 (min (point-max) (1+ end1))
5857 '(face org-block))) ; end of source block
5858 ((not org-fontify-quote-and-verse-blocks))
5859 ((string= block-type "quote")
5860 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5861 ((string= block-type "verse")
5862 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5863 (add-text-properties beg beg1 '(face org-block-begin-line))
5864 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5865 '(face org-block-end-line))
5867 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5868 (add-text-properties
5869 beg (match-end 3)
5870 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5871 '(font-lock-fontified t invisible t)
5872 '(font-lock-fontified t face org-document-info-keyword)))
5873 (add-text-properties
5874 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5875 (if (string-equal dc1 "+title:")
5876 '(font-lock-fontified t face org-document-title)
5877 '(font-lock-fontified t face org-document-info))))
5878 ((or (equal dc1 "+results")
5879 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5880 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5881 "+call:" "+header:" "+headers:" "+name:"))
5882 (and (match-end 4) (equal dc3 "+attr")))
5883 (add-text-properties
5884 beg (match-end 0)
5885 '(font-lock-fontified t face org-meta-line))
5887 ((member dc3 '(" " ""))
5888 (add-text-properties
5889 beg (match-end 0)
5890 '(font-lock-fontified t face font-lock-comment-face)))
5891 ((not (member (char-after beg) '(?\ ?\t)))
5892 ;; just any other in-buffer setting, but not indented
5893 (add-text-properties
5894 beg (match-end 0)
5895 '(font-lock-fontified t face org-meta-line))
5897 (t nil))))))
5899 (defun org-activate-angle-links (limit)
5900 "Run through the buffer and add overlays to links."
5901 (if (and (re-search-forward org-angle-link-re limit t)
5902 (not (org-in-src-block-p)))
5903 (progn
5904 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5905 (add-text-properties (match-beginning 0) (match-end 0)
5906 (list 'mouse-face 'highlight
5907 'keymap org-mouse-map))
5908 (org-rear-nonsticky-at (match-end 0))
5909 t)))
5911 (defun org-activate-footnote-links (limit)
5912 "Run through the buffer and add overlays to footnotes."
5913 (let ((fn (org-footnote-next-reference-or-definition limit)))
5914 (when fn
5915 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5916 (org-remove-flyspell-overlays-in beg end)
5917 (add-text-properties beg end
5918 (list 'mouse-face 'highlight
5919 'keymap org-mouse-map
5920 'help-echo
5921 (if (= (point-at-bol) beg)
5922 "Footnote definition"
5923 "Footnote reference")
5924 'font-lock-fontified t
5925 'font-lock-multiline t
5926 'face 'org-footnote))))))
5928 (defun org-activate-bracket-links (limit)
5929 "Run through the buffer and add overlays to bracketed links."
5930 (if (and (re-search-forward org-bracket-link-regexp limit t)
5931 (not (org-in-src-block-p)))
5932 (let* ((hl (org-match-string-no-properties 1))
5933 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5934 (ip (org-maybe-intangible
5935 (list 'invisible 'org-link
5936 'keymap org-mouse-map 'mouse-face 'highlight
5937 'font-lock-multiline t 'help-echo help
5938 'htmlize-link `(:uri ,hl))))
5939 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5940 'font-lock-multiline t 'help-echo help
5941 'htmlize-link `(:uri ,hl))))
5942 ;; We need to remove the invisible property here. Table narrowing
5943 ;; may have made some of this invisible.
5944 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5945 (remove-text-properties (match-beginning 0) (match-end 0)
5946 '(invisible nil))
5947 (if (match-end 3)
5948 (progn
5949 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5950 (org-rear-nonsticky-at (match-beginning 3))
5951 (add-text-properties (match-beginning 3) (match-end 3) vp)
5952 (org-rear-nonsticky-at (match-end 3))
5953 (add-text-properties (match-end 3) (match-end 0) ip)
5954 (org-rear-nonsticky-at (match-end 0)))
5955 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5956 (org-rear-nonsticky-at (match-beginning 1))
5957 (add-text-properties (match-beginning 1) (match-end 1) vp)
5958 (org-rear-nonsticky-at (match-end 1))
5959 (add-text-properties (match-end 1) (match-end 0) ip)
5960 (org-rear-nonsticky-at (match-end 0)))
5961 t)))
5963 (defun org-activate-dates (limit)
5964 "Run through the buffer and add overlays to dates."
5965 (if (and (re-search-forward org-tsr-regexp-both limit t)
5966 (not (equal (char-before (match-beginning 0)) 91)))
5967 (progn
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (add-text-properties (match-beginning 0) (match-end 0)
5970 (list 'mouse-face 'highlight
5971 'keymap org-mouse-map))
5972 (org-rear-nonsticky-at (match-end 0))
5973 (when org-display-custom-times
5974 (if (match-end 3)
5975 (org-display-custom-time (match-beginning 3) (match-end 3)))
5976 (org-display-custom-time (match-beginning 1) (match-end 1)))
5977 t)))
5979 (defvar org-target-link-regexp nil
5980 "Regular expression matching radio targets in plain text.")
5981 (make-variable-buffer-local 'org-target-link-regexp)
5982 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5983 "Regular expression matching a link target.")
5984 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5985 "Regular expression matching a radio target.")
5986 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5987 "Regular expression matching any target.")
5989 (defun org-activate-target-links (limit)
5990 "Run through the buffer and add overlays to target matches."
5991 (when org-target-link-regexp
5992 (let ((case-fold-search t))
5993 (if (re-search-forward org-target-link-regexp limit t)
5994 (progn
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (add-text-properties (match-beginning 0) (match-end 0)
5997 (list 'mouse-face 'highlight
5998 'keymap org-mouse-map
5999 'help-echo "Radio target link"
6000 'org-linked-text t))
6001 (org-rear-nonsticky-at (match-end 0))
6002 t)))))
6004 (defun org-update-radio-target-regexp ()
6005 "Find all radio targets in this file and update the regular expression."
6006 (interactive)
6007 (when (memq 'radio org-activate-links)
6008 (setq org-target-link-regexp
6009 (org-make-target-link-regexp (org-all-targets 'radio)))
6010 (org-restart-font-lock)))
6012 (defun org-hide-wide-columns (limit)
6013 (let (s e)
6014 (setq s (text-property-any (point) (or limit (point-max))
6015 'org-cwidth t))
6016 (when s
6017 (setq e (next-single-property-change s 'org-cwidth))
6018 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6019 (goto-char e)
6020 t)))
6022 (defvar org-latex-and-related-regexp nil
6023 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6024 (defvar org-match-substring-regexp)
6025 (defvar org-match-substring-with-braces-regexp)
6027 (defun org-compute-latex-and-related-regexp ()
6028 "Compute regular expression for LaTeX, entities and sub/superscript.
6029 Result depends on variable `org-highlight-latex-and-related'."
6030 (org-set-local
6031 'org-latex-and-related-regexp
6032 (let* ((re-sub
6033 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6034 ((eq org-use-sub-superscripts '{})
6035 (list org-match-substring-with-braces-regexp))
6036 (org-use-sub-superscripts (list org-match-substring-regexp))))
6037 (re-latex
6038 (when (memq 'latex org-highlight-latex-and-related)
6039 (let ((matchers (plist-get org-format-latex-options :matchers)))
6040 (delq nil
6041 (mapcar (lambda (x)
6042 (and (member (car x) matchers) (nth 1 x)))
6043 org-latex-regexps)))))
6044 (re-entities
6045 (when (memq 'entities org-highlight-latex-and-related)
6046 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6047 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6049 (defun org-do-latex-and-related (limit)
6050 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6051 LIMIT bounds the search for syntax to highlight. Stop at first
6052 highlighted object, if any. Return t if some highlighting was
6053 done, nil otherwise."
6054 (when (org-string-nw-p org-latex-and-related-regexp)
6055 (catch 'found
6056 (while (re-search-forward org-latex-and-related-regexp limit t)
6057 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6058 'face))
6059 '(org-code org-verbatim underline))
6060 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6061 '(?_ ?^))
6063 0)))
6064 (font-lock-prepend-text-property
6065 (+ offset (match-beginning 0)) (match-end 0)
6066 'face 'org-latex-and-related)
6067 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6068 '(font-lock-multiline t)))
6069 (throw 'found t)))
6070 nil)))
6072 (defun org-restart-font-lock ()
6073 "Restart `font-lock-mode', to force refontification."
6074 (when (and (boundp 'font-lock-mode) font-lock-mode)
6075 (font-lock-mode -1)
6076 (font-lock-mode 1)))
6078 (defun org-all-targets (&optional radio)
6079 "Return a list of all targets in this file.
6080 When optional argument RADIO is non-nil, only find radio
6081 targets."
6082 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6083 (save-excursion
6084 (goto-char (point-min))
6085 (while (re-search-forward re nil t)
6086 ;; Make sure point is really within the object.
6087 (backward-char)
6088 (let ((obj (org-element-context)))
6089 (when (memq (org-element-type obj) '(radio-target target))
6090 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6091 rtn)))
6093 (defun org-make-target-link-regexp (targets)
6094 "Make regular expression matching all strings in TARGETS.
6095 The regular expression finds the targets also if there is a line break
6096 between words."
6097 (and targets
6098 (concat
6099 "\\<\\("
6100 (mapconcat
6101 (lambda (x)
6102 (setq x (regexp-quote x))
6103 (while (string-match " +" x)
6104 (setq x (replace-match "\\s-+" t t x)))
6106 targets
6107 "\\|")
6108 "\\)\\>")))
6110 (defun org-activate-tags (limit)
6111 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6112 (progn
6113 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6114 (add-text-properties (match-beginning 1) (match-end 1)
6115 (list 'mouse-face 'highlight
6116 'keymap org-mouse-map))
6117 (org-rear-nonsticky-at (match-end 1))
6118 t)))
6120 (defun org-outline-level ()
6121 "Compute the outline level of the heading at point.
6122 If this is called at a normal headline, the level is the number of stars.
6123 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6124 (save-excursion
6125 (if (not (condition-case nil
6126 (org-back-to-heading t)
6127 (error nil)))
6129 (looking-at org-outline-regexp)
6130 (1- (- (match-end 0) (match-beginning 0))))))
6132 (defvar org-font-lock-keywords nil)
6134 (defsubst org-re-property (property &optional literal)
6135 "Return a regexp matching a PROPERTY line.
6136 Match group 3 will be set to the value if it exists."
6137 (concat "^\\(?4:[ \t]*\\)\\(?1::\\(?2:"
6138 (if literal property (regexp-quote property))
6139 "\\):\\)[ \t]+\\(?3:[^ \t\r\n].*?\\)\\(?5:[ \t]*\\)$"))
6141 (defconst org-property-re
6142 (org-re-property ".*?" 'literal)
6143 "Regular expression matching a property line.
6144 There are four matching groups:
6145 1: :PROPKEY: including the leading and trailing colon,
6146 2: PROPKEY without the leading and trailing colon,
6147 3: PROPVAL without leading or trailing spaces,
6148 4: the indentation of the current line,
6149 5: trailing whitespace.")
6151 (defvar org-font-lock-hook nil
6152 "Functions to be called for special font lock stuff.")
6154 (defvar org-font-lock-set-keywords-hook nil
6155 "Functions that can manipulate `org-font-lock-extra-keywords'.
6156 This is called after `org-font-lock-extra-keywords' is defined, but before
6157 it is installed to be used by font lock. This can be useful if something
6158 needs to be inserted at a specific position in the font-lock sequence.")
6160 (defun org-font-lock-hook (limit)
6161 "Run `org-font-lock-hook' within LIMIT."
6162 (run-hook-with-args 'org-font-lock-hook limit))
6164 (defun org-set-font-lock-defaults ()
6165 "Set font lock defaults for the current buffer."
6166 (let* ((em org-fontify-emphasized-text)
6167 (lk org-activate-links)
6168 (org-font-lock-extra-keywords
6169 (list
6170 ;; Call the hook
6171 '(org-font-lock-hook)
6172 ;; Headlines
6173 `(,(if org-fontify-whole-heading-line
6174 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6175 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6176 (1 (org-get-level-face 1))
6177 (2 (org-get-level-face 2))
6178 (3 (org-get-level-face 3)))
6179 ;; Table lines
6180 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6181 (1 'org-table t))
6182 ;; Table internals
6183 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6184 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6185 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6186 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6187 ;; Drawers
6188 (list org-drawer-regexp '(0 'org-special-keyword t))
6189 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6190 ;; Properties
6191 (list org-property-re
6192 '(1 'org-special-keyword t)
6193 '(3 'org-property-value t))
6194 ;; Links
6195 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6196 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6197 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6198 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6199 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6200 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6201 (if (memq 'footnote lk) '(org-activate-footnote-links))
6202 ;; Targets.
6203 (list org-any-target-regexp '(0 'org-target t))
6204 ;; Diary sexps.
6205 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6206 ;; Macro
6207 '("{{{.+}}}" (0 'org-macro t))
6208 '(org-hide-wide-columns (0 nil append))
6209 ;; TODO keyword
6210 (list (format org-heading-keyword-regexp-format
6211 org-todo-regexp)
6212 '(2 (org-get-todo-face 2) t))
6213 ;; DONE
6214 (if org-fontify-done-headline
6215 (list (format org-heading-keyword-regexp-format
6216 (concat
6217 "\\(?:"
6218 (mapconcat 'regexp-quote org-done-keywords "\\|")
6219 "\\)"))
6220 '(2 'org-headline-done t))
6221 nil)
6222 ;; Priorities
6223 '(org-font-lock-add-priority-faces)
6224 ;; Tags
6225 '(org-font-lock-add-tag-faces)
6226 ;; Tags groups
6227 (if (and org-group-tags org-tag-groups-alist)
6228 (list (concat org-outline-regexp-bol ".+\\(:"
6229 (regexp-opt (mapcar 'car org-tag-groups-alist))
6230 ":\\).*$")
6231 '(1 'org-tag-group prepend)))
6232 ;; Special keywords
6233 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6234 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6235 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6236 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6237 ;; Emphasis
6238 (if em
6239 (if (featurep 'xemacs)
6240 '(org-do-emphasis-faces (0 nil append))
6241 '(org-do-emphasis-faces)))
6242 ;; Checkboxes
6243 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6244 1 'org-checkbox prepend)
6245 (if (cdr (assq 'checkbox org-list-automatic-rules))
6246 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6247 (0 (org-get-checkbox-statistics-face) t)))
6248 ;; Description list items
6249 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6250 1 'org-list-dt prepend)
6251 ;; ARCHIVEd headings
6252 (list (concat
6253 org-outline-regexp-bol
6254 "\\(.*:" org-archive-tag ":.*\\)")
6255 '(1 'org-archived prepend))
6256 ;; Specials
6257 '(org-do-latex-and-related)
6258 '(org-fontify-entities)
6259 '(org-raise-scripts)
6260 ;; Code
6261 '(org-activate-code (1 'org-code t))
6262 ;; COMMENT
6263 (list (format org-heading-keyword-regexp-format
6264 (concat "\\("
6265 org-comment-string "\\|" org-quote-string
6266 "\\)"))
6267 '(2 'org-special-keyword t))
6268 ;; Blocks and meta lines
6269 '(org-fontify-meta-lines-and-blocks))))
6270 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6271 (run-hooks 'org-font-lock-set-keywords-hook)
6272 ;; Now set the full font-lock-keywords
6273 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6274 (org-set-local 'font-lock-defaults
6275 '(org-font-lock-keywords t nil nil backward-paragraph))
6276 (kill-local-variable 'font-lock-keywords) nil))
6278 (defun org-toggle-pretty-entities ()
6279 "Toggle the composition display of entities as UTF8 characters."
6280 (interactive)
6281 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6282 (org-restart-font-lock)
6283 (if org-pretty-entities
6284 (message "Entities are now displayed as UTF8 characters")
6285 (save-restriction
6286 (widen)
6287 (org-decompose-region (point-min) (point-max))
6288 (message "Entities are now displayed as plain text"))))
6290 (defvar org-custom-properties-overlays nil
6291 "List of overlays used for custom properties.")
6292 (make-variable-buffer-local 'org-custom-properties-overlays)
6294 (defun org-toggle-custom-properties-visibility ()
6295 "Display or hide properties in `org-custom-properties'."
6296 (interactive)
6297 (if org-custom-properties-overlays
6298 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6299 (setq org-custom-properties-overlays nil))
6300 (unless (not org-custom-properties)
6301 (save-excursion
6302 (save-restriction
6303 (widen)
6304 (goto-char (point-min))
6305 (while (re-search-forward org-property-re nil t)
6306 (mapc (lambda(p)
6307 (when (equal p (substring (match-string 1) 1 -1))
6308 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6309 (overlay-put o 'invisible t)
6310 (overlay-put o 'org-custom-property t)
6311 (push o org-custom-properties-overlays))))
6312 org-custom-properties)))))))
6314 (defun org-fontify-entities (limit)
6315 "Find an entity to fontify."
6316 (let (ee)
6317 (when org-pretty-entities
6318 (catch 'match
6319 (while (re-search-forward
6320 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6321 limit t)
6322 (if (and (not (org-in-indented-comment-line))
6323 (setq ee (org-entity-get (match-string 1)))
6324 (= (length (nth 6 ee)) 1))
6325 (let*
6326 ((end (if (equal (match-string 2) "{}")
6327 (match-end 2)
6328 (match-end 1))))
6329 (add-text-properties
6330 (match-beginning 0) end
6331 (list 'font-lock-fontified t))
6332 (compose-region (match-beginning 0) end
6333 (nth 6 ee) nil)
6334 (backward-char 1)
6335 (throw 'match t))))
6336 nil))))
6338 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6339 "Fontify string S like in Org-mode."
6340 (with-temp-buffer
6341 (insert s)
6342 (let ((org-odd-levels-only odd-levels))
6343 (org-mode)
6344 (font-lock-fontify-buffer)
6345 (buffer-string))))
6347 (defvar org-m nil)
6348 (defvar org-l nil)
6349 (defvar org-f nil)
6350 (defun org-get-level-face (n)
6351 "Get the right face for match N in font-lock matching of headlines."
6352 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6353 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6354 (if org-cycle-level-faces
6355 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6356 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6357 (cond
6358 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6359 ((eq n 2) org-f)
6360 (t (if org-level-color-stars-only nil org-f))))
6363 (defun org-get-todo-face (kwd)
6364 "Get the right face for a TODO keyword KWD.
6365 If KWD is a number, get the corresponding match group."
6366 (if (numberp kwd) (setq kwd (match-string kwd)))
6367 (or (org-face-from-face-or-color
6368 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6369 (and (member kwd org-done-keywords) 'org-done)
6370 'org-todo))
6372 (defun org-face-from-face-or-color (context inherit face-or-color)
6373 "Create a face list that inherits INHERIT, but sets the foreground color.
6374 When FACE-OR-COLOR is not a string, just return it."
6375 (if (stringp face-or-color)
6376 (list :inherit inherit
6377 (cdr (assoc context org-faces-easy-properties))
6378 face-or-color)
6379 face-or-color))
6381 (defun org-font-lock-add-tag-faces (limit)
6382 "Add the special tag faces."
6383 (when (and org-tag-faces org-tags-special-faces-re)
6384 (while (re-search-forward org-tags-special-faces-re limit t)
6385 (add-text-properties (match-beginning 1) (match-end 1)
6386 (list 'face (org-get-tag-face 1)
6387 'font-lock-fontified t))
6388 (backward-char 1))))
6390 (defun org-font-lock-add-priority-faces (limit)
6391 "Add the special priority faces."
6392 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6393 (when (save-match-data (org-at-heading-p))
6394 (add-text-properties
6395 (match-beginning 0) (match-end 0)
6396 (list 'face (or (org-face-from-face-or-color
6397 'priority 'org-priority
6398 (cdr (assoc (char-after (match-beginning 1))
6399 org-priority-faces)))
6400 'org-priority)
6401 'font-lock-fontified t)))))
6403 (defun org-get-tag-face (kwd)
6404 "Get the right face for a TODO keyword KWD.
6405 If KWD is a number, get the corresponding match group."
6406 (if (numberp kwd) (setq kwd (match-string kwd)))
6407 (or (org-face-from-face-or-color
6408 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6409 'org-tag))
6411 (defun org-unfontify-region (beg end &optional maybe_loudly)
6412 "Remove fontification and activation overlays from links."
6413 (font-lock-default-unfontify-region beg end)
6414 (let* ((buffer-undo-list t)
6415 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6416 (inhibit-modification-hooks t)
6417 deactivate-mark buffer-file-name buffer-file-truename)
6418 (org-decompose-region beg end)
6419 (remove-text-properties beg end
6420 '(mouse-face t keymap t org-linked-text t
6421 invisible t intangible t
6422 org-no-flyspell t org-emphasis t))
6423 (org-remove-font-lock-display-properties beg end)))
6425 (defconst org-script-display '(((raise -0.3) (height 0.7))
6426 ((raise 0.3) (height 0.7))
6427 ((raise -0.5))
6428 ((raise 0.5)))
6429 "Display properties for showing superscripts and subscripts.")
6431 (defun org-remove-font-lock-display-properties (beg end)
6432 "Remove specific display properties that have been added by font lock.
6433 The will remove the raise properties that are used to show superscripts
6434 and subscripts."
6435 (let (next prop)
6436 (while (< beg end)
6437 (setq next (next-single-property-change beg 'display nil end)
6438 prop (get-text-property beg 'display))
6439 (if (member prop org-script-display)
6440 (put-text-property beg next 'display nil))
6441 (setq beg next))))
6443 (defun org-raise-scripts (limit)
6444 "Add raise properties to sub/superscripts."
6445 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6446 (if (re-search-forward
6447 (if (eq org-use-sub-superscripts t)
6448 org-match-substring-regexp
6449 org-match-substring-with-braces-regexp)
6450 limit t)
6451 (let* ((pos (point)) table-p comment-p
6452 (mpos (match-beginning 3))
6453 (emph-p (get-text-property mpos 'org-emphasis))
6454 (link-p (get-text-property mpos 'mouse-face))
6455 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6456 (goto-char (point-at-bol))
6457 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6458 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6459 (goto-char pos)
6460 ;; Handle a_b^c
6461 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6462 (if (or comment-p emph-p link-p keyw-p)
6464 (put-text-property (match-beginning 3) (match-end 0)
6465 'display
6466 (if (equal (char-after (match-beginning 2)) ?^)
6467 (nth (if table-p 3 1) org-script-display)
6468 (nth (if table-p 2 0) org-script-display)))
6469 (add-text-properties (match-beginning 2) (match-end 2)
6470 (list 'invisible t
6471 'org-dwidth t 'org-dwidth-n 1))
6472 (if (and (eq (char-after (match-beginning 3)) ?{)
6473 (eq (char-before (match-end 3)) ?}))
6474 (progn
6475 (add-text-properties
6476 (match-beginning 3) (1+ (match-beginning 3))
6477 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6478 (add-text-properties
6479 (1- (match-end 3)) (match-end 3)
6480 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6481 t)))))
6483 ;;;; Visibility cycling, including org-goto and indirect buffer
6485 ;;; Cycling
6487 (defvar org-cycle-global-status nil)
6488 (make-variable-buffer-local 'org-cycle-global-status)
6489 (put 'org-cycle-global-status 'org-state t)
6490 (defvar org-cycle-subtree-status nil)
6491 (make-variable-buffer-local 'org-cycle-subtree-status)
6492 (put 'org-cycle-subtree-status 'org-state t)
6494 (defvar org-inlinetask-min-level)
6496 (defun org-unlogged-message (&rest args)
6497 "Display a message, but avoid logging it in the *Messages* buffer."
6498 (let ((message-log-max nil))
6499 (apply 'message args)))
6501 ;;;###autoload
6502 (defun org-cycle (&optional arg)
6503 "TAB-action and visibility cycling for Org-mode.
6505 This is the command invoked in Org-mode by the TAB key. Its main purpose
6506 is outline visibility cycling, but it also invokes other actions
6507 in special contexts.
6509 - When this function is called with a prefix argument, rotate the entire
6510 buffer through 3 states (global cycling)
6511 1. OVERVIEW: Show only top-level headlines.
6512 2. CONTENTS: Show all headlines of all levels, but no body text.
6513 3. SHOW ALL: Show everything.
6514 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6515 determined by the variable `org-startup-folded', and by any VISIBILITY
6516 properties in the buffer.
6517 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6518 including any drawers.
6520 - When inside a table, re-align the table and move to the next field.
6522 - When point is at the beginning of a headline, rotate the subtree started
6523 by this line through 3 different states (local cycling)
6524 1. FOLDED: Only the main headline is shown.
6525 2. CHILDREN: The main headline and the direct children are shown.
6526 From this state, you can move to one of the children
6527 and zoom in further.
6528 3. SUBTREE: Show the entire subtree, including body text.
6529 If there is no subtree, switch directly from CHILDREN to FOLDED.
6531 - When point is at the beginning of an empty headline and the variable
6532 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6533 of the headline by demoting and promoting it to likely levels. This
6534 speeds up creation document structure by pressing TAB once or several
6535 times right after creating a new headline.
6537 - When there is a numeric prefix, go up to a heading with level ARG, do
6538 a `show-subtree' and return to the previous cursor position. If ARG
6539 is negative, go up that many levels.
6541 - When point is not at the beginning of a headline, execute the global
6542 binding for TAB, which is re-indenting the line. See the option
6543 `org-cycle-emulate-tab' for details.
6545 - Special case: if point is at the beginning of the buffer and there is
6546 no headline in line 1, this function will act as if called with prefix arg
6547 (C-u TAB, same as S-TAB) also when called without prefix arg.
6548 But only if also the variable `org-cycle-global-at-bob' is t."
6549 (interactive "P")
6550 (org-load-modules-maybe)
6551 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6552 (and org-cycle-level-after-item/entry-creation
6553 (or (org-cycle-level)
6554 (org-cycle-item-indentation))))
6555 (let* ((limit-level
6556 (or org-cycle-max-level
6557 (and (boundp 'org-inlinetask-min-level)
6558 org-inlinetask-min-level
6559 (1- org-inlinetask-min-level))))
6560 (nstars (and limit-level
6561 (if org-odd-levels-only
6562 (and limit-level (1- (* limit-level 2)))
6563 limit-level)))
6564 (org-outline-regexp
6565 (if (not (derived-mode-p 'org-mode))
6566 outline-regexp
6567 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6568 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6569 (not (looking-at org-outline-regexp))))
6570 (org-cycle-hook
6571 (if bob-special
6572 (delq 'org-optimize-window-after-visibility-change
6573 (copy-sequence org-cycle-hook))
6574 org-cycle-hook))
6575 (pos (point)))
6577 (if (or bob-special (equal arg '(4)))
6578 ;; special case: use global cycling
6579 (setq arg t))
6581 (cond
6583 ((equal arg '(16))
6584 (setq last-command 'dummy)
6585 (org-set-startup-visibility)
6586 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6588 ((equal arg '(64))
6589 (show-all)
6590 (org-unlogged-message "Entire buffer visible, including drawers"))
6592 ;; Table: enter it or move to the next field.
6593 ((org-at-table-p 'any)
6594 (if (org-at-table.el-p)
6595 (message "Use C-c ' to edit table.el tables")
6596 (if arg (org-table-edit-field t)
6597 (org-table-justify-field-maybe)
6598 (call-interactively 'org-table-next-field))))
6600 ((run-hook-with-args-until-success
6601 'org-tab-after-check-for-table-hook))
6603 ;; Global cycling: delegate to `org-cycle-internal-global'.
6604 ((eq arg t) (org-cycle-internal-global))
6606 ;; Drawers: delegate to `org-flag-drawer'.
6607 ((and org-drawers org-drawer-regexp
6608 (save-excursion
6609 (beginning-of-line 1)
6610 (looking-at org-drawer-regexp)))
6611 (org-flag-drawer ; toggle block visibility
6612 (not (get-char-property (match-end 0) 'invisible))))
6614 ;; Show-subtree, ARG levels up from here.
6615 ((integerp arg)
6616 (save-excursion
6617 (org-back-to-heading)
6618 (outline-up-heading (if (< arg 0) (- arg)
6619 (- (funcall outline-level) arg)))
6620 (org-show-subtree)))
6622 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6623 ((and (featurep 'org-inlinetask)
6624 (org-inlinetask-at-task-p)
6625 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6626 (org-inlinetask-toggle-visibility))
6628 ((org-try-cdlatex-tab))
6630 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6631 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6632 (save-excursion (beginning-of-line 1)
6633 (looking-at org-outline-regexp)))
6634 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6635 (org-cycle-internal-local))
6637 ;; From there: TAB emulation and template completion.
6638 (buffer-read-only (org-back-to-heading))
6640 ((run-hook-with-args-until-success
6641 'org-tab-after-check-for-cycling-hook))
6643 ((org-try-structure-completion))
6645 ((run-hook-with-args-until-success
6646 'org-tab-before-tab-emulation-hook))
6648 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6649 (or (not (bolp))
6650 (not (looking-at org-outline-regexp))))
6651 (call-interactively (global-key-binding "\t")))
6653 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6654 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6655 (or (and (eq org-cycle-emulate-tab 'white)
6656 (= (match-end 0) (point-at-eol)))
6657 (and (eq org-cycle-emulate-tab 'whitestart)
6658 (>= (match-end 0) pos))))
6660 (eq org-cycle-emulate-tab t))
6661 (call-interactively (global-key-binding "\t")))
6663 (t (save-excursion
6664 (org-back-to-heading)
6665 (org-cycle)))))))
6667 (defun org-cycle-internal-global ()
6668 "Do the global cycling action."
6669 ;; Hack to avoid display of messages for .org attachments in Gnus
6670 (let ((ga (string-match "\\*fontification" (buffer-name))))
6671 (cond
6672 ((and (eq last-command this-command)
6673 (eq org-cycle-global-status 'overview))
6674 ;; We just created the overview - now do table of contents
6675 ;; This can be slow in very large buffers, so indicate action
6676 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6677 (unless ga (org-unlogged-message "CONTENTS..."))
6678 (org-content)
6679 (unless ga (org-unlogged-message "CONTENTS...done"))
6680 (setq org-cycle-global-status 'contents)
6681 (run-hook-with-args 'org-cycle-hook 'contents))
6683 ((and (eq last-command this-command)
6684 (eq org-cycle-global-status 'contents))
6685 ;; We just showed the table of contents - now show everything
6686 (run-hook-with-args 'org-pre-cycle-hook 'all)
6687 (show-all)
6688 (unless ga (org-unlogged-message "SHOW ALL"))
6689 (setq org-cycle-global-status 'all)
6690 (run-hook-with-args 'org-cycle-hook 'all))
6693 ;; Default action: go to overview
6694 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6695 (org-overview)
6696 (unless ga (org-unlogged-message "OVERVIEW"))
6697 (setq org-cycle-global-status 'overview)
6698 (run-hook-with-args 'org-cycle-hook 'overview)))))
6700 (defvar org-called-with-limited-levels);Dyn-bound in ̀org-with-limited-levels'.
6702 (defun org-cycle-internal-local ()
6703 "Do the local cycling action."
6704 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6705 ;; First, determine end of headline (EOH), end of subtree or item
6706 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6707 (save-excursion
6708 (if (org-at-item-p)
6709 (progn
6710 (beginning-of-line)
6711 (setq struct (org-list-struct))
6712 (setq eoh (point-at-eol))
6713 (setq eos (org-list-get-item-end-before-blank (point) struct))
6714 (setq has-children (org-list-has-child-p (point) struct)))
6715 (org-back-to-heading)
6716 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6717 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6718 (setq has-children
6719 (or (save-excursion
6720 (let ((level (funcall outline-level)))
6721 (outline-next-heading)
6722 (and (org-at-heading-p t)
6723 (> (funcall outline-level) level))))
6724 (save-excursion
6725 (org-list-search-forward (org-item-beginning-re) eos t)))))
6726 ;; Determine end invisible part of buffer (EOL)
6727 (beginning-of-line 2)
6728 ;; XEmacs doesn't have `next-single-char-property-change'
6729 (if (featurep 'xemacs)
6730 (while (and (not (eobp)) ;; this is like `next-line'
6731 (get-char-property (1- (point)) 'invisible))
6732 (beginning-of-line 2))
6733 (while (and (not (eobp)) ;; this is like `next-line'
6734 (get-char-property (1- (point)) 'invisible))
6735 (goto-char (next-single-char-property-change (point) 'invisible))
6736 (and (eolp) (beginning-of-line 2))))
6737 (setq eol (point)))
6738 ;; Find out what to do next and set `this-command'
6739 (cond
6740 ((= eos eoh)
6741 ;; Nothing is hidden behind this heading
6742 (unless (org-before-first-heading-p)
6743 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6744 (org-unlogged-message "EMPTY ENTRY")
6745 (setq org-cycle-subtree-status nil)
6746 (save-excursion
6747 (goto-char eos)
6748 (outline-next-heading)
6749 (if (outline-invisible-p) (org-flag-heading nil))))
6750 ((and (or (>= eol eos)
6751 (not (string-match "\\S-" (buffer-substring eol eos))))
6752 (or has-children
6753 (not (setq children-skipped
6754 org-cycle-skip-children-state-if-no-children))))
6755 ;; Entire subtree is hidden in one line: children view
6756 (unless (org-before-first-heading-p)
6757 (run-hook-with-args 'org-pre-cycle-hook 'children))
6758 (if (org-at-item-p)
6759 (org-list-set-item-visibility (point-at-bol) struct 'children)
6760 (org-show-entry)
6761 (org-with-limited-levels (show-children))
6762 ;; FIXME: This slows down the func way too much.
6763 ;; How keep drawers hidden in subtree anyway?
6764 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6765 ;; (org-cycle-hide-drawers 'subtree))
6767 ;; Fold every list in subtree to top-level items.
6768 (when (eq org-cycle-include-plain-lists 'integrate)
6769 (save-excursion
6770 (org-back-to-heading)
6771 (while (org-list-search-forward (org-item-beginning-re) eos t)
6772 (beginning-of-line 1)
6773 (let* ((struct (org-list-struct))
6774 (prevs (org-list-prevs-alist struct))
6775 (end (org-list-get-bottom-point struct)))
6776 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6777 (org-list-get-all-items (point) struct prevs))
6778 (goto-char (if (< end eos) end eos)))))))
6779 (org-unlogged-message "CHILDREN")
6780 (save-excursion
6781 (goto-char eos)
6782 (outline-next-heading)
6783 (if (outline-invisible-p) (org-flag-heading nil)))
6784 (setq org-cycle-subtree-status 'children)
6785 (unless (org-before-first-heading-p)
6786 (run-hook-with-args 'org-cycle-hook 'children)))
6787 ((or children-skipped
6788 (and (eq last-command this-command)
6789 (eq org-cycle-subtree-status 'children)))
6790 ;; We just showed the children, or no children are there,
6791 ;; now show everything.
6792 (unless (org-before-first-heading-p)
6793 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6794 (outline-flag-region eoh eos nil)
6795 (org-unlogged-message
6796 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6797 (setq org-cycle-subtree-status 'subtree)
6798 (unless (org-before-first-heading-p)
6799 (run-hook-with-args 'org-cycle-hook 'subtree)))
6801 ;; Default action: hide the subtree.
6802 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6803 (outline-flag-region eoh eos t)
6804 (org-unlogged-message "FOLDED")
6805 (setq org-cycle-subtree-status 'folded)
6806 (unless (org-before-first-heading-p)
6807 (run-hook-with-args 'org-cycle-hook 'folded))))))
6809 ;;;###autoload
6810 (defun org-global-cycle (&optional arg)
6811 "Cycle the global visibility. For details see `org-cycle'.
6812 With \\[universal-argument] prefix arg, switch to startup visibility.
6813 With a numeric prefix, show all headlines up to that level."
6814 (interactive "P")
6815 (let ((org-cycle-include-plain-lists
6816 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6817 (cond
6818 ((integerp arg)
6819 (show-all)
6820 (hide-sublevels arg)
6821 (setq org-cycle-global-status 'contents))
6822 ((equal arg '(4))
6823 (org-set-startup-visibility)
6824 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6826 (org-cycle '(4))))))
6828 (defun org-set-startup-visibility ()
6829 "Set the visibility required by startup options and properties."
6830 (cond
6831 ((eq org-startup-folded t)
6832 (org-overview))
6833 ((eq org-startup-folded 'content)
6834 (org-content))
6835 ((or (eq org-startup-folded 'showeverything)
6836 (eq org-startup-folded nil))
6837 (show-all)))
6838 (unless (eq org-startup-folded 'showeverything)
6839 (if org-hide-block-startup (org-hide-block-all))
6840 (org-set-visibility-according-to-property 'no-cleanup)
6841 (org-cycle-hide-archived-subtrees 'all)
6842 (org-cycle-hide-drawers 'all)
6843 (org-cycle-show-empty-lines t)))
6845 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6846 "Switch subtree visibilities according to :VISIBILITY: property."
6847 (interactive)
6848 (let (org-show-entry-below state)
6849 (save-excursion
6850 (goto-char (point-min))
6851 (while (re-search-forward
6852 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6853 nil t)
6854 (setq state (match-string 1))
6855 (save-excursion
6856 (org-back-to-heading t)
6857 (hide-subtree)
6858 (org-reveal)
6859 (cond
6860 ((equal state '("fold" "folded"))
6861 (hide-subtree))
6862 ((equal state "children")
6863 (org-show-hidden-entry)
6864 (show-children))
6865 ((equal state "content")
6866 (save-excursion
6867 (save-restriction
6868 (org-narrow-to-subtree)
6869 (org-content))))
6870 ((member state '("all" "showall"))
6871 (show-subtree)))))
6872 (unless no-cleanup
6873 (org-cycle-hide-archived-subtrees 'all)
6874 (org-cycle-hide-drawers 'all)
6875 (org-cycle-show-empty-lines 'all)))))
6877 ;; This function uses outline-regexp instead of the more fundamental
6878 ;; org-outline-regexp so that org-cycle-global works outside of Org
6879 ;; buffers, where outline-regexp is needed.
6880 (defun org-overview ()
6881 "Switch to overview mode, showing only top-level headlines.
6882 Really, this shows all headlines with level equal or greater than the level
6883 of the first headline in the buffer. This is important, because if the
6884 first headline is not level one, then (hide-sublevels 1) gives confusing
6885 results."
6886 (interactive)
6887 (let ((pos (point))
6888 (level (save-excursion
6889 (goto-char (point-min))
6890 (if (re-search-forward (concat "^" outline-regexp) nil t)
6891 (progn
6892 (goto-char (match-beginning 0))
6893 (funcall outline-level))))))
6894 (and level (hide-sublevels level))
6895 (recenter '(4))
6896 (goto-char pos)))
6898 (defun org-content (&optional arg)
6899 "Show all headlines in the buffer, like a table of contents.
6900 With numerical argument N, show content up to level N."
6901 (interactive "P")
6902 (org-overview)
6903 (save-excursion
6904 ;; Visit all headings and show their offspring
6905 (and (integerp arg) (org-overview))
6906 (goto-char (point-max))
6907 (catch 'exit
6908 (while (and (progn (condition-case nil
6909 (outline-previous-visible-heading 1)
6910 (error (goto-char (point-min))))
6912 (looking-at org-outline-regexp))
6913 (if (integerp arg)
6914 (show-children (1- arg))
6915 (show-branches))
6916 (if (bobp) (throw 'exit nil))))))
6918 (defun org-optimize-window-after-visibility-change (state)
6919 "Adjust the window after a change in outline visibility.
6920 This function is the default value of the hook `org-cycle-hook'."
6921 (when (get-buffer-window (current-buffer))
6922 (cond
6923 ((eq state 'content) nil)
6924 ((eq state 'all) nil)
6925 ((eq state 'folded) nil)
6926 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6927 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6929 (defun org-remove-empty-overlays-at (pos)
6930 "Remove outline overlays that do not contain non-white stuff."
6931 (mapc
6932 (lambda (o)
6933 (and (eq 'outline (overlay-get o 'invisible))
6934 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6935 (overlay-end o))))
6936 (delete-overlay o)))
6937 (overlays-at pos)))
6939 (defun org-clean-visibility-after-subtree-move ()
6940 "Fix visibility issues after moving a subtree."
6941 ;; First, find a reasonable region to look at:
6942 ;; Start two siblings above, end three below
6943 (let* ((beg (save-excursion
6944 (and (org-get-last-sibling)
6945 (org-get-last-sibling))
6946 (point)))
6947 (end (save-excursion
6948 (and (org-get-next-sibling)
6949 (org-get-next-sibling)
6950 (org-get-next-sibling))
6951 (if (org-at-heading-p)
6952 (point-at-eol)
6953 (point))))
6954 (level (looking-at "\\*+"))
6955 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6956 (save-excursion
6957 (save-restriction
6958 (narrow-to-region beg end)
6959 (when re
6960 ;; Properly fold already folded siblings
6961 (goto-char (point-min))
6962 (while (re-search-forward re nil t)
6963 (if (and (not (outline-invisible-p))
6964 (save-excursion
6965 (goto-char (point-at-eol)) (outline-invisible-p)))
6966 (hide-entry))))
6967 (org-cycle-show-empty-lines 'overview)
6968 (org-cycle-hide-drawers 'overview)))))
6970 (defun org-cycle-show-empty-lines (state)
6971 "Show empty lines above all visible headlines.
6972 The region to be covered depends on STATE when called through
6973 `org-cycle-hook'. Lisp program can use t for STATE to get the
6974 entire buffer covered. Note that an empty line is only shown if there
6975 are at least `org-cycle-separator-lines' empty lines before the headline."
6976 (when (not (= org-cycle-separator-lines 0))
6977 (save-excursion
6978 (let* ((n (abs org-cycle-separator-lines))
6979 (re (cond
6980 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6981 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6982 (t (let ((ns (number-to-string (- n 2))))
6983 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6984 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6985 beg end b e)
6986 (cond
6987 ((memq state '(overview contents t))
6988 (setq beg (point-min) end (point-max)))
6989 ((memq state '(children folded))
6990 (setq beg (point) end (progn (org-end-of-subtree t t)
6991 (beginning-of-line 2)
6992 (point)))))
6993 (when beg
6994 (goto-char beg)
6995 (while (re-search-forward re end t)
6996 (unless (get-char-property (match-end 1) 'invisible)
6997 (setq e (match-end 1))
6998 (if (< org-cycle-separator-lines 0)
6999 (setq b (save-excursion
7000 (goto-char (match-beginning 0))
7001 (org-back-over-empty-lines)
7002 (if (save-excursion
7003 (goto-char (max (point-min) (1- (point))))
7004 (org-at-heading-p))
7005 (1- (point))
7006 (point))))
7007 (setq b (match-beginning 1)))
7008 (outline-flag-region b e nil)))))))
7009 ;; Never hide empty lines at the end of the file.
7010 (save-excursion
7011 (goto-char (point-max))
7012 (outline-previous-heading)
7013 (outline-end-of-heading)
7014 (if (and (looking-at "[ \t\n]+")
7015 (= (match-end 0) (point-max)))
7016 (outline-flag-region (point) (match-end 0) nil))))
7018 (defun org-show-empty-lines-in-parent ()
7019 "Move to the parent and re-show empty lines before visible headlines."
7020 (save-excursion
7021 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7022 (org-cycle-show-empty-lines context))))
7024 (defun org-files-list ()
7025 "Return `org-agenda-files' list, plus all open org-mode files.
7026 This is useful for operations that need to scan all of a user's
7027 open and agenda-wise Org files."
7028 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7029 (dolist (buf (buffer-list))
7030 (with-current-buffer buf
7031 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7032 (let ((file (expand-file-name (buffer-file-name))))
7033 (unless (member file files)
7034 (push file files))))))
7035 files))
7037 (defsubst org-entry-beginning-position ()
7038 "Return the beginning position of the current entry."
7039 (save-excursion (outline-back-to-heading t) (point)))
7041 (defsubst org-entry-end-position ()
7042 "Return the end position of the current entry."
7043 (save-excursion (outline-next-heading) (point)))
7045 (defun org-cycle-hide-drawers (state)
7046 "Re-hide all drawers after a visibility state change."
7047 (when (and (derived-mode-p 'org-mode)
7048 (not (memq state '(overview folded contents))))
7049 (save-excursion
7050 (let* ((globalp (memq state '(contents all)))
7051 (beg (if globalp (point-min) (point)))
7052 (end (if globalp (point-max)
7053 (if (eq state 'children)
7054 (save-excursion (outline-next-heading) (point))
7055 (org-end-of-subtree t)))))
7056 (goto-char beg)
7057 (while (re-search-forward org-drawer-regexp end t)
7058 (org-flag-drawer t))))))
7060 (defun org-cycle-hide-inline-tasks (state)
7061 "Re-hide inline tasks when switching to 'contents or 'children
7062 visibility state."
7063 (case state
7064 (contents
7065 (when (org-bound-and-true-p org-inlinetask-min-level)
7066 (hide-sublevels (1- org-inlinetask-min-level))))
7067 (children
7068 (when (featurep 'org-inlinetask)
7069 (save-excursion
7070 (while (and (outline-next-heading)
7071 (org-inlinetask-at-task-p))
7072 (org-inlinetask-toggle-visibility)
7073 (org-inlinetask-goto-end)))))))
7075 (defun org-flag-drawer (flag)
7076 "When FLAG is non-nil, hide the drawer we are within.
7077 Otherwise make it visible."
7078 (save-excursion
7079 (beginning-of-line 1)
7080 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7081 (let ((b (match-end 0)))
7082 (if (re-search-forward
7083 "^[ \t]*:END:"
7084 (save-excursion (outline-next-heading) (point)) t)
7085 (outline-flag-region b (point-at-eol) flag)
7086 (user-error ":END: line missing at position %s" b))))))
7088 (defun org-subtree-end-visible-p ()
7089 "Is the end of the current subtree visible?"
7090 (pos-visible-in-window-p
7091 (save-excursion (org-end-of-subtree t) (point))))
7093 (defun org-first-headline-recenter (&optional N)
7094 "Move cursor to the first headline and recenter the headline.
7095 Optional argument N means put the headline into the Nth line of the window."
7096 (goto-char (point-min))
7097 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7098 (beginning-of-line)
7099 (recenter (prefix-numeric-value N))))
7101 ;;; Saving and restoring visibility
7103 (defun org-outline-overlay-data (&optional use-markers)
7104 "Return a list of the locations of all outline overlays.
7105 These are overlays with the `invisible' property value `outline'.
7106 The return value is a list of cons cells, with start and stop
7107 positions for each overlay.
7108 If USE-MARKERS is set, return the positions as markers."
7109 (let (beg end)
7110 (save-excursion
7111 (save-restriction
7112 (widen)
7113 (delq nil
7114 (mapcar (lambda (o)
7115 (when (eq (overlay-get o 'invisible) 'outline)
7116 (setq beg (overlay-start o)
7117 end (overlay-end o))
7118 (and beg end (> end beg)
7119 (if use-markers
7120 (cons (move-marker (make-marker) beg)
7121 (move-marker (make-marker) end))
7122 (cons beg end)))))
7123 (overlays-in (point-min) (point-max))))))))
7125 (defun org-set-outline-overlay-data (data)
7126 "Create visibility overlays for all positions in DATA.
7127 DATA should have been made by `org-outline-overlay-data'."
7128 (let (o)
7129 (save-excursion
7130 (save-restriction
7131 (widen)
7132 (show-all)
7133 (mapc (lambda (c)
7134 (outline-flag-region (car c) (cdr c) t))
7135 data)))))
7137 ;;; Folding of blocks
7139 (defvar org-hide-block-overlays nil
7140 "Overlays hiding blocks.")
7141 (make-variable-buffer-local 'org-hide-block-overlays)
7143 (defun org-block-map (function &optional start end)
7144 "Call FUNCTION at the head of all source blocks in the current buffer.
7145 Optional arguments START and END can be used to limit the range."
7146 (let ((start (or start (point-min)))
7147 (end (or end (point-max))))
7148 (save-excursion
7149 (goto-char start)
7150 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7151 (save-excursion
7152 (save-match-data
7153 (goto-char (match-beginning 0))
7154 (funcall function)))))))
7156 (defun org-hide-block-toggle-all ()
7157 "Toggle the visibility of all blocks in the current buffer."
7158 (org-block-map #'org-hide-block-toggle))
7160 (defun org-hide-block-all ()
7161 "Fold all blocks in the current buffer."
7162 (interactive)
7163 (org-show-block-all)
7164 (org-block-map #'org-hide-block-toggle-maybe))
7166 (defun org-show-block-all ()
7167 "Unfold all blocks in the current buffer."
7168 (interactive)
7169 (mapc 'delete-overlay org-hide-block-overlays)
7170 (setq org-hide-block-overlays nil))
7172 (defun org-hide-block-toggle-maybe ()
7173 "Toggle visibility of block at point."
7174 (interactive)
7175 (let ((case-fold-search t))
7176 (if (save-excursion
7177 (beginning-of-line 1)
7178 (looking-at org-block-regexp))
7179 (progn (org-hide-block-toggle)
7180 t) ;; to signal that we took action
7181 nil))) ;; to signal that we did not
7183 (defun org-hide-block-toggle (&optional force)
7184 "Toggle the visibility of the current block."
7185 (interactive)
7186 (save-excursion
7187 (beginning-of-line)
7188 (if (re-search-forward org-block-regexp nil t)
7189 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7190 (end (match-end 0)) ;; end of entire body
7192 (if (memq t (mapcar (lambda (overlay)
7193 (eq (overlay-get overlay 'invisible)
7194 'org-hide-block))
7195 (overlays-at start)))
7196 (if (or (not force) (eq force 'off))
7197 (mapc (lambda (ov)
7198 (when (member ov org-hide-block-overlays)
7199 (setq org-hide-block-overlays
7200 (delq ov org-hide-block-overlays)))
7201 (when (eq (overlay-get ov 'invisible)
7202 'org-hide-block)
7203 (delete-overlay ov)))
7204 (overlays-at start)))
7205 (setq ov (make-overlay start end))
7206 (overlay-put ov 'invisible 'org-hide-block)
7207 ;; make the block accessible to isearch
7208 (overlay-put
7209 ov 'isearch-open-invisible
7210 (lambda (ov)
7211 (when (member ov org-hide-block-overlays)
7212 (setq org-hide-block-overlays
7213 (delq ov org-hide-block-overlays)))
7214 (when (eq (overlay-get ov 'invisible)
7215 'org-hide-block)
7216 (delete-overlay ov))))
7217 (push ov org-hide-block-overlays)))
7218 (user-error "Not looking at a source block"))))
7220 ;; org-tab-after-check-for-cycling-hook
7221 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7222 ;; Remove overlays when changing major mode
7223 (add-hook 'org-mode-hook
7224 (lambda () (org-add-hook 'change-major-mode-hook
7225 'org-show-block-all 'append 'local)))
7227 ;;; Org-goto
7229 (defvar org-goto-window-configuration nil)
7230 (defvar org-goto-marker nil)
7231 (defvar org-goto-map)
7232 (defun org-goto-map ()
7233 "Set the keymap `org-goto'."
7234 (setq org-goto-map
7235 (let ((map (make-sparse-keymap)))
7236 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7237 mouse-drag-region universal-argument org-occur))
7238 cmd)
7239 (while (setq cmd (pop cmds))
7240 (substitute-key-definition cmd cmd map global-map)))
7241 (suppress-keymap map)
7242 (org-defkey map "\C-m" 'org-goto-ret)
7243 (org-defkey map [(return)] 'org-goto-ret)
7244 (org-defkey map [(left)] 'org-goto-left)
7245 (org-defkey map [(right)] 'org-goto-right)
7246 (org-defkey map [(control ?g)] 'org-goto-quit)
7247 (org-defkey map "\C-i" 'org-cycle)
7248 (org-defkey map [(tab)] 'org-cycle)
7249 (org-defkey map [(down)] 'outline-next-visible-heading)
7250 (org-defkey map [(up)] 'outline-previous-visible-heading)
7251 (if org-goto-auto-isearch
7252 (if (fboundp 'define-key-after)
7253 (define-key-after map [t] 'org-goto-local-auto-isearch)
7254 nil)
7255 (org-defkey map "q" 'org-goto-quit)
7256 (org-defkey map "n" 'outline-next-visible-heading)
7257 (org-defkey map "p" 'outline-previous-visible-heading)
7258 (org-defkey map "f" 'outline-forward-same-level)
7259 (org-defkey map "b" 'outline-backward-same-level)
7260 (org-defkey map "u" 'outline-up-heading))
7261 (org-defkey map "/" 'org-occur)
7262 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7263 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7264 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7265 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7266 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7267 map)))
7269 (defconst org-goto-help
7270 "Browse buffer copy, to find location or copy text.%s
7271 RET=jump to location C-g=quit and return to previous location
7272 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7274 (defvar org-goto-start-pos) ; dynamically scoped parameter
7276 (defun org-goto (&optional alternative-interface)
7277 "Look up a different location in the current file, keeping current visibility.
7279 When you want look-up or go to a different location in a
7280 document, the fastest way is often to fold the entire buffer and
7281 then dive into the tree. This method has the disadvantage, that
7282 the previous location will be folded, which may not be what you
7283 want.
7285 This command works around this by showing a copy of the current
7286 buffer in an indirect buffer, in overview mode. You can dive
7287 into the tree in that copy, use org-occur and incremental search
7288 to find a location. When pressing RET or `Q', the command
7289 returns to the original buffer in which the visibility is still
7290 unchanged. After RET it will also jump to the location selected
7291 in the indirect buffer and expose the headline hierarchy above.
7293 With a prefix argument, use the alternative interface: e.g. if
7294 `org-goto-interface' is 'outline use 'outline-path-completion."
7295 (interactive "P")
7296 (org-goto-map)
7297 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7298 (org-refile-use-outline-path t)
7299 (org-refile-target-verify-function nil)
7300 (interface
7301 (if (not alternative-interface)
7302 org-goto-interface
7303 (if (eq org-goto-interface 'outline)
7304 'outline-path-completion
7305 'outline)))
7306 (org-goto-start-pos (point))
7307 (selected-point
7308 (if (eq interface 'outline)
7309 (car (org-get-location (current-buffer) org-goto-help))
7310 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7311 (org-refile-check-position pa)
7312 (nth 3 pa)))))
7313 (if selected-point
7314 (progn
7315 (org-mark-ring-push org-goto-start-pos)
7316 (goto-char selected-point)
7317 (if (or (outline-invisible-p) (org-invisible-p2))
7318 (org-show-context 'org-goto)))
7319 (message "Quit"))))
7321 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7322 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7323 (defvar org-goto-local-auto-isearch-map) ; defined below
7325 (defun org-get-location (buf help)
7326 "Let the user select a location in the Org-mode buffer BUF.
7327 This function uses a recursive edit. It returns the selected position
7328 or nil."
7329 (org-no-popups
7330 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7331 (isearch-hide-immediately nil)
7332 (isearch-search-fun-function
7333 (lambda () 'org-goto-local-search-headings))
7334 (org-goto-selected-point org-goto-exit-command))
7335 (save-excursion
7336 (save-window-excursion
7337 (delete-other-windows)
7338 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7339 (org-pop-to-buffer-same-window
7340 (condition-case nil
7341 (make-indirect-buffer (current-buffer) "*org-goto*")
7342 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7343 (with-output-to-temp-buffer "*Org Help*"
7344 (princ (format help (if org-goto-auto-isearch
7345 " Just type for auto-isearch."
7346 " n/p/f/b/u to navigate, q to quit."))))
7347 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7348 (setq buffer-read-only nil)
7349 (let ((org-startup-truncated t)
7350 (org-startup-folded nil)
7351 (org-startup-align-all-tables nil))
7352 (org-mode)
7353 (org-overview))
7354 (setq buffer-read-only t)
7355 (if (and (boundp 'org-goto-start-pos)
7356 (integer-or-marker-p org-goto-start-pos))
7357 (let ((org-show-hierarchy-above t)
7358 (org-show-siblings t)
7359 (org-show-following-heading t))
7360 (goto-char org-goto-start-pos)
7361 (and (outline-invisible-p) (org-show-context)))
7362 (goto-char (point-min)))
7363 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7364 (message "Select location and press RET")
7365 (use-local-map org-goto-map)
7366 (recursive-edit)))
7367 (kill-buffer "*org-goto*")
7368 (cons org-goto-selected-point org-goto-exit-command))))
7370 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7371 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7372 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7373 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7375 (defun org-goto-local-search-headings (string bound noerror)
7376 "Search and make sure that any matches are in headlines."
7377 (catch 'return
7378 (while (if isearch-forward
7379 (search-forward string bound noerror)
7380 (search-backward string bound noerror))
7381 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7382 (and (member :headline context)
7383 (not (member :tags context))))
7384 (throw 'return (point))))))
7386 (defun org-goto-local-auto-isearch ()
7387 "Start isearch."
7388 (interactive)
7389 (goto-char (point-min))
7390 (let ((keys (this-command-keys)))
7391 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7392 (isearch-mode t)
7393 (isearch-process-search-char (string-to-char keys)))))
7395 (defun org-goto-ret (&optional arg)
7396 "Finish `org-goto' by going to the new location."
7397 (interactive "P")
7398 (setq org-goto-selected-point (point)
7399 org-goto-exit-command 'return)
7400 (throw 'exit nil))
7402 (defun org-goto-left ()
7403 "Finish `org-goto' by going to the new location."
7404 (interactive)
7405 (if (org-at-heading-p)
7406 (progn
7407 (beginning-of-line 1)
7408 (setq org-goto-selected-point (point)
7409 org-goto-exit-command 'left)
7410 (throw 'exit nil))
7411 (user-error "Not on a heading")))
7413 (defun org-goto-right ()
7414 "Finish `org-goto' by going to the new location."
7415 (interactive)
7416 (if (org-at-heading-p)
7417 (progn
7418 (setq org-goto-selected-point (point)
7419 org-goto-exit-command 'right)
7420 (throw 'exit nil))
7421 (user-error "Not on a heading")))
7423 (defun org-goto-quit ()
7424 "Finish `org-goto' without cursor motion."
7425 (interactive)
7426 (setq org-goto-selected-point nil)
7427 (setq org-goto-exit-command 'quit)
7428 (throw 'exit nil))
7430 ;;; Indirect buffer display of subtrees
7432 (defvar org-indirect-dedicated-frame nil
7433 "This is the frame being used for indirect tree display.")
7434 (defvar org-last-indirect-buffer nil)
7436 (defun org-tree-to-indirect-buffer (&optional arg)
7437 "Create indirect buffer and narrow it to current subtree.
7438 With a numerical prefix ARG, go up to this level and then take that tree.
7439 If ARG is negative, go up that many levels.
7441 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7442 indirect buffer previously made with this command, to avoid proliferation of
7443 indirect buffers. However, when you call the command with a \
7444 \\[universal-argument] prefix, or
7445 when `org-indirect-buffer-display' is `new-frame', the last buffer
7446 is kept so that you can work with several indirect buffers at the same time.
7447 If `org-indirect-buffer-display' is `dedicated-frame', the \
7448 \\[universal-argument] prefix also
7449 requests that a new frame be made for the new buffer, so that the dedicated
7450 frame is not changed."
7451 (interactive "P")
7452 (let ((cbuf (current-buffer))
7453 (cwin (selected-window))
7454 (pos (point))
7455 beg end level heading ibuf)
7456 (save-excursion
7457 (org-back-to-heading t)
7458 (when (numberp arg)
7459 (setq level (org-outline-level))
7460 (if (< arg 0) (setq arg (+ level arg)))
7461 (while (> (setq level (org-outline-level)) arg)
7462 (org-up-heading-safe)))
7463 (setq beg (point)
7464 heading (org-get-heading))
7465 (org-end-of-subtree t t)
7466 (if (org-at-heading-p) (backward-char 1))
7467 (setq end (point)))
7468 (if (and (buffer-live-p org-last-indirect-buffer)
7469 (not (eq org-indirect-buffer-display 'new-frame))
7470 (not arg))
7471 (kill-buffer org-last-indirect-buffer))
7472 (setq ibuf (org-get-indirect-buffer cbuf)
7473 org-last-indirect-buffer ibuf)
7474 (cond
7475 ((or (eq org-indirect-buffer-display 'new-frame)
7476 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7477 (select-frame (make-frame))
7478 (delete-other-windows)
7479 (org-pop-to-buffer-same-window ibuf)
7480 (org-set-frame-title heading))
7481 ((eq org-indirect-buffer-display 'dedicated-frame)
7482 (raise-frame
7483 (select-frame (or (and org-indirect-dedicated-frame
7484 (frame-live-p org-indirect-dedicated-frame)
7485 org-indirect-dedicated-frame)
7486 (setq org-indirect-dedicated-frame (make-frame)))))
7487 (delete-other-windows)
7488 (org-pop-to-buffer-same-window ibuf)
7489 (org-set-frame-title (concat "Indirect: " heading)))
7490 ((eq org-indirect-buffer-display 'current-window)
7491 (org-pop-to-buffer-same-window ibuf))
7492 ((eq org-indirect-buffer-display 'other-window)
7493 (pop-to-buffer ibuf))
7494 (t (error "Invalid value")))
7495 (if (featurep 'xemacs)
7496 (save-excursion (org-mode) (turn-on-font-lock)))
7497 (narrow-to-region beg end)
7498 (show-all)
7499 (goto-char pos)
7500 (run-hook-with-args 'org-cycle-hook 'all)
7501 (and (window-live-p cwin) (select-window cwin))))
7503 (defun org-get-indirect-buffer (&optional buffer)
7504 (setq buffer (or buffer (current-buffer)))
7505 (let ((n 1) (base (buffer-name buffer)) bname)
7506 (while (buffer-live-p
7507 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7508 (setq n (1+ n)))
7509 (condition-case nil
7510 (make-indirect-buffer buffer bname 'clone)
7511 (error (make-indirect-buffer buffer bname)))))
7513 (defun org-set-frame-title (title)
7514 "Set the title of the current frame to the string TITLE."
7515 ;; FIXME: how to name a single frame in XEmacs???
7516 (unless (featurep 'xemacs)
7517 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7519 ;;;; Structure editing
7521 ;;; Inserting headlines
7523 (defun org-previous-line-empty-p (&optional next)
7524 "Is the previous line a blank line?
7525 When NEXT is non-nil, check the next line instead."
7526 (save-excursion
7527 (and (not (bobp))
7528 (or (beginning-of-line (if next 2 0)) t)
7529 (save-match-data
7530 (looking-at "[ \t]*$")))))
7532 (defun org-insert-heading (&optional arg invisible-ok)
7533 "Insert a new heading or item with same depth at point.
7534 If point is in a plain list and ARG is nil, create a new list item.
7535 With one universal prefix argument, insert a heading even in lists.
7536 With two universal prefix arguments, insert the heading at the end
7537 of the parent subtree.
7539 If point is at the beginning of a headline, insert a sibling before
7540 the current headline. If point is not at the beginning, split the line
7541 and create a new headline with the text in the current line after point
7542 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7544 If point is at the beginning of a normal line, turn this line into
7545 a heading.
7547 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7548 This is important for non-interactive uses of the command."
7549 (interactive "P")
7550 (if (org-called-interactively-p 'any) (org-reveal))
7551 (let ((itemp (org-in-item-p))
7552 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7553 (respect-content (or org-insert-heading-respect-content
7554 (equal arg '(4))))
7555 (initial-content "")
7556 (adjust-empty-lines t))
7558 (cond
7560 ((or (= (buffer-size) 0)
7561 (and (not (save-excursion
7562 (and (ignore-errors (org-back-to-heading invisible-ok))
7563 (org-at-heading-p))))
7564 (or arg (not itemp))))
7565 ;; At beginning of buffer or so high up that only a heading
7566 ;; makes sense.
7567 (insert
7568 (if (or (bobp) (org-previous-line-empty-p)) "" "\n")
7569 (if (org-in-src-block-p) ",* " "* "))
7570 (run-hooks 'org-insert-heading-hook))
7572 ((and itemp (not (equal arg '(4))))
7573 ;; Insert an item
7574 (org-insert-item))
7577 ;; Maybe move at the end of the subtree
7578 (when (equal arg '(16))
7579 (org-up-heading-safe)
7580 (org-end-of-subtree t))
7581 ;; Insert a heading
7582 (save-restriction
7583 (widen)
7584 (let* ((level nil)
7585 (on-heading (org-at-heading-p))
7586 (empty-line-p (if on-heading
7587 (org-previous-line-empty-p)
7588 ;; We will decide later
7589 nil))
7590 ;; Get a level string to fall back on
7591 (fix-level
7592 (save-excursion
7593 (org-back-to-heading t)
7594 (if (org-previous-line-empty-p) (setq empty-line-p t))
7595 (looking-at org-outline-regexp)
7596 (make-string (1- (length (match-string 0))) ?*)))
7597 (stars
7598 (save-excursion
7599 (condition-case nil
7600 (progn
7601 (org-back-to-heading invisible-ok)
7602 (when (and (not on-heading)
7603 (featurep 'org-inlinetask)
7604 (integerp org-inlinetask-min-level)
7605 (>= (length (match-string 0))
7606 org-inlinetask-min-level))
7607 ;; Find a heading level before the inline task
7608 (while (and (setq level (org-up-heading-safe))
7609 (>= level org-inlinetask-min-level)))
7610 (if (org-at-heading-p)
7611 (org-back-to-heading invisible-ok)
7612 (error "This should not happen")))
7613 (unless (and (save-excursion
7614 (save-match-data
7615 (org-backward-heading-same-level
7616 1 invisible-ok))
7617 (= (point) (match-beginning 0)))
7618 (not (org-previous-line-empty-p t)))
7619 (setq empty-line-p (or empty-line-p
7620 (org-previous-line-empty-p))))
7621 (match-string 0))
7622 (error (or fix-level "* ")))))
7623 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7624 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7625 pos hide-previous previous-pos)
7627 ;; If we insert after content, move there and clean up whitespace
7628 (when respect-content
7629 (org-end-of-subtree nil t)
7630 (skip-chars-backward " \r\n")
7631 (and (not (looking-back "^\*+"))
7632 (looking-at "[ \t]+") (replace-match ""))
7633 (unless (eobp) (forward-char 1))
7634 (when (looking-at "^\\*")
7635 (unless (bobp) (backward-char 1))
7636 (insert "\n")))
7638 ;; If we are splitting, grab the text that should be moved to the new headline
7639 (when may-split
7640 (if (org-on-heading-p)
7641 ;; This is a heading, we split intelligently (keeping tags)
7642 (let ((pos (point)))
7643 (goto-char (point-at-bol))
7644 (unless (looking-at org-complex-heading-regexp)
7645 (error "This should not happen"))
7646 (when (and (match-beginning 4)
7647 (> pos (match-beginning 4))
7648 (< pos (match-end 4)))
7649 (setq initial-content (buffer-substring pos (match-end 4)))
7650 (goto-char pos)
7651 (delete-region (point) (match-end 4))
7652 (if (looking-at "[ \t]*$")
7653 (replace-match "")
7654 (insert (make-string (length initial-content) ?\ )))
7655 (setq initial-content (org-trim initial-content)))
7656 (goto-char pos))
7657 ;; a normal line
7658 (unless (bolp)
7659 (setq initial-content (buffer-substring (point) (point-at-eol)))
7660 (delete-region (point) (point-at-eol))
7661 (setq initial-content (org-trim initial-content)))))
7663 ;; If we are at the beginning of the line, insert before it. Else after
7664 (cond
7665 ((and (bolp) (looking-at "[ \t]*$")))
7666 ((and (bolp) (not (looking-at "[ \t]*$")))
7667 (open-line 1))
7669 (goto-char (point-at-eol))
7670 (insert "\n")))
7672 ;; Insert the new heading
7673 (insert stars)
7674 (just-one-space)
7675 (insert initial-content)
7676 (when adjust-empty-lines
7677 (if (or (not blank)
7678 (and blank (not (org-previous-line-empty-p))))
7679 (org-N-empty-lines-before-current (if blank 1 0))))
7680 (run-hooks 'org-insert-heading-hook)))))))
7682 (defun org-N-empty-lines-before-current (N)
7683 "Make the number of empty lines before current exactly N.
7684 So this will delete or add empty lines."
7685 (save-excursion
7686 (goto-char (point-at-bol))
7687 (if (looking-back "\\s-+" nil 'greedy)
7688 (replace-match ""))
7689 (or (bobp) (insert "\n"))
7690 (while (> N 0)
7691 (insert "\n")
7692 (setq N (1- N)))))
7694 (defun org-get-heading (&optional no-tags no-todo)
7695 "Return the heading of the current entry, without the stars.
7696 When NO-TAGS is non-nil, don't include tags.
7697 When NO-TODO is non-nil, don't include TODO keywords."
7698 (save-excursion
7699 (org-back-to-heading t)
7700 (cond
7701 ((and no-tags no-todo)
7702 (looking-at org-complex-heading-regexp)
7703 (match-string 4))
7704 (no-tags
7705 (looking-at (concat org-outline-regexp
7706 "\\(.*?\\)"
7707 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7708 (match-string 1))
7709 (no-todo
7710 (looking-at org-todo-line-regexp)
7711 (match-string 3))
7712 (t (looking-at org-heading-regexp)
7713 (match-string 2)))))
7715 (defvar orgstruct-mode) ; defined below
7717 (defun org-heading-components ()
7718 "Return the components of the current heading.
7719 This is a list with the following elements:
7720 - the level as an integer
7721 - the reduced level, different if `org-odd-levels-only' is set.
7722 - the TODO keyword, or nil
7723 - the priority character, like ?A, or nil if no priority is given
7724 - the headline text itself, or the tags string if no headline text
7725 - the tags string, or nil."
7726 (save-excursion
7727 (org-back-to-heading t)
7728 (if (let (case-fold-search)
7729 (looking-at
7730 (if orgstruct-mode
7731 org-heading-regexp
7732 org-complex-heading-regexp)))
7733 (if orgstruct-mode
7734 (list (length (match-string 1))
7735 (org-reduced-level (length (match-string 1)))
7738 (match-string 2)
7739 nil)
7740 (list (length (match-string 1))
7741 (org-reduced-level (length (match-string 1)))
7742 (org-match-string-no-properties 2)
7743 (and (match-end 3) (aref (match-string 3) 2))
7744 (org-match-string-no-properties 4)
7745 (org-match-string-no-properties 5))))))
7747 (defun org-get-entry ()
7748 "Get the entry text, after heading, entire subtree."
7749 (save-excursion
7750 (org-back-to-heading t)
7751 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7753 (defun org-insert-heading-after-current ()
7754 "Insert a new heading with same level as current, after current subtree."
7755 (interactive)
7756 (org-back-to-heading)
7757 (org-insert-heading)
7758 (org-move-subtree-down)
7759 (end-of-line 1))
7761 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7762 "Insert heading with `org-insert-heading-respect-content' set to t."
7763 (interactive "P")
7764 (let ((org-insert-heading-respect-content t))
7765 (org-insert-heading '(4) invisible-ok)))
7767 (defun org-insert-todo-heading-respect-content (&optional force-state)
7768 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7769 (interactive "P")
7770 (let ((org-insert-heading-respect-content t))
7771 (org-insert-todo-heading force-state '(4))))
7773 (defun org-insert-todo-heading (arg &optional force-heading)
7774 "Insert a new heading with the same level and TODO state as current heading.
7775 If the heading has no TODO state, or if the state is DONE, use the first
7776 state (TODO by default). Also with one prefix arg, force first state. With
7777 two prefix args, force inserting at the end of the parent subtree."
7778 (interactive "P")
7779 (when (or force-heading (not (org-insert-item 'checkbox)))
7780 (org-insert-heading (or (and (equal arg '(16)) '(16))
7781 force-heading))
7782 (save-excursion
7783 (org-back-to-heading)
7784 (outline-previous-heading)
7785 (looking-at org-todo-line-regexp))
7786 (let*
7787 ((new-mark-x
7788 (if (or (equal arg '(4))
7789 (not (match-beginning 2))
7790 (member (match-string 2) org-done-keywords))
7791 (car org-todo-keywords-1)
7792 (match-string 2)))
7793 (new-mark
7795 (run-hook-with-args-until-success
7796 'org-todo-get-default-hook new-mark-x nil)
7797 new-mark-x)))
7798 (beginning-of-line 1)
7799 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7800 (if org-treat-insert-todo-heading-as-state-change
7801 (org-todo new-mark)
7802 (insert new-mark " "))))
7803 (when org-provide-todo-statistics
7804 (org-update-parent-todo-statistics))))
7806 (defun org-insert-subheading (arg)
7807 "Insert a new subheading and demote it.
7808 Works for outline headings and for plain lists alike."
7809 (interactive "P")
7810 (org-insert-heading arg)
7811 (cond
7812 ((org-at-heading-p) (org-do-demote))
7813 ((org-at-item-p) (org-indent-item))))
7815 (defun org-insert-todo-subheading (arg)
7816 "Insert a new subheading with TODO keyword or checkbox and demote it.
7817 Works for outline headings and for plain lists alike."
7818 (interactive "P")
7819 (org-insert-todo-heading arg)
7820 (cond
7821 ((org-at-heading-p) (org-do-demote))
7822 ((org-at-item-p) (org-indent-item))))
7824 ;;; Promotion and Demotion
7826 (defvar org-after-demote-entry-hook nil
7827 "Hook run after an entry has been demoted.
7828 The cursor will be at the beginning of the entry.
7829 When a subtree is being demoted, the hook will be called for each node.")
7831 (defvar org-after-promote-entry-hook nil
7832 "Hook run after an entry has been promoted.
7833 The cursor will be at the beginning of the entry.
7834 When a subtree is being promoted, the hook will be called for each node.")
7836 (defun org-promote-subtree ()
7837 "Promote the entire subtree.
7838 See also `org-promote'."
7839 (interactive)
7840 (save-excursion
7841 (org-with-limited-levels (org-map-tree 'org-promote)))
7842 (org-fix-position-after-promote))
7844 (defun org-demote-subtree ()
7845 "Demote the entire subtree. See `org-demote'.
7846 See also `org-promote'."
7847 (interactive)
7848 (save-excursion
7849 (org-with-limited-levels (org-map-tree 'org-demote)))
7850 (org-fix-position-after-promote))
7853 (defun org-do-promote ()
7854 "Promote the current heading higher up the tree.
7855 If the region is active in `transient-mark-mode', promote all headings
7856 in the region."
7857 (interactive)
7858 (save-excursion
7859 (if (org-region-active-p)
7860 (org-map-region 'org-promote (region-beginning) (region-end))
7861 (org-promote)))
7862 (org-fix-position-after-promote))
7864 (defun org-do-demote ()
7865 "Demote the current heading lower down the tree.
7866 If the region is active in `transient-mark-mode', demote all headings
7867 in the region."
7868 (interactive)
7869 (save-excursion
7870 (if (org-region-active-p)
7871 (org-map-region 'org-demote (region-beginning) (region-end))
7872 (org-demote)))
7873 (org-fix-position-after-promote))
7875 (defun org-fix-position-after-promote ()
7876 "Make sure that after pro/demotion cursor position is right."
7877 (let ((pos (point)))
7878 (when (save-excursion
7879 (beginning-of-line 1)
7880 (looking-at org-todo-line-regexp)
7881 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7882 (cond ((eobp) (insert " "))
7883 ((eolp) (insert " "))
7884 ((equal (char-after) ?\ ) (forward-char 1))))))
7886 (defun org-current-level ()
7887 "Return the level of the current entry, or nil if before the first headline.
7888 The level is the number of stars at the beginning of the headline."
7889 (save-excursion
7890 (org-with-limited-levels
7891 (if (ignore-errors (org-back-to-heading t))
7892 (funcall outline-level)))))
7894 (defun org-get-previous-line-level ()
7895 "Return the outline depth of the last headline before the current line.
7896 Returns 0 for the first headline in the buffer, and nil if before the
7897 first headline."
7898 (and (org-current-level)
7899 (or (and (/= (line-beginning-position) (point-min))
7900 (save-excursion (beginning-of-line 0) (org-current-level)))
7901 0)))
7903 (defun org-reduced-level (l)
7904 "Compute the effective level of a heading.
7905 This takes into account the setting of `org-odd-levels-only'."
7906 (cond
7907 ((zerop l) 0)
7908 (org-odd-levels-only (1+ (floor (/ l 2))))
7909 (t l)))
7911 (defun org-level-increment ()
7912 "Return the number of stars that will be added or removed at a
7913 time to headlines when structure editing, based on the value of
7914 `org-odd-levels-only'."
7915 (if org-odd-levels-only 2 1))
7917 (defun org-get-valid-level (level &optional change)
7918 "Rectify a level change under the influence of `org-odd-levels-only'
7919 LEVEL is a current level, CHANGE is by how much the level should be
7920 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7921 even level numbers will become the next higher odd number."
7922 (if org-odd-levels-only
7923 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7924 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7925 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7926 (max 1 (+ level (or change 0)))))
7928 (if (boundp 'define-obsolete-function-alias)
7929 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7930 (define-obsolete-function-alias 'org-get-legal-level
7931 'org-get-valid-level)
7932 (define-obsolete-function-alias 'org-get-legal-level
7933 'org-get-valid-level "23.1")))
7935 (defun org-promote ()
7936 "Promote the current heading higher up the tree.
7937 If the region is active in `transient-mark-mode', promote all headings
7938 in the region."
7939 (org-back-to-heading t)
7940 (let* ((level (save-match-data (funcall outline-level)))
7941 (after-change-functions (remove 'flyspell-after-change-function
7942 after-change-functions))
7943 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7944 (diff (abs (- level (length up-head) -1))))
7945 (cond ((and (= level 1) org-called-with-limited-levels
7946 org-allow-promoting-top-level-subtree)
7947 (replace-match "# " nil t))
7948 ((= level 1)
7949 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7950 (t (replace-match up-head nil t)))
7951 ;; Fixup tag positioning
7952 (unless (= level 1)
7953 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7954 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7955 (run-hooks 'org-after-promote-entry-hook)))
7957 (defun org-demote ()
7958 "Demote the current heading lower down the tree.
7959 If the region is active in `transient-mark-mode', demote all headings
7960 in the region."
7961 (org-back-to-heading t)
7962 (let* ((level (save-match-data (funcall outline-level)))
7963 (after-change-functions (remove 'flyspell-after-change-function
7964 after-change-functions))
7965 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7966 (diff (abs (- level (length down-head) -1))))
7967 (replace-match down-head nil t)
7968 ;; Fixup tag positioning
7969 (and org-auto-align-tags (org-set-tags nil 'ignore-column))
7970 (if org-adapt-indentation (org-fixup-indentation diff))
7971 (run-hooks 'org-after-demote-entry-hook)))
7973 (defun org-cycle-level ()
7974 "Cycle the level of an empty headline through possible states.
7975 This goes first to child, then to parent, level, then up the hierarchy.
7976 After top level, it switches back to sibling level."
7977 (interactive)
7978 (let ((org-adapt-indentation nil))
7979 (when (org-point-at-end-of-empty-headline)
7980 (setq this-command 'org-cycle-level) ; Only needed for caching
7981 (let ((cur-level (org-current-level))
7982 (prev-level (org-get-previous-line-level)))
7983 (cond
7984 ;; If first headline in file, promote to top-level.
7985 ((= prev-level 0)
7986 (loop repeat (/ (- cur-level 1) (org-level-increment))
7987 do (org-do-promote)))
7988 ;; If same level as prev, demote one.
7989 ((= prev-level cur-level)
7990 (org-do-demote))
7991 ;; If parent is top-level, promote to top level if not already.
7992 ((= prev-level 1)
7993 (loop repeat (/ (- cur-level 1) (org-level-increment))
7994 do (org-do-promote)))
7995 ;; If top-level, return to prev-level.
7996 ((= cur-level 1)
7997 (loop repeat (/ (- prev-level 1) (org-level-increment))
7998 do (org-do-demote)))
7999 ;; If less than prev-level, promote one.
8000 ((< cur-level prev-level)
8001 (org-do-promote))
8002 ;; If deeper than prev-level, promote until higher than
8003 ;; prev-level.
8004 ((> cur-level prev-level)
8005 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8006 do (org-do-promote))))
8007 t))))
8009 (defun org-map-tree (fun)
8010 "Call FUN for every heading underneath the current one."
8011 (org-back-to-heading)
8012 (let ((level (funcall outline-level)))
8013 (save-excursion
8014 (funcall fun)
8015 (while (and (progn
8016 (outline-next-heading)
8017 (> (funcall outline-level) level))
8018 (not (eobp)))
8019 (funcall fun)))))
8021 (defun org-map-region (fun beg end)
8022 "Call FUN for every heading between BEG and END."
8023 (let ((org-ignore-region t))
8024 (save-excursion
8025 (setq end (copy-marker end))
8026 (goto-char beg)
8027 (if (and (re-search-forward org-outline-regexp-bol nil t)
8028 (< (point) end))
8029 (funcall fun))
8030 (while (and (progn
8031 (outline-next-heading)
8032 (< (point) end))
8033 (not (eobp)))
8034 (funcall fun)))))
8036 (defvar org-property-end-re) ; silence byte-compiler
8037 (defun org-fixup-indentation (diff)
8038 "Change the indentation in the current entry by DIFF.
8039 However, if any line in the current entry has no indentation, or if it
8040 would end up with no indentation after the change, nothing at all is done."
8041 (save-excursion
8042 (let ((end (save-excursion (outline-next-heading)
8043 (point-marker)))
8044 (prohibit (if (> diff 0)
8045 "^\\S-"
8046 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8047 col)
8048 (unless (save-excursion (end-of-line 1)
8049 (re-search-forward prohibit end t))
8050 (while (and (< (point) end)
8051 (re-search-forward "^[ \t]+" end t))
8052 (goto-char (match-end 0))
8053 (setq col (current-column))
8054 (if (< diff 0) (replace-match ""))
8055 (org-indent-to-column (+ diff col))))
8056 (move-marker end nil))))
8058 (defun org-convert-to-odd-levels ()
8059 "Convert an org-mode file with all levels allowed to one with odd levels.
8060 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8061 level 5 etc."
8062 (interactive)
8063 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8064 (let ((outline-level 'org-outline-level)
8065 (org-odd-levels-only nil) n)
8066 (save-excursion
8067 (goto-char (point-min))
8068 (while (re-search-forward "^\\*\\*+ " nil t)
8069 (setq n (- (length (match-string 0)) 2))
8070 (while (>= (setq n (1- n)) 0)
8071 (org-demote))
8072 (end-of-line 1))))))
8074 (defun org-convert-to-oddeven-levels ()
8075 "Convert an org-mode file with only odd levels to one with odd/even levels.
8076 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8077 file contains a section with an even level, conversion would
8078 destroy the structure of the file. An error is signaled in this
8079 case."
8080 (interactive)
8081 (goto-char (point-min))
8082 ;; First check if there are no even levels
8083 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8084 (org-show-context t)
8085 (error "Not all levels are odd in this file. Conversion not possible"))
8086 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8087 (let ((outline-regexp org-outline-regexp)
8088 (outline-level 'org-outline-level)
8089 (org-odd-levels-only nil) n)
8090 (save-excursion
8091 (goto-char (point-min))
8092 (while (re-search-forward "^\\*\\*+ " nil t)
8093 (setq n (/ (1- (length (match-string 0))) 2))
8094 (while (>= (setq n (1- n)) 0)
8095 (org-promote))
8096 (end-of-line 1))))))
8098 (defun org-tr-level (n)
8099 "Make N odd if required."
8100 (if org-odd-levels-only (1+ (/ n 2)) n))
8102 ;;; Vertical tree motion, cutting and pasting of subtrees
8104 (defun org-move-subtree-up (&optional arg)
8105 "Move the current subtree up past ARG headlines of the same level."
8106 (interactive "p")
8107 (org-move-subtree-down (- (prefix-numeric-value arg))))
8109 (defun org-move-subtree-down (&optional arg)
8110 "Move the current subtree down past ARG headlines of the same level."
8111 (interactive "p")
8112 (setq arg (prefix-numeric-value arg))
8113 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8114 'org-get-last-sibling))
8115 (ins-point (make-marker))
8116 (cnt (abs arg))
8117 (col (current-column))
8118 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8119 ;; Select the tree
8120 (org-back-to-heading)
8121 (setq beg0 (point))
8122 (save-excursion
8123 (setq ne-beg (org-back-over-empty-lines))
8124 (setq beg (point)))
8125 (save-match-data
8126 (save-excursion (outline-end-of-heading)
8127 (setq folded (outline-invisible-p)))
8128 (outline-end-of-subtree))
8129 (outline-next-heading)
8130 (setq ne-end (org-back-over-empty-lines))
8131 (setq end (point))
8132 (goto-char beg0)
8133 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8134 ;; include less whitespace
8135 (save-excursion
8136 (goto-char beg)
8137 (forward-line (- ne-beg ne-end))
8138 (setq beg (point))))
8139 ;; Find insertion point, with error handling
8140 (while (> cnt 0)
8141 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8142 (progn (goto-char beg0)
8143 (user-error "Cannot move past superior level or buffer limit")))
8144 (setq cnt (1- cnt)))
8145 (if (> arg 0)
8146 ;; Moving forward - still need to move over subtree
8147 (progn (org-end-of-subtree t t)
8148 (save-excursion
8149 (org-back-over-empty-lines)
8150 (or (bolp) (newline)))))
8151 (setq ne-ins (org-back-over-empty-lines))
8152 (move-marker ins-point (point))
8153 (setq txt (buffer-substring beg end))
8154 (org-save-markers-in-region beg end)
8155 (delete-region beg end)
8156 (org-remove-empty-overlays-at beg)
8157 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8158 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8159 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8160 (let ((bbb (point)))
8161 (insert-before-markers txt)
8162 (org-reinstall-markers-in-region bbb)
8163 (move-marker ins-point bbb))
8164 (or (bolp) (insert "\n"))
8165 (setq ins-end (point))
8166 (goto-char ins-point)
8167 (org-skip-whitespace)
8168 (when (and (< arg 0)
8169 (org-first-sibling-p)
8170 (> ne-ins ne-beg))
8171 ;; Move whitespace back to beginning
8172 (save-excursion
8173 (goto-char ins-end)
8174 (let ((kill-whole-line t))
8175 (kill-line (- ne-ins ne-beg)) (point)))
8176 (insert (make-string (- ne-ins ne-beg) ?\n)))
8177 (move-marker ins-point nil)
8178 (if folded
8179 (hide-subtree)
8180 (org-show-entry)
8181 (show-children)
8182 (org-cycle-hide-drawers 'children))
8183 (org-clean-visibility-after-subtree-move)
8184 ;; move back to the initial column we were at
8185 (move-to-column col)))
8187 (defvar org-subtree-clip ""
8188 "Clipboard for cut and paste of subtrees.
8189 This is actually only a copy of the kill, because we use the normal kill
8190 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8192 (defvar org-subtree-clip-folded nil
8193 "Was the last copied subtree folded?
8194 This is used to fold the tree back after pasting.")
8196 (defun org-cut-subtree (&optional n)
8197 "Cut the current subtree into the clipboard.
8198 With prefix arg N, cut this many sequential subtrees.
8199 This is a short-hand for marking the subtree and then cutting it."
8200 (interactive "p")
8201 (org-copy-subtree n 'cut))
8203 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8204 "Copy the current subtree it in the clipboard.
8205 With prefix arg N, copy this many sequential subtrees.
8206 This is a short-hand for marking the subtree and then copying it.
8207 If CUT is non-nil, actually cut the subtree.
8208 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8209 of some markers in the region, even if CUT is non-nil. This is
8210 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8211 (interactive "p")
8212 (let (beg end folded (beg0 (point)))
8213 (if (org-called-interactively-p 'any)
8214 (org-back-to-heading nil) ; take what looks like a subtree
8215 (org-back-to-heading t)) ; take what is really there
8216 (setq beg (point))
8217 (skip-chars-forward " \t\r\n")
8218 (save-match-data
8219 (if nosubtrees
8220 (outline-next-heading)
8221 (save-excursion (outline-end-of-heading)
8222 (setq folded (outline-invisible-p)))
8223 (condition-case nil
8224 (org-forward-heading-same-level (1- n) t)
8225 (error nil))
8226 (org-end-of-subtree t t)))
8227 (setq end (point))
8228 (goto-char beg0)
8229 (when (> end beg)
8230 (setq org-subtree-clip-folded folded)
8231 (when (or cut force-store-markers)
8232 (org-save-markers-in-region beg end))
8233 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8234 (setq org-subtree-clip (current-kill 0))
8235 (message "%s: Subtree(s) with %d characters"
8236 (if cut "Cut" "Copied")
8237 (length org-subtree-clip)))))
8239 (defun org-paste-subtree (&optional level tree for-yank)
8240 "Paste the clipboard as a subtree, with modification of headline level.
8241 The entire subtree is promoted or demoted in order to match a new headline
8242 level.
8244 If the cursor is at the beginning of a headline, the same level as
8245 that headline is used to paste the tree.
8247 If not, the new level is derived from the *visible* headings
8248 before and after the insertion point, and taken to be the inferior headline
8249 level of the two. So if the previous visible heading is level 3 and the
8250 next is level 4 (or vice versa), level 4 will be used for insertion.
8251 This makes sure that the subtree remains an independent subtree and does
8252 not swallow low level entries.
8254 You can also force a different level, either by using a numeric prefix
8255 argument, or by inserting the heading marker by hand. For example, if the
8256 cursor is after \"*****\", then the tree will be shifted to level 5.
8258 If optional TREE is given, use this text instead of the kill ring.
8260 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8261 move back over whitespace before inserting, and move point to the end of
8262 the inserted text when done."
8263 (interactive "P")
8264 (setq tree (or tree (and kill-ring (current-kill 0))))
8265 (unless (org-kill-is-subtree-p tree)
8266 (user-error "%s"
8267 (substitute-command-keys
8268 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8269 (org-with-limited-levels
8270 (let* ((visp (not (outline-invisible-p)))
8271 (txt tree)
8272 (^re_ "\\(\\*+\\)[ \t]*")
8273 (old-level (if (string-match org-outline-regexp-bol txt)
8274 (- (match-end 0) (match-beginning 0) 1)
8275 -1))
8276 (force-level (cond (level (prefix-numeric-value level))
8277 ((and (looking-at "[ \t]*$")
8278 (string-match
8279 "^\\*+$" (buffer-substring
8280 (point-at-bol) (point))))
8281 (- (match-end 1) (match-beginning 1)))
8282 ((and (bolp)
8283 (looking-at org-outline-regexp))
8284 (- (match-end 0) (point) 1))))
8285 (previous-level (save-excursion
8286 (condition-case nil
8287 (progn
8288 (outline-previous-visible-heading 1)
8289 (if (looking-at ^re_)
8290 (- (match-end 0) (match-beginning 0) 1)
8292 (error 1))))
8293 (next-level (save-excursion
8294 (condition-case nil
8295 (progn
8296 (or (looking-at org-outline-regexp)
8297 (outline-next-visible-heading 1))
8298 (if (looking-at ^re_)
8299 (- (match-end 0) (match-beginning 0) 1)
8301 (error 1))))
8302 (new-level (or force-level (max previous-level next-level)))
8303 (shift (if (or (= old-level -1)
8304 (= new-level -1)
8305 (= old-level new-level))
8307 (- new-level old-level)))
8308 (delta (if (> shift 0) -1 1))
8309 (func (if (> shift 0) 'org-demote 'org-promote))
8310 (org-odd-levels-only nil)
8311 beg end newend)
8312 ;; Remove the forced level indicator
8313 (if force-level
8314 (delete-region (point-at-bol) (point)))
8315 ;; Paste
8316 (beginning-of-line (if (bolp) 1 2))
8317 (setq beg (point))
8318 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8319 (insert-before-markers txt)
8320 (unless (string-match "\n\\'" txt) (insert "\n"))
8321 (setq newend (point))
8322 (org-reinstall-markers-in-region beg)
8323 (setq end (point))
8324 (goto-char beg)
8325 (skip-chars-forward " \t\n\r")
8326 (setq beg (point))
8327 (if (and (outline-invisible-p) visp)
8328 (save-excursion (outline-show-heading)))
8329 ;; Shift if necessary
8330 (unless (= shift 0)
8331 (save-restriction
8332 (narrow-to-region beg end)
8333 (while (not (= shift 0))
8334 (org-map-region func (point-min) (point-max))
8335 (setq shift (+ delta shift)))
8336 (goto-char (point-min))
8337 (setq newend (point-max))))
8338 (when (or (org-called-interactively-p 'interactive) for-yank)
8339 (message "Clipboard pasted as level %d subtree" new-level))
8340 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8341 kill-ring
8342 (eq org-subtree-clip (current-kill 0))
8343 org-subtree-clip-folded)
8344 ;; The tree was folded before it was killed/copied
8345 (hide-subtree))
8346 (and for-yank (goto-char newend)))))
8348 (defun org-kill-is-subtree-p (&optional txt)
8349 "Check if the current kill is an outline subtree, or a set of trees.
8350 Returns nil if kill does not start with a headline, or if the first
8351 headline level is not the largest headline level in the tree.
8352 So this will actually accept several entries of equal levels as well,
8353 which is OK for `org-paste-subtree'.
8354 If optional TXT is given, check this string instead of the current kill."
8355 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8356 (re (org-get-limited-outline-regexp))
8357 (^re (concat "^" re))
8358 (start-level (and kill
8359 (string-match
8360 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8361 kill)
8362 (- (match-end 2) (match-beginning 2) 1)))
8363 (start (1+ (or (match-beginning 2) -1))))
8364 (if (not start-level)
8365 (progn
8366 nil) ;; does not even start with a heading
8367 (catch 'exit
8368 (while (setq start (string-match ^re kill (1+ start)))
8369 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8370 (throw 'exit nil)))
8371 t))))
8373 (defvar org-markers-to-move nil
8374 "Markers that should be moved with a cut-and-paste operation.
8375 Those markers are stored together with their positions relative to
8376 the start of the region.")
8378 (defun org-save-markers-in-region (beg end)
8379 "Check markers in region.
8380 If these markers are between BEG and END, record their position relative
8381 to BEG, so that after moving the block of text, we can put the markers back
8382 into place.
8383 This function gets called just before an entry or tree gets cut from the
8384 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8385 called immediately, to move the markers with the entries."
8386 (setq org-markers-to-move nil)
8387 (when (featurep 'org-clock)
8388 (org-clock-save-markers-for-cut-and-paste beg end))
8389 (when (featurep 'org-agenda)
8390 (org-agenda-save-markers-for-cut-and-paste beg end)))
8392 (defun org-check-and-save-marker (marker beg end)
8393 "Check if MARKER is between BEG and END.
8394 If yes, remember the marker and the distance to BEG."
8395 (when (and (marker-buffer marker)
8396 (equal (marker-buffer marker) (current-buffer)))
8397 (if (and (>= marker beg) (< marker end))
8398 (push (cons marker (- marker beg)) org-markers-to-move))))
8400 (defun org-reinstall-markers-in-region (beg)
8401 "Move all remembered markers to their position relative to BEG."
8402 (mapc (lambda (x)
8403 (move-marker (car x) (+ beg (cdr x))))
8404 org-markers-to-move)
8405 (setq org-markers-to-move nil))
8407 (defun org-narrow-to-subtree ()
8408 "Narrow buffer to the current subtree."
8409 (interactive)
8410 (save-excursion
8411 (save-match-data
8412 (org-with-limited-levels
8413 (narrow-to-region
8414 (progn (org-back-to-heading t) (point))
8415 (progn (org-end-of-subtree t t)
8416 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8417 (point)))))))
8419 (defun org-narrow-to-block ()
8420 "Narrow buffer to the current block."
8421 (interactive)
8422 (let* ((case-fold-search t)
8423 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8424 "^[ \t]*#\\+end_.*")))
8425 (if blockp
8426 (narrow-to-region (car blockp) (cdr blockp))
8427 (user-error "Not in a block"))))
8429 (eval-when-compile
8430 (defvar org-property-drawer-re))
8432 (defvar org-property-start-re) ;; defined below
8433 (defun org-clone-subtree-with-time-shift (n &optional shift)
8434 "Clone the task (subtree) at point N times.
8435 The clones will be inserted as siblings.
8437 In interactive use, the user will be prompted for the number of
8438 clones to be produced. If the entry has a timestamp, the user
8439 will also be prompted for a time shift, which may be a repeater
8440 as used in time stamps, for example `+3d'. To disable this,
8441 you can call the function with a universal prefix argument.
8443 When a valid repeater is given and the entry contains any time
8444 stamps, the clones will become a sequence in time, with time
8445 stamps in the subtree shifted for each clone produced. If SHIFT
8446 is nil or the empty string, time stamps will be left alone. The
8447 ID property of the original subtree is removed.
8449 If the original subtree did contain time stamps with a repeater,
8450 the following will happen:
8451 - the repeater will be removed in each clone
8452 - an additional clone will be produced, with the current, unshifted
8453 date(s) in the entry.
8454 - the original entry will be placed *after* all the clones, with
8455 repeater intact.
8456 - the start days in the repeater in the original entry will be shifted
8457 to past the last clone.
8458 In this way you can spell out a number of instances of a repeating task,
8459 and still retain the repeater to cover future instances of the task."
8460 (interactive "nNumber of clones to produce: ")
8461 (let ((shift
8462 (or shift
8463 (if (and (not (equal current-prefix-arg '(4)))
8464 (save-excursion
8465 (re-search-forward org-ts-regexp-both
8466 (save-excursion
8467 (org-end-of-subtree t)
8468 (point)) t)))
8469 (read-from-minibuffer
8470 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8471 ""))) ;; No time shift
8472 (n-no-remove -1)
8473 (drawer-re org-drawer-regexp)
8474 beg end template task idprop
8475 shift-n shift-what doshift nmin nmax)
8476 (if (not (and (integerp n) (> n 0)))
8477 (error "Invalid number of replications %s" n))
8478 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8479 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8480 shift)))
8481 (error "Invalid shift specification %s" shift))
8482 (when doshift
8483 (setq shift-n (string-to-number (match-string 1 shift))
8484 shift-what (cdr (assoc (match-string 2 shift)
8485 '(("d" . day) ("w" . week)
8486 ("m" . month) ("y" . year))))))
8487 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8488 (setq nmin 1 nmax n)
8489 (org-back-to-heading t)
8490 (setq beg (point))
8491 (setq idprop (org-entry-get nil "ID"))
8492 (org-end-of-subtree t t)
8493 (or (bolp) (insert "\n"))
8494 (setq end (point))
8495 (setq template (buffer-substring beg end))
8496 (when (and doshift
8497 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8498 (delete-region beg end)
8499 (setq end beg)
8500 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8501 (goto-char end)
8502 (loop for n from nmin to nmax do
8503 ;; prepare clone
8504 (with-temp-buffer
8505 (insert template)
8506 (org-mode)
8507 (goto-char (point-min))
8508 (org-show-subtree)
8509 (and idprop (if org-clone-delete-id
8510 (org-entry-delete nil "ID")
8511 (org-id-get-create t)))
8512 (unless (= n 0)
8513 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8514 (kill-whole-line))
8515 (goto-char (point-min))
8516 (while (re-search-forward drawer-re nil t)
8517 (mapc (lambda (d)
8518 (org-remove-empty-drawer-at d (point))) org-drawers)))
8519 (goto-char (point-min))
8520 (when doshift
8521 (while (re-search-forward org-ts-regexp-both nil t)
8522 (org-timestamp-change (* n shift-n) shift-what))
8523 (unless (= n n-no-remove)
8524 (goto-char (point-min))
8525 (while (re-search-forward org-ts-regexp nil t)
8526 (save-excursion
8527 (goto-char (match-beginning 0))
8528 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8529 (delete-region (match-beginning 1) (match-end 1)))))))
8530 (setq task (buffer-string)))
8531 (insert task))
8532 (goto-char beg)))
8534 ;;; Outline Sorting
8536 (defun org-sort (with-case)
8537 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8538 Optional argument WITH-CASE means sort case-sensitively."
8539 (interactive "P")
8540 (cond
8541 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8542 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8544 (org-call-with-arg 'org-sort-entries with-case))))
8546 (defun org-sort-remove-invisible (s)
8547 "Remove invisible links from string S."
8548 (remove-text-properties 0 (length s) org-rm-props s)
8549 (while (string-match org-bracket-link-regexp s)
8550 (setq s (replace-match (if (match-end 2)
8551 (match-string 3 s)
8552 (match-string 1 s)) t t s)))
8553 (let ((st (format " %s " s)))
8554 (while (string-match org-emph-re st)
8555 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8556 (setq s (substring st 1 -1)))
8559 (defvar org-priority-regexp) ; defined later in the file
8561 (defvar org-after-sorting-entries-or-items-hook nil
8562 "Hook that is run after a bunch of entries or items have been sorted.
8563 When children are sorted, the cursor is in the parent line when this
8564 hook gets called. When a region or a plain list is sorted, the cursor
8565 will be in the first entry of the sorted region/list.")
8567 (defun org-sort-entries
8568 (&optional with-case sorting-type getkey-func compare-func property)
8569 "Sort entries on a certain level of an outline tree.
8570 If there is an active region, the entries in the region are sorted.
8571 Else, if the cursor is before the first entry, sort the top-level items.
8572 Else, the children of the entry at point are sorted.
8574 Sorting can be alphabetically, numerically, by date/time as given by
8575 a time stamp, by a property, by priority order, or by a custom function.
8577 The command prompts for the sorting type unless it has been given to the
8578 function through the SORTING-TYPE argument, which needs to be a character,
8579 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8580 precise meaning of each character:
8582 n Numerically, by converting the beginning of the entry/item to a number.
8583 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8584 o By order of TODO keywords.
8585 t By date/time, either the first active time stamp in the entry, or, if
8586 none exist, by the first inactive one.
8587 s By the scheduled date/time.
8588 d By deadline date/time.
8589 c By creation time, which is assumed to be the first inactive time stamp
8590 at the beginning of a line.
8591 p By priority according to the cookie.
8592 r By the value of a property.
8594 Capital letters will reverse the sort order.
8596 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8597 called with point at the beginning of the record. It must return either
8598 a string or a number that should serve as the sorting key for that record.
8600 Comparing entries ignores case by default. However, with an optional argument
8601 WITH-CASE, the sorting considers case as well.
8603 Sorting is done against the visible part of the headlines, it ignores hidden
8604 links."
8605 (interactive "P")
8606 (let ((case-func (if with-case 'identity 'downcase))
8607 (cmstr
8608 ;; The clock marker is lost when using `sort-subr', let's
8609 ;; store the clocking string.
8610 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8611 (save-excursion
8612 (goto-char org-clock-marker)
8613 (looking-back "^.*") (match-string-no-properties 0))))
8614 start beg end stars re re2
8615 txt what tmp)
8616 ;; Find beginning and end of region to sort
8617 (cond
8618 ((org-region-active-p)
8619 ;; we will sort the region
8620 (setq end (region-end)
8621 what "region")
8622 (goto-char (region-beginning))
8623 (if (not (org-at-heading-p)) (outline-next-heading))
8624 (setq start (point)))
8625 ((or (org-at-heading-p)
8626 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8627 ;; we will sort the children of the current headline
8628 (org-back-to-heading)
8629 (setq start (point)
8630 end (progn (org-end-of-subtree t t)
8631 (or (bolp) (insert "\n"))
8632 (org-back-over-empty-lines)
8633 (point))
8634 what "children")
8635 (goto-char start)
8636 (show-subtree)
8637 (outline-next-heading))
8639 ;; we will sort the top-level entries in this file
8640 (goto-char (point-min))
8641 (or (org-at-heading-p) (outline-next-heading))
8642 (setq start (point))
8643 (goto-char (point-max))
8644 (beginning-of-line 1)
8645 (when (looking-at ".*?\\S-")
8646 ;; File ends in a non-white line
8647 (end-of-line 1)
8648 (insert "\n"))
8649 (setq end (point-max))
8650 (setq what "top-level")
8651 (goto-char start)
8652 (show-all)))
8654 (setq beg (point))
8655 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8657 (looking-at "\\(\\*+\\)")
8658 (setq stars (match-string 1)
8659 re (concat "^" (regexp-quote stars) " +")
8660 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8661 txt (buffer-substring beg end))
8662 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8663 (if (and (not (equal stars "*")) (string-match re2 txt))
8664 (user-error "Region to sort contains a level above the first entry"))
8666 (unless sorting-type
8667 (message
8668 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8669 [t]ime [s]cheduled [d]eadline [c]reated
8670 A/N/P/R/O/F/T/S/D/C means reversed:"
8671 what)
8672 (setq sorting-type (read-char-exclusive))
8674 (unless getkey-func
8675 (and (= (downcase sorting-type) ?f)
8676 (setq getkey-func
8677 (org-icompleting-read "Sort using function: "
8678 obarray 'fboundp t nil nil))
8679 (setq getkey-func (intern getkey-func))))
8681 (and (= (downcase sorting-type) ?r)
8682 (not property)
8683 (setq property
8684 (org-icompleting-read "Property: "
8685 (mapcar 'list (org-buffer-property-keys t))
8686 nil t))))
8688 (message "Sorting entries...")
8690 (save-restriction
8691 (narrow-to-region start end)
8692 (let ((dcst (downcase sorting-type))
8693 (case-fold-search nil)
8694 (now (current-time)))
8695 (sort-subr
8696 (/= dcst sorting-type)
8697 ;; This function moves to the beginning character of the "record" to
8698 ;; be sorted.
8699 (lambda nil
8700 (if (re-search-forward re nil t)
8701 (goto-char (match-beginning 0))
8702 (goto-char (point-max))))
8703 ;; This function moves to the last character of the "record" being
8704 ;; sorted.
8705 (lambda nil
8706 (save-match-data
8707 (condition-case nil
8708 (outline-forward-same-level 1)
8709 (error
8710 (goto-char (point-max))))))
8711 ;; This function returns the value that gets sorted against.
8712 (lambda nil
8713 (cond
8714 ((= dcst ?n)
8715 (if (looking-at org-complex-heading-regexp)
8716 (string-to-number (org-sort-remove-invisible (match-string 4)))
8717 nil))
8718 ((= dcst ?a)
8719 (if (looking-at org-complex-heading-regexp)
8720 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8721 nil))
8722 ((= dcst ?t)
8723 (let ((end (save-excursion (outline-next-heading) (point))))
8724 (if (or (re-search-forward org-ts-regexp end t)
8725 (re-search-forward org-ts-regexp-both end t))
8726 (org-time-string-to-seconds (match-string 0))
8727 (org-float-time now))))
8728 ((= dcst ?c)
8729 (let ((end (save-excursion (outline-next-heading) (point))))
8730 (if (re-search-forward
8731 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8732 end t)
8733 (org-time-string-to-seconds (match-string 0))
8734 (org-float-time now))))
8735 ((= dcst ?s)
8736 (let ((end (save-excursion (outline-next-heading) (point))))
8737 (if (re-search-forward org-scheduled-time-regexp end t)
8738 (org-time-string-to-seconds (match-string 1))
8739 (org-float-time now))))
8740 ((= dcst ?d)
8741 (let ((end (save-excursion (outline-next-heading) (point))))
8742 (if (re-search-forward org-deadline-time-regexp end t)
8743 (org-time-string-to-seconds (match-string 1))
8744 (org-float-time now))))
8745 ((= dcst ?p)
8746 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8747 (string-to-char (match-string 2))
8748 org-default-priority))
8749 ((= dcst ?r)
8750 (or (org-entry-get nil property) ""))
8751 ((= dcst ?o)
8752 (if (looking-at org-complex-heading-regexp)
8753 (- 9999 (length (member (match-string 2)
8754 org-todo-keywords-1)))))
8755 ((= dcst ?f)
8756 (if getkey-func
8757 (progn
8758 (setq tmp (funcall getkey-func))
8759 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8760 tmp)
8761 (error "Invalid key function `%s'" getkey-func)))
8762 (t (error "Invalid sorting type `%c'" sorting-type))))
8764 (cond
8765 ((= dcst ?a) 'string<)
8766 ((= dcst ?f) compare-func)
8767 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8768 (run-hooks 'org-after-sorting-entries-or-items-hook)
8769 ;; Reset the clock marker if needed
8770 (when cmstr
8771 (save-excursion
8772 (goto-char start)
8773 (search-forward cmstr nil t)
8774 (move-marker org-clock-marker (point))))
8775 (message "Sorting entries...done")))
8777 (defun org-do-sort (table what &optional with-case sorting-type)
8778 "Sort TABLE of WHAT according to SORTING-TYPE.
8779 The user will be prompted for the SORTING-TYPE if the call to this
8780 function does not specify it. WHAT is only for the prompt, to indicate
8781 what is being sorted. The sorting key will be extracted from
8782 the car of the elements of the table.
8783 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8784 (unless sorting-type
8785 (message
8786 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8787 what)
8788 (setq sorting-type (read-char-exclusive)))
8789 (let ((dcst (downcase sorting-type))
8790 extractfun comparefun)
8791 ;; Define the appropriate functions
8792 (cond
8793 ((= dcst ?n)
8794 (setq extractfun 'string-to-number
8795 comparefun (if (= dcst sorting-type) '< '>)))
8796 ((= dcst ?a)
8797 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8798 (lambda(x) (downcase (org-sort-remove-invisible x))))
8799 comparefun (if (= dcst sorting-type)
8800 'string<
8801 (lambda (a b) (and (not (string< a b))
8802 (not (string= a b)))))))
8803 ((= dcst ?t)
8804 (setq extractfun
8805 (lambda (x)
8806 (if (or (string-match org-ts-regexp x)
8807 (string-match org-ts-regexp-both x))
8808 (org-float-time
8809 (org-time-string-to-time (match-string 0 x)))
8811 comparefun (if (= dcst sorting-type) '< '>)))
8812 (t (error "Invalid sorting type `%c'" sorting-type)))
8814 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8815 table)
8816 (lambda (a b) (funcall comparefun (car a) (car b))))))
8819 ;;; The orgstruct minor mode
8821 ;; Define a minor mode which can be used in other modes in order to
8822 ;; integrate the org-mode structure editing commands.
8824 ;; This is really a hack, because the org-mode structure commands use
8825 ;; keys which normally belong to the major mode. Here is how it
8826 ;; works: The minor mode defines all the keys necessary to operate the
8827 ;; structure commands, but wraps the commands into a function which
8828 ;; tests if the cursor is currently at a headline or a plain list
8829 ;; item. If that is the case, the structure command is used,
8830 ;; temporarily setting many Org-mode variables like regular
8831 ;; expressions for filling etc. However, when any of those keys is
8832 ;; used at a different location, function uses `key-binding' to look
8833 ;; up if the key has an associated command in another currently active
8834 ;; keymap (minor modes, major mode, global), and executes that
8835 ;; command. There might be problems if any of the keys is otherwise
8836 ;; used as a prefix key.
8838 (defcustom orgstruct-heading-prefix-regexp ""
8839 "Regexp that matches the custom prefix of Org headlines in
8840 orgstruct(++)-mode."
8841 :group 'org
8842 :version "24.4"
8843 :package-version '(Org . "8.3")
8844 :type 'regexp)
8845 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8847 (defcustom orgstruct-setup-hook nil
8848 "Hook run after orgstruct-mode-map is filled."
8849 :group 'org
8850 :version "24.4"
8851 :package-version '(Org . "8.0")
8852 :type 'hook)
8854 (defvar orgstruct-initialized nil)
8856 (defvar org-local-vars nil
8857 "List of local variables, for use by `orgstruct-mode'.")
8859 ;;;###autoload
8860 (define-minor-mode orgstruct-mode
8861 "Toggle the minor mode `orgstruct-mode'.
8862 This mode is for using Org-mode structure commands in other
8863 modes. The following keys behave as if Org-mode were active, if
8864 the cursor is on a headline, or on a plain list item (both as
8865 defined by Org-mode)."
8866 nil " OrgStruct" (make-sparse-keymap)
8867 (funcall (if orgstruct-mode
8868 'add-to-invisibility-spec
8869 'remove-from-invisibility-spec)
8870 '(outline . t))
8871 (when orgstruct-mode
8872 (org-load-modules-maybe)
8873 (unless orgstruct-initialized
8874 (orgstruct-setup)
8875 (setq orgstruct-initialized t))))
8877 ;;;###autoload
8878 (defun turn-on-orgstruct ()
8879 "Unconditionally turn on `orgstruct-mode'."
8880 (orgstruct-mode 1))
8882 (defvar org-fb-vars nil)
8883 (make-variable-buffer-local 'org-fb-vars)
8884 (defun orgstruct++-mode (&optional arg)
8885 "Toggle `orgstruct-mode', the enhanced version of it.
8886 In addition to setting orgstruct-mode, this also exports all
8887 indentation and autofilling variables from org-mode into the
8888 buffer. It will also recognize item context in multiline items."
8889 (interactive "P")
8890 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8891 (if (< arg 1)
8892 (progn (orgstruct-mode -1)
8893 (mapc (lambda(v)
8894 (org-set-local (car v)
8895 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8896 org-fb-vars))
8897 (orgstruct-mode 1)
8898 (setq org-fb-vars nil)
8899 (unless org-local-vars
8900 (setq org-local-vars (org-get-local-variables)))
8901 (let (var val)
8902 (mapc
8903 (lambda (x)
8904 (when (string-match
8905 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8906 (symbol-name (car x)))
8907 (setq var (car x) val (nth 1 x))
8908 (push (list var `(quote ,(eval var))) org-fb-vars)
8909 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8910 org-local-vars)
8911 (org-set-local 'orgstruct-is-++ t))))
8913 (defvar orgstruct-is-++ nil
8914 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8915 (make-variable-buffer-local 'orgstruct-is-++)
8917 ;;;###autoload
8918 (defun turn-on-orgstruct++ ()
8919 "Unconditionally turn on `orgstruct++-mode'."
8920 (orgstruct++-mode 1))
8922 (defun orgstruct-error ()
8923 "Error when there is no default binding for a structure key."
8924 (interactive)
8925 (funcall (if (fboundp 'user-error)
8926 'user-error
8927 'error)
8928 "This key has no function outside structure elements"))
8930 (defun orgstruct-setup ()
8931 "Setup orgstruct keymap."
8932 (dolist (cell '((org-demote . t)
8933 (org-metaleft . t)
8934 (org-metaright . t)
8935 (org-promote . t)
8936 (org-shiftmetaleft . t)
8937 (org-shiftmetaright . t)
8938 org-backward-element
8939 org-backward-heading-same-level
8940 org-ctrl-c-ret
8941 org-ctrl-c-minus
8942 org-ctrl-c-star
8943 org-cycle
8944 org-forward-heading-same-level
8945 org-insert-heading
8946 org-insert-heading-respect-content
8947 org-kill-note-or-show-branches
8948 org-mark-subtree
8949 org-meta-return
8950 org-metadown
8951 org-metaup
8952 org-narrow-to-subtree
8953 org-promote-subtree
8954 org-reveal
8955 org-shiftdown
8956 org-shiftleft
8957 org-shiftmetadown
8958 org-shiftmetaup
8959 org-shiftright
8960 org-shifttab
8961 org-shifttab
8962 org-shiftup
8963 org-show-subtree
8964 org-sort
8965 org-up-element
8966 outline-demote
8967 outline-next-visible-heading
8968 outline-previous-visible-heading
8969 outline-promote
8970 outline-up-heading
8971 show-children))
8972 (let ((f (or (car-safe cell) cell))
8973 (disable-when-heading-prefix (cdr-safe cell)))
8974 (when (fboundp f)
8975 (let ((new-bindings))
8976 (dolist (binding (nconc (where-is-internal f org-mode-map)
8977 (where-is-internal f outline-mode-map)))
8978 (push binding new-bindings)
8979 ;; TODO use local-function-key-map
8980 (dolist (rep '(("<tab>" . "TAB")
8981 ("<return>" . "RET")
8982 ("<escape>" . "ESC")
8983 ("<delete>" . "DEL")))
8984 (setq binding (read-kbd-macro
8985 (let ((case-fold-search))
8986 (replace-regexp-in-string
8987 (regexp-quote (cdr rep))
8988 (car rep)
8989 (key-description binding)))))
8990 (pushnew binding new-bindings :test 'equal)))
8991 (dolist (binding new-bindings)
8992 (let ((key (lookup-key orgstruct-mode-map binding)))
8993 (when (or (not key) (numberp key))
8994 (condition-case nil
8995 (org-defkey orgstruct-mode-map
8996 binding
8997 (orgstruct-make-binding f binding disable-when-heading-prefix))
8998 (error nil)))))))))
8999 (run-hooks 'orgstruct-setup-hook))
9001 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9002 "Create a function for binding in the structure minor mode.
9003 FUN is the command to call inside a table. KEY is the key that
9004 should be checked in for a command to execute outside of tables.
9005 Non-nil `disable-when-heading-prefix' means to disable the command
9006 if `orgstruct-heading-prefix-regexp' is not empty."
9007 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9008 (let ((nname name)
9009 (i 0))
9010 (while (fboundp (intern nname))
9011 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9012 (setq name (intern nname)))
9013 (eval
9014 (let ((bindings '((org-heading-regexp
9015 (concat "^"
9016 orgstruct-heading-prefix-regexp
9017 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9018 (org-outline-regexp
9019 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9020 (org-outline-regexp-bol
9021 (concat "^" org-outline-regexp))
9022 (outline-regexp org-outline-regexp)
9023 (outline-heading-end-regexp "\n")
9024 (outline-level 'org-outline-level)
9025 (outline-heading-alist))))
9026 `(defun ,name (arg)
9027 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9028 "Outside of structure, run the binding of `"
9029 (key-description key) "'."
9030 (when disable-when-heading-prefix
9031 (concat
9032 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9033 "back to the default binding due to limitations of Org's implementation of\n"
9034 "`" (symbol-name fun) "'.")))
9035 (interactive "p")
9036 (let* ((disable
9037 ,(and disable-when-heading-prefix
9038 '(not (string= orgstruct-heading-prefix-regexp ""))))
9039 (fallback
9040 (or disable
9041 (not
9042 (let* ,bindings
9043 (org-context-p 'headline 'item
9044 ,(when (memq fun
9045 '(org-insert-heading
9046 org-insert-heading-respect-content
9047 org-meta-return))
9048 '(when orgstruct-is-++
9049 'item-body))))))))
9050 (if fallback
9051 (let* ((orgstruct-mode)
9052 (binding
9053 (loop with key = ,key
9054 for rep in
9055 '(nil
9056 ("<\\([^>]*\\)tab>" . "\\1TAB")
9057 ("<\\([^>]*\\)return>" . "\\1RET")
9058 ("<\\([^>]*\\)escape>" . "\\1ESC")
9059 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9061 (when rep
9062 (setq key (read-kbd-macro
9063 (let ((case-fold-search))
9064 (replace-regexp-in-string
9065 (car rep)
9066 (cdr rep)
9067 (key-description key))))))
9068 thereis (key-binding key))))
9069 (if (keymapp binding)
9070 (org-set-transient-map binding)
9071 (let ((func (or binding
9072 (unless disable
9073 'orgstruct-error))))
9074 (when func
9075 (call-interactively func)))))
9076 (org-run-like-in-org-mode
9077 (lambda ()
9078 (interactive)
9079 (let* ,bindings
9080 (call-interactively ',fun)))))))))
9081 name))
9083 (defun org-contextualize-keys (alist contexts)
9084 "Return valid elements in ALIST depending on CONTEXTS.
9086 `org-agenda-custom-commands' or `org-capture-templates' are the
9087 values used for ALIST, and `org-agenda-custom-commands-contexts'
9088 or `org-capture-templates-contexts' are the associated contexts
9089 definitions."
9090 (let ((contexts
9091 ;; normalize contexts
9092 (mapcar
9093 (lambda(c) (cond ((listp (cadr c))
9094 (list (car c) (car c) (cadr c)))
9095 ((string= "" (cadr c))
9096 (list (car c) (car c) (caddr c)))
9097 (t c))) contexts))
9098 (a alist) c r s)
9099 ;; loop over all commands or templates
9100 (while (setq c (pop a))
9101 (let (vrules repl)
9102 (cond
9103 ((not (assoc (car c) contexts))
9104 (push c r))
9105 ((and (assoc (car c) contexts)
9106 (setq vrules (org-contextualize-validate-key
9107 (car c) contexts)))
9108 (mapc (lambda (vr)
9109 (when (not (equal (car vr) (cadr vr)))
9110 (setq repl vr))) vrules)
9111 (if (not repl) (push c r)
9112 (push (cadr repl) s)
9113 (push
9114 (cons (car c)
9115 (cdr (or (assoc (cadr repl) alist)
9116 (error "Undefined key `%s' as contextual replacement for `%s'"
9117 (cadr repl) (car c)))))
9118 r))))))
9119 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9120 (delq
9122 (delete-dups
9123 (mapcar (lambda (x)
9124 (let ((tpl (car x)))
9125 (when (not (delq
9127 (mapcar (lambda(y)
9128 (equal y tpl)) s))) x)))
9129 (reverse r))))))
9131 (defun org-contextualize-validate-key (key contexts)
9132 "Check CONTEXTS for agenda or capture KEY."
9133 (let (r rr res)
9134 (while (setq r (pop contexts))
9135 (mapc
9136 (lambda (rr)
9137 (when
9138 (and (equal key (car r))
9139 (if (functionp rr) (funcall rr)
9140 (or (and (eq (car rr) 'in-file)
9141 (buffer-file-name)
9142 (string-match (cdr rr) (buffer-file-name)))
9143 (and (eq (car rr) 'in-mode)
9144 (string-match (cdr rr) (symbol-name major-mode)))
9145 (and (eq (car rr) 'in-buffer)
9146 (string-match (cdr rr) (buffer-name)))
9147 (if (and (eq (car rr) 'not-in-file)
9148 (buffer-file-name))
9149 (not (string-match (cdr rr) (buffer-file-name)))
9151 (when (eq (car rr) 'not-in-mode)
9152 (not (string-match (cdr rr) (symbol-name major-mode))))
9153 (when (eq (car rr) 'not-in-buffer)
9154 (not (string-match (cdr rr) (buffer-name)))))))
9155 (push r res)))
9156 (car (last r))))
9157 (delete-dups (delq nil res))))
9159 (defun org-context-p (&rest contexts)
9160 "Check if local context is any of CONTEXTS.
9161 Possible values in the list of contexts are `table', `headline', and `item'."
9162 (let ((pos (point)))
9163 (goto-char (point-at-bol))
9164 (prog1 (or (and (memq 'table contexts)
9165 (looking-at "[ \t]*|"))
9166 (and (memq 'headline contexts)
9167 (looking-at org-outline-regexp))
9168 (and (memq 'item contexts)
9169 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9170 (and (memq 'item-body contexts)
9171 (org-in-item-p)))
9172 (goto-char pos))))
9174 (defun org-get-local-variables ()
9175 "Return a list of all local variables in an Org mode buffer."
9176 (let (varlist)
9177 (with-current-buffer (get-buffer-create "*Org tmp*")
9178 (erase-buffer)
9179 (org-mode)
9180 (setq varlist (buffer-local-variables)))
9181 (kill-buffer "*Org tmp*")
9182 (delq nil
9183 (mapcar
9184 (lambda (x)
9185 (setq x
9186 (if (symbolp x)
9187 (list x)
9188 (list (car x) (cdr x))))
9189 (if (and (not (get (car x) 'org-state))
9190 (string-match
9191 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9192 (symbol-name (car x))))
9193 x nil))
9194 varlist))))
9196 (defun org-clone-local-variables (from-buffer &optional regexp)
9197 "Clone local variables from FROM-BUFFER.
9198 Optional argument REGEXP selects variables to clone."
9199 (mapc
9200 (lambda (pair)
9201 (and (symbolp (car pair))
9202 (or (null regexp)
9203 (string-match regexp (symbol-name (car pair))))
9204 (set (make-local-variable (car pair))
9205 (cdr pair))))
9206 (buffer-local-variables from-buffer)))
9208 ;;;###autoload
9209 (defun org-run-like-in-org-mode (cmd)
9210 "Run a command, pretending that the current buffer is in Org-mode.
9211 This will temporarily bind local variables that are typically bound in
9212 Org-mode to the values they have in Org-mode, and then interactively
9213 call CMD."
9214 (org-load-modules-maybe)
9215 (unless org-local-vars
9216 (setq org-local-vars (org-get-local-variables)))
9217 (let (binds)
9218 (dolist (var org-local-vars)
9219 (when (or (not (boundp (car var)))
9220 (eq (symbol-value (car var))
9221 (default-value (car var))))
9222 (push (list (car var) `(quote ,(cadr var))) binds)))
9223 (eval `(let ,binds
9224 (call-interactively (quote ,cmd))))))
9226 ;;;; Archiving
9228 (defun org-get-category (&optional pos force-refresh)
9229 "Get the category applying to position POS."
9230 (save-match-data
9231 (if force-refresh (org-refresh-category-properties))
9232 (let ((pos (or pos (point))))
9233 (or (get-text-property pos 'org-category)
9234 (progn (org-refresh-category-properties)
9235 (get-text-property pos 'org-category))))))
9237 (defun org-refresh-category-properties ()
9238 "Refresh category text properties in the buffer."
9239 (let ((case-fold-search t)
9240 (inhibit-read-only t)
9241 (def-cat (cond
9242 ((null org-category)
9243 (if buffer-file-name
9244 (file-name-sans-extension
9245 (file-name-nondirectory buffer-file-name))
9246 "???"))
9247 ((symbolp org-category) (symbol-name org-category))
9248 (t org-category)))
9249 beg end cat pos optionp)
9250 (org-with-silent-modifications
9251 (save-excursion
9252 (save-restriction
9253 (widen)
9254 (goto-char (point-min))
9255 (put-text-property (point) (point-max) 'org-category def-cat)
9256 (while (re-search-forward
9257 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9258 (setq pos (match-end 0)
9259 optionp (equal (char-after (match-beginning 0)) ?#)
9260 cat (org-trim (match-string 2)))
9261 (if optionp
9262 (setq beg (point-at-bol) end (point-max))
9263 (org-back-to-heading t)
9264 (setq beg (point) end (org-end-of-subtree t t)))
9265 (put-text-property beg end 'org-category cat)
9266 (put-text-property beg end 'org-category-position beg)
9267 (goto-char pos)))))))
9269 (defun org-refresh-properties (dprop tprop)
9270 "Refresh buffer text properties.
9271 DPROP is the drawer property and TPROP is the corresponding text
9272 property to set."
9273 (let ((case-fold-search t)
9274 (inhibit-read-only t) p)
9275 (org-with-silent-modifications
9276 (save-excursion
9277 (save-restriction
9278 (widen)
9279 (goto-char (point-min))
9280 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9281 (setq p (org-match-string-no-properties 1))
9282 (save-excursion
9283 (org-back-to-heading t)
9284 (put-text-property
9285 (point-at-bol) (outline-next-heading) tprop p))))))))
9288 ;;;; Link Stuff
9290 ;;; Link abbreviations
9292 (defun org-link-expand-abbrev (link)
9293 "Apply replacements as defined in `org-link-abbrev-alist'."
9294 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9295 (let* ((key (match-string 1 link))
9296 (as (or (assoc key org-link-abbrev-alist-local)
9297 (assoc key org-link-abbrev-alist)))
9298 (tag (and (match-end 2) (match-string 3 link)))
9299 rpl)
9300 (if (not as)
9301 link
9302 (setq rpl (cdr as))
9303 (cond
9304 ((symbolp rpl) (funcall rpl tag))
9305 ((string-match "%(\\([^)]+\\))" rpl)
9306 (replace-match
9307 (save-match-data
9308 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9309 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9310 ((string-match "%h" rpl)
9311 (replace-match (url-hexify-string (or tag "")) t t rpl))
9312 (t (concat rpl tag)))))
9313 link))
9315 ;;; Storing and inserting links
9317 (defvar org-insert-link-history nil
9318 "Minibuffer history for links inserted with `org-insert-link'.")
9320 (defvar org-stored-links nil
9321 "Contains the links stored with `org-store-link'.")
9323 (defvar org-store-link-plist nil
9324 "Plist with info about the most recently link created with `org-store-link'.")
9326 (defvar org-link-protocols nil
9327 "Link protocols added to Org-mode using `org-add-link-type'.")
9329 (defvar org-store-link-functions nil
9330 "List of functions that are called to create and store a link.
9331 Each function will be called in turn until one returns a non-nil
9332 value. Each function should check if it is responsible for creating
9333 this link (for example by looking at the major mode).
9334 If not, it must exit and return nil.
9335 If yes, it should return a non-nil value after a calling
9336 `org-store-link-props' with a list of properties and values.
9337 Special properties are:
9339 :type The link prefix, like \"http\". This must be given.
9340 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9341 This is obligatory as well.
9342 :description Optional default description for the second pair
9343 of brackets in an Org-mode link. The user can still change
9344 this when inserting this link into an Org-mode buffer.
9346 In addition to these, any additional properties can be specified
9347 and then used in capture templates.")
9349 (defun org-add-link-type (type &optional follow export)
9350 "Add TYPE to the list of `org-link-types'.
9351 Re-compute all regular expressions depending on `org-link-types'
9353 FOLLOW and EXPORT are two functions.
9355 FOLLOW should take the link path as the single argument and do whatever
9356 is necessary to follow the link, for example find a file or display
9357 a mail message.
9359 EXPORT should format the link path for export to one of the export formats.
9360 It should be a function accepting three arguments:
9362 path the path of the link, the text after the prefix (like \"http:\")
9363 desc the description of the link, if any, or a description added by
9364 org-export-normalize-links if there is none
9365 format the export format, a symbol like `html' or `latex' or `ascii'..
9367 The function may use the FORMAT information to return different values
9368 depending on the format. The return value will be put literally into
9369 the exported file. If the return value is nil, this means Org should
9370 do what it normally does with links which do not have EXPORT defined.
9372 Org-mode has a built-in default for exporting links. If you are happy with
9373 this default, there is no need to define an export function for the link
9374 type. For a simple example of an export function, see `org-bbdb.el'."
9375 (add-to-list 'org-link-types type t)
9376 (org-make-link-regexps)
9377 (if (assoc type org-link-protocols)
9378 (setcdr (assoc type org-link-protocols) (list follow export))
9379 (push (list type follow export) org-link-protocols)))
9381 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9382 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9384 ;;;###autoload
9385 (defun org-store-link (arg)
9386 "\\<org-mode-map>Store an org-link to the current location.
9387 This link is added to `org-stored-links' and can later be inserted
9388 into an org-buffer with \\[org-insert-link].
9390 For some link types, a prefix arg is interpreted.
9391 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9392 For file links, arg negates `org-context-in-file-links'.
9394 A double prefix arg force skipping storing functions that are not
9395 part of Org's core.
9397 A triple prefix arg force storing a link for each line in the
9398 active region."
9399 (interactive "P")
9400 (org-load-modules-maybe)
9401 (if (and (equal arg '(64)) (org-region-active-p))
9402 (save-excursion
9403 (let ((end (region-end)))
9404 (goto-char (region-beginning))
9405 (set-mark (point))
9406 (while (< (point-at-eol) end)
9407 (move-end-of-line 1) (activate-mark)
9408 (let (current-prefix-arg)
9409 (call-interactively 'org-store-link))
9410 (move-beginning-of-line 2)
9411 (set-mark (point)))))
9412 (org-with-limited-levels
9413 (setq org-store-link-plist nil)
9414 (let (link cpltxt desc description search
9415 txt custom-id agenda-link sfuns sfunsn)
9416 (cond
9418 ;; Store a link using an external link type
9419 ((and (not (equal arg '(16)))
9420 (setq sfuns
9421 (delq
9422 nil (mapcar (lambda (f)
9423 (let (fs) (if (funcall f) (push f fs))))
9424 org-store-link-functions))
9425 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9426 (or (and (cdr sfuns)
9427 (funcall (intern
9428 (completing-read
9429 "Which function for creating the link? "
9430 sfunsn nil t (car sfunsn)))))
9431 (funcall (caar sfuns)))
9432 (setq link (plist-get org-store-link-plist :link)
9433 desc (or (plist-get org-store-link-plist
9434 :description) link))))
9436 ;; Store a link from a source code buffer
9437 ((org-src-edit-buffer-p)
9438 (let (label gc)
9439 (while (or (not label)
9440 (save-excursion
9441 (save-restriction
9442 (widen)
9443 (goto-char (point-min))
9444 (re-search-forward
9445 (regexp-quote (format org-coderef-label-format label))
9446 nil t))))
9447 (when label (message "Label exists already") (sit-for 2))
9448 (setq label (read-string "Code line label: " label)))
9449 (end-of-line 1)
9450 (setq link (format org-coderef-label-format label))
9451 (setq gc (- 79 (length link)))
9452 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9453 (insert link)
9454 (setq link (concat "(" label ")") desc nil)))
9456 ;; We are in the agenda, link to referenced location
9457 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9458 (let ((m (or (get-text-property (point) 'org-hd-marker)
9459 (get-text-property (point) 'org-marker))))
9460 (when m
9461 (org-with-point-at m
9462 (setq agenda-link
9463 (if (org-called-interactively-p 'any)
9464 (call-interactively 'org-store-link)
9465 (org-store-link nil)))))))
9467 ((eq major-mode 'calendar-mode)
9468 (let ((cd (calendar-cursor-to-date)))
9469 (setq link
9470 (format-time-string
9471 (car org-time-stamp-formats)
9472 (apply 'encode-time
9473 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9474 nil nil nil))))
9475 (org-store-link-props :type "calendar" :date cd)))
9477 ((eq major-mode 'help-mode)
9478 (setq link (concat "help:" (save-excursion
9479 (goto-char (point-min))
9480 (looking-at "^[^ ]+")
9481 (match-string 0))))
9482 (org-store-link-props :type "help"))
9484 ((eq major-mode 'w3-mode)
9485 (setq cpltxt (if (and (buffer-name)
9486 (not (string-match "Untitled" (buffer-name))))
9487 (buffer-name)
9488 (url-view-url t))
9489 link (url-view-url t))
9490 (org-store-link-props :type "w3" :url (url-view-url t)))
9492 ((eq major-mode 'image-mode)
9493 (setq cpltxt (concat "file:"
9494 (abbreviate-file-name buffer-file-name))
9495 link cpltxt)
9496 (org-store-link-props :type "image" :file buffer-file-name))
9498 ;; In dired, store a link to the file of the current line
9499 ((eq major-mode 'dired-mode)
9500 (let ((file (dired-get-filename nil t)))
9501 (setq file (if file
9502 (abbreviate-file-name
9503 (expand-file-name (dired-get-filename nil t)))
9504 ;; otherwise, no file so use current directory.
9505 default-directory))
9506 (setq cpltxt (concat "file:" file)
9507 link cpltxt)))
9509 ((setq search (run-hook-with-args-until-success
9510 'org-create-file-search-functions))
9511 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9512 "::" search))
9513 (setq cpltxt (or description link)))
9515 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9516 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9517 (cond
9518 ;; Store a link using the target at point
9519 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9520 (setq cpltxt
9521 (concat "file:"
9522 (abbreviate-file-name
9523 (buffer-file-name (buffer-base-buffer)))
9524 "::" (match-string 1))
9525 link cpltxt))
9526 ((and (featurep 'org-id)
9527 (or (eq org-id-link-to-org-use-id t)
9528 (and (org-called-interactively-p 'any)
9529 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9530 (and (eq org-id-link-to-org-use-id
9531 'create-if-interactive-and-no-custom-id)
9532 (not custom-id))))
9533 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9534 ;; Store a link using the ID at point
9535 (setq link (condition-case nil
9536 (prog1 (org-id-store-link)
9537 (setq desc (or (plist-get org-store-link-plist
9538 :description)
9539 "")))
9540 (error
9541 ;; Probably before first headline, link only to file
9542 (concat "file:"
9543 (abbreviate-file-name
9544 (buffer-file-name (buffer-base-buffer))))))))
9546 ;; Just link to current headline
9547 (setq cpltxt (concat "file:"
9548 (abbreviate-file-name
9549 (buffer-file-name (buffer-base-buffer)))))
9550 ;; Add a context search string
9551 (when (org-xor org-context-in-file-links arg)
9552 (let* ((ee (org-element-at-point))
9553 (et (org-element-type ee))
9554 (ev (plist-get (cadr ee) :value))
9555 (ek (plist-get (cadr ee) :key))
9556 (eok (and (stringp ek) (string-match "name" ek))))
9557 (setq txt (cond
9558 ((org-at-heading-p) nil)
9559 ((and (eq et 'keyword) eok) ev)
9560 ((org-region-active-p)
9561 (buffer-substring (region-beginning) (region-end)))))
9562 (when (or (null txt) (string-match "\\S-" txt))
9563 (setq cpltxt
9564 (concat cpltxt "::"
9565 (condition-case nil
9566 (org-make-org-heading-search-string txt)
9567 (error "")))
9568 desc (or (and (eq et 'keyword) eok ev)
9569 (nth 4 (ignore-errors (org-heading-components)))
9570 "NONE")))))
9571 (if (string-match "::\\'" cpltxt)
9572 (setq cpltxt (substring cpltxt 0 -2)))
9573 (setq link cpltxt))))
9575 ((buffer-file-name (buffer-base-buffer))
9576 ;; Just link to this file here.
9577 (setq cpltxt (concat "file:"
9578 (abbreviate-file-name
9579 (buffer-file-name (buffer-base-buffer)))))
9580 ;; Add a context string.
9581 (when (org-xor org-context-in-file-links arg)
9582 (setq txt (if (org-region-active-p)
9583 (buffer-substring (region-beginning) (region-end))
9584 (buffer-substring (point-at-bol) (point-at-eol))))
9585 ;; Only use search option if there is some text.
9586 (when (string-match "\\S-" txt)
9587 (setq cpltxt
9588 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9589 desc "NONE")))
9590 (setq link cpltxt))
9592 ((org-called-interactively-p 'interactive)
9593 (user-error "No method for storing a link from this buffer"))
9595 (t (setq link nil)))
9597 ;; We're done setting link and desc, clean up
9598 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9599 (setq link (or link cpltxt)
9600 desc (or desc cpltxt))
9601 (cond ((equal desc "NONE") (setq desc nil))
9602 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9603 (let ((d0 (match-string 3 desc))
9604 (p0 (match-string 5 desc)))
9605 (setq desc
9606 (replace-regexp-in-string
9607 org-bracket-link-regexp
9608 (concat (or p0 d0)
9609 (if (equal (length (match-string 0 desc))
9610 (length desc)) "*" "")) desc)))))
9612 ;; Return the link
9613 (if (not (and (or (org-called-interactively-p 'any)
9614 executing-kbd-macro) link))
9615 (or agenda-link (and link (org-make-link-string link desc)))
9616 (push (list link desc) org-stored-links)
9617 (message "Stored: %s" (or desc link))
9618 (when custom-id
9619 (setq link (concat "file:" (abbreviate-file-name
9620 (buffer-file-name)) "::#" custom-id))
9621 (push (list link desc) org-stored-links))
9622 (car org-stored-links))))))
9624 (defun org-store-link-props (&rest plist)
9625 "Store link properties, extract names and addresses."
9626 (let (x adr)
9627 (when (setq x (plist-get plist :from))
9628 (setq adr (mail-extract-address-components x))
9629 (setq plist (plist-put plist :fromname (car adr)))
9630 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9631 (when (setq x (plist-get plist :to))
9632 (setq adr (mail-extract-address-components x))
9633 (setq plist (plist-put plist :toname (car adr)))
9634 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9635 (let ((from (plist-get plist :from))
9636 (to (plist-get plist :to)))
9637 (when (and from to org-from-is-user-regexp)
9638 (setq plist
9639 (plist-put plist :fromto
9640 (if (string-match org-from-is-user-regexp from)
9641 (concat "to %t")
9642 (concat "from %f"))))))
9643 (setq org-store-link-plist plist))
9645 (defun org-add-link-props (&rest plist)
9646 "Add these properties to the link property list."
9647 (let (key value)
9648 (while plist
9649 (setq key (pop plist) value (pop plist))
9650 (setq org-store-link-plist
9651 (plist-put org-store-link-plist key value)))))
9653 (defun org-email-link-description (&optional fmt)
9654 "Return the description part of an email link.
9655 This takes information from `org-store-link-plist' and formats it
9656 according to FMT (default from `org-email-link-description-format')."
9657 (setq fmt (or fmt org-email-link-description-format))
9658 (let* ((p org-store-link-plist)
9659 (to (plist-get p :toaddress))
9660 (from (plist-get p :fromaddress))
9661 (table
9662 (list
9663 (cons "%c" (plist-get p :fromto))
9664 (cons "%F" (plist-get p :from))
9665 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9666 (cons "%T" (plist-get p :to))
9667 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9668 (cons "%s" (plist-get p :subject))
9669 (cons "%d" (plist-get p :date))
9670 (cons "%m" (plist-get p :message-id)))))
9671 (when (string-match "%c" fmt)
9672 ;; Check if the user wrote this message
9673 (if (and org-from-is-user-regexp from to
9674 (save-match-data (string-match org-from-is-user-regexp from)))
9675 (setq fmt (replace-match "to %t" t t fmt))
9676 (setq fmt (replace-match "from %f" t t fmt))))
9677 (org-replace-escapes fmt table)))
9679 (defun org-make-org-heading-search-string (&optional string)
9680 "Make search string for the current headline or STRING."
9681 (let ((s (or string
9682 (and (derived-mode-p 'org-mode)
9683 (save-excursion
9684 (org-back-to-heading t)
9685 (org-element-property :raw-value (org-element-at-point))))))
9686 (lines org-context-in-file-links))
9687 (or string (setq s (concat "*" s))) ; Add * for headlines
9688 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9689 (when (and string (integerp lines) (> lines 0))
9690 (let ((slines (org-split-string s "\n")))
9691 (when (< lines (length slines))
9692 (setq s (mapconcat
9693 'identity
9694 (reverse (nthcdr (- (length slines) lines)
9695 (reverse slines))) "\n")))))
9696 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9698 (defun org-make-link-string (link &optional description)
9699 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9700 (unless (string-match "\\S-" link)
9701 (error "Empty link"))
9702 (when (and description
9703 (stringp description)
9704 (not (string-match "\\S-" description)))
9705 (setq description nil))
9706 (when (stringp description)
9707 ;; Remove brackets from the description, they are fatal.
9708 (while (string-match "\\[" description)
9709 (setq description (replace-match "{" t t description)))
9710 (while (string-match "\\]" description)
9711 (setq description (replace-match "}" t t description))))
9712 (when (equal link description)
9713 ;; No description needed, it is identical
9714 (setq description nil))
9715 (when (and (not description)
9716 (not (string-match (org-image-file-name-regexp) link))
9717 (not (equal link (org-link-escape link))))
9718 (setq description (org-extract-attributes link)))
9719 (setq link
9720 (cond ((string-match (org-image-file-name-regexp) link) link)
9721 ((string-match org-link-types-re link)
9722 (concat (match-string 1 link)
9723 (org-link-escape (substring link (match-end 1)))))
9724 (t (org-link-escape link))))
9725 (concat "[[" link "]"
9726 (if description (concat "[" description "]") "")
9727 "]"))
9729 (defconst org-link-escape-chars
9730 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9731 "List of characters that should be escaped in link.
9732 This is the list that is used for internal purposes.")
9734 (defconst org-link-escape-chars-browser
9735 '(?\ ?\")
9736 "List of escapes for characters that are problematic in links.
9737 This is the list that is used before handing over to the browser.")
9739 (defun org-link-escape (text &optional table merge)
9740 "Return percent escaped representation of TEXT.
9741 TEXT is a string with the text to escape.
9742 Optional argument TABLE is a list with characters that should be
9743 escaped. When nil, `org-link-escape-chars' is used.
9744 If optional argument MERGE is set, merge TABLE into
9745 `org-link-escape-chars'."
9746 (cond
9747 ((and table merge)
9748 (mapc (lambda (defchr)
9749 (unless (member defchr table)
9750 (setq table (cons defchr table)))) org-link-escape-chars))
9751 ((null table)
9752 (setq table org-link-escape-chars)))
9753 (mapconcat
9754 (lambda (char)
9755 (if (or (member char table)
9756 (and (or (< char 32) (= char 37) (> char 126))
9757 org-url-hexify-p))
9758 (mapconcat (lambda (sequence-element)
9759 (format "%%%.2X" sequence-element))
9760 (or (encode-coding-char char 'utf-8)
9761 (error "Unable to percent escape character: %s"
9762 (char-to-string char))) "")
9763 (char-to-string char))) text ""))
9765 (defun org-link-unescape (str)
9766 "Unhex hexified Unicode strings as returned from the JavaScript function
9767 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9768 (unless (and (null str) (string= "" str))
9769 (let ((pos 0) (case-fold-search t) unhexed)
9770 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9771 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9772 (setq str (replace-match unhexed t t str))
9773 (setq pos (+ pos (length unhexed))))))
9774 str)
9776 (defun org-link-unescape-compound (hex)
9777 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9778 Note: this function also decodes single byte encodings like
9779 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9780 (save-match-data
9781 (let* ((bytes (cdr (split-string hex "%")))
9782 (ret "")
9783 (eat 0)
9784 (sum 0))
9785 (while bytes
9786 (let* ((val (string-to-number (pop bytes) 16))
9787 (shift-xor
9788 (if (= 0 eat)
9789 (cond
9790 ((>= val 252) (cons 6 252))
9791 ((>= val 248) (cons 5 248))
9792 ((>= val 240) (cons 4 240))
9793 ((>= val 224) (cons 3 224))
9794 ((>= val 192) (cons 2 192))
9795 (t (cons 0 0)))
9796 (cons 6 128))))
9797 (if (>= val 192) (setq eat (car shift-xor)))
9798 (setq val (logxor val (cdr shift-xor)))
9799 (setq sum (+ (lsh sum (car shift-xor)) val))
9800 (if (> eat 0) (setq eat (- eat 1)))
9801 (cond
9802 ((= 0 eat) ;multi byte
9803 (setq ret (concat ret (org-char-to-string sum)))
9804 (setq sum 0))
9805 ((not bytes) ; single byte(s)
9806 (setq ret (org-link-unescape-single-byte-sequence hex))))
9807 )) ;; end (while bytes
9808 ret )))
9810 (defun org-link-unescape-single-byte-sequence (hex)
9811 "Unhexify hex-encoded single byte character sequences."
9812 (mapconcat (lambda (byte)
9813 (char-to-string (string-to-number byte 16)))
9814 (cdr (split-string hex "%")) ""))
9816 (defun org-xor (a b)
9817 "Exclusive or."
9818 (if a (not b) b))
9820 (defun org-fixup-message-id-for-http (s)
9821 "Replace special characters in a message id, so it can be used in an http query."
9822 (when (string-match "%" s)
9823 (setq s (mapconcat (lambda (c)
9824 (if (eq c ?%)
9825 "%25"
9826 (char-to-string c)))
9827 s "")))
9828 (while (string-match "<" s)
9829 (setq s (replace-match "%3C" t t s)))
9830 (while (string-match ">" s)
9831 (setq s (replace-match "%3E" t t s)))
9832 (while (string-match "@" s)
9833 (setq s (replace-match "%40" t t s)))
9836 (defun org-link-prettify (link)
9837 "Return a human-readable representation of LINK.
9838 The car of LINK must be a raw link the cdr of LINK must be either
9839 a link description or nil."
9840 (let ((desc (or (cadr link) "<no description>")))
9841 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9842 "<" (car link) ">")))
9844 ;;;###autoload
9845 (defun org-insert-link-global ()
9846 "Insert a link like Org-mode does.
9847 This command can be called in any mode to insert a link in Org-mode syntax."
9848 (interactive)
9849 (org-load-modules-maybe)
9850 (org-run-like-in-org-mode 'org-insert-link))
9852 (defun org-insert-all-links (&optional keep)
9853 "Insert all links in `org-stored-links'."
9854 (interactive "P")
9855 (let ((links (copy-sequence org-stored-links)) l)
9856 (while (setq l (if keep (pop links) (pop org-stored-links)))
9857 (insert "- ")
9858 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9859 (insert "\n"))))
9861 (defun org-link-fontify-links-to-this-file ()
9862 "Fontify links to the current file in `org-stored-links'."
9863 (let ((f (buffer-file-name)) a b)
9864 (setq a (mapcar (lambda(l)
9865 (let ((ll (car l)))
9866 (when (and (string-match "^file:\\(.+\\)::" ll)
9867 (equal f (expand-file-name (match-string 1 ll))))
9868 ll)))
9869 org-stored-links))
9870 (when (featurep 'org-id)
9871 (setq b (mapcar (lambda(l)
9872 (let ((ll (car l)))
9873 (when (and (string-match "^id:\\(.+\\)$" ll)
9874 (equal f (expand-file-name
9875 (or (org-id-find-id-file
9876 (match-string 1 ll)) ""))))
9877 ll)))
9878 org-stored-links)))
9879 (mapcar (lambda(l)
9880 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9881 (delq nil (append a b)))))
9883 (defvar org-link-links-in-this-file nil)
9884 (defun org-insert-link (&optional complete-file link-location default-description)
9885 "Insert a link. At the prompt, enter the link.
9887 Completion can be used to insert any of the link protocol prefixes like
9888 http or ftp in use.
9890 The history can be used to select a link previously stored with
9891 `org-store-link'. When the empty string is entered (i.e. if you just
9892 press RET at the prompt), the link defaults to the most recently
9893 stored link. As SPC triggers completion in the minibuffer, you need to
9894 use M-SPC or C-q SPC to force the insertion of a space character.
9896 You will also be prompted for a description, and if one is given, it will
9897 be displayed in the buffer instead of the link.
9899 If there is already a link at point, this command will allow you to edit link
9900 and description parts.
9902 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9903 be selected using completion. The path to the file will be relative to the
9904 current directory if the file is in the current directory or a subdirectory.
9905 Otherwise, the link will be the absolute path as completed in the minibuffer
9906 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9907 option `org-link-file-path-type'.
9909 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9910 the current directory or below.
9912 With three \\[universal-argument] prefixes, negate the meaning of
9913 `org-keep-stored-link-after-insertion'.
9915 If `org-make-link-description-function' is non-nil, this function will be
9916 called with the link target, and the result will be the default
9917 link description.
9919 If the LINK-LOCATION parameter is non-nil, this value will be
9920 used as the link location instead of reading one interactively.
9922 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9923 be used as the default description."
9924 (interactive "P")
9925 (let* ((wcf (current-window-configuration))
9926 (origbuf (current-buffer))
9927 (region (if (org-region-active-p)
9928 (buffer-substring (region-beginning) (region-end))))
9929 (remove (and region (list (region-beginning) (region-end))))
9930 (desc region)
9931 tmphist ; byte-compile incorrectly complains about this
9932 (link link-location)
9933 (abbrevs org-link-abbrev-alist-local)
9934 entry file all-prefixes auto-desc)
9935 (cond
9936 (link-location) ; specified by arg, just use it.
9937 ((org-in-regexp org-bracket-link-regexp 1)
9938 ;; We do have a link at point, and we are going to edit it.
9939 (setq remove (list (match-beginning 0) (match-end 0)))
9940 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9941 (setq link (read-string "Link: "
9942 (org-link-unescape
9943 (org-match-string-no-properties 1)))))
9944 ((or (org-in-regexp org-angle-link-re)
9945 (org-in-regexp org-plain-link-re))
9946 ;; Convert to bracket link
9947 (setq remove (list (match-beginning 0) (match-end 0))
9948 link (read-string "Link: "
9949 (org-remove-angle-brackets (match-string 0)))))
9950 ((member complete-file '((4) (16)))
9951 ;; Completing read for file names.
9952 (setq link (org-file-complete-link complete-file)))
9954 ;; Read link, with completion for stored links.
9955 (org-link-fontify-links-to-this-file)
9956 (org-switch-to-buffer-other-window "*Org Links*")
9957 (with-current-buffer "*Org Links*"
9958 (erase-buffer)
9959 (insert "Insert a link.
9960 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9961 (when org-stored-links
9962 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9963 (insert (mapconcat 'org-link-prettify
9964 (reverse org-stored-links) "\n")))
9965 (goto-char (point-min)))
9966 (let ((cw (selected-window)))
9967 (select-window (get-buffer-window "*Org Links*" 'visible))
9968 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9969 (unless (pos-visible-in-window-p (point-max))
9970 (org-fit-window-to-buffer))
9971 (and (window-live-p cw) (select-window cw)))
9972 ;; Fake a link history, containing the stored links.
9973 (setq tmphist (append (mapcar 'car org-stored-links)
9974 org-insert-link-history))
9975 (setq all-prefixes (append (mapcar 'car abbrevs)
9976 (mapcar 'car org-link-abbrev-alist)
9977 org-link-types))
9978 (unwind-protect
9979 (progn
9980 (setq link
9981 (org-completing-read
9982 "Link: "
9983 (append
9984 (mapcar (lambda (x) (concat x ":"))
9985 all-prefixes)
9986 (mapcar 'car org-stored-links))
9987 nil nil nil
9988 'tmphist
9989 (caar org-stored-links)))
9990 (if (not (string-match "\\S-" link))
9991 (user-error "No link selected"))
9992 (mapc (lambda(l)
9993 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9994 org-stored-links)
9995 (if (or (member link all-prefixes)
9996 (and (equal ":" (substring link -1))
9997 (member (substring link 0 -1) all-prefixes)
9998 (setq link (substring link 0 -1))))
9999 (setq link (with-current-buffer origbuf
10000 (org-link-try-special-completion link)))))
10001 (set-window-configuration wcf)
10002 (kill-buffer "*Org Links*"))
10003 (setq entry (assoc link org-stored-links))
10004 (or entry (push link org-insert-link-history))
10005 (setq desc (or desc (nth 1 entry)))))
10007 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10008 (not org-keep-stored-link-after-insertion))
10009 (setq org-stored-links (delq (assoc link org-stored-links)
10010 org-stored-links)))
10012 (if (and (string-match org-plain-link-re link)
10013 (not (string-match org-ts-regexp link)))
10014 ;; URL-like link, normalize the use of angular brackets.
10015 (setq link (org-remove-angle-brackets link)))
10017 ;; Check if we are linking to the current file with a search
10018 ;; option If yes, simplify the link by using only the search
10019 ;; option.
10020 (when (and buffer-file-name
10021 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10022 (let* ((path (match-string 1 link))
10023 (case-fold-search nil)
10024 (search (match-string 2 link)))
10025 (save-match-data
10026 (if (equal (file-truename buffer-file-name) (file-truename path))
10027 ;; We are linking to this same file, with a search option
10028 (setq link search)))))
10030 ;; Check if we can/should use a relative path. If yes, simplify the link
10031 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10032 (let* ((type (match-string 1 link))
10033 (path (match-string 2 link))
10034 (origpath path)
10035 (case-fold-search nil))
10036 (cond
10037 ((or (eq org-link-file-path-type 'absolute)
10038 (equal complete-file '(16)))
10039 (setq path (abbreviate-file-name (expand-file-name path))))
10040 ((eq org-link-file-path-type 'noabbrev)
10041 (setq path (expand-file-name path)))
10042 ((eq org-link-file-path-type 'relative)
10043 (setq path (file-relative-name path)))
10045 (save-match-data
10046 (if (string-match (concat "^" (regexp-quote
10047 (expand-file-name
10048 (file-name-as-directory
10049 default-directory))))
10050 (expand-file-name path))
10051 ;; We are linking a file with relative path name.
10052 (setq path (substring (expand-file-name path)
10053 (match-end 0)))
10054 (setq path (abbreviate-file-name (expand-file-name path)))))))
10055 (setq link (concat type path))
10056 (if (equal desc origpath)
10057 (setq desc path))))
10059 (if org-make-link-description-function
10060 (setq desc
10061 (or (condition-case nil
10062 (funcall org-make-link-description-function link desc)
10063 (error (progn (message "Can't get link description from `%s'"
10064 (symbol-name org-make-link-description-function))
10065 (sit-for 2) nil)))
10066 (read-string "Description: " default-description)))
10067 (if default-description (setq desc default-description)
10068 (setq desc (or (and auto-desc desc)
10069 (read-string "Description: " desc)))))
10071 (unless (string-match "\\S-" desc) (setq desc nil))
10072 (if remove (apply 'delete-region remove))
10073 (insert (org-make-link-string link desc))))
10075 (defun org-link-try-special-completion (type)
10076 "If there is completion support for link type TYPE, offer it."
10077 (let ((fun (intern (concat "org-" type "-complete-link"))))
10078 (if (functionp fun)
10079 (funcall fun)
10080 (read-string "Link (no completion support): " (concat type ":")))))
10082 (defun org-file-complete-link (&optional arg)
10083 "Create a file link using completion."
10084 (let (file link)
10085 (setq file (org-iread-file-name "File: "))
10086 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10087 (pwd1 (file-name-as-directory (abbreviate-file-name
10088 (expand-file-name ".")))))
10089 (cond
10090 ((equal arg '(16))
10091 (setq link (concat
10092 "file:"
10093 (abbreviate-file-name (expand-file-name file)))))
10094 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10095 (setq link (concat "file:" (match-string 1 file))))
10096 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10097 (expand-file-name file))
10098 (setq link (concat
10099 "file:" (match-string 1 (expand-file-name file)))))
10100 (t (setq link (concat "file:" file)))))
10101 link))
10103 (defun org-iread-file-name (&rest args)
10104 "Read-file-name using `ido-mode' speedup if available.
10105 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10106 See `read-file-name' for a description of parameters."
10107 (org-without-partial-completion
10108 (if (and org-completion-use-ido
10109 (fboundp 'ido-read-file-name)
10110 (boundp 'ido-mode) ido-mode
10111 (listp (second args)))
10112 (let ((ido-enter-matching-directory nil))
10113 (apply 'ido-read-file-name args))
10114 (apply 'read-file-name args))))
10116 (defun org-completing-read (&rest args)
10117 "Completing-read with SPACE being a normal character."
10118 (let ((enable-recursive-minibuffers t)
10119 (minibuffer-local-completion-map
10120 (copy-keymap minibuffer-local-completion-map)))
10121 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10122 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10123 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10124 (apply 'org-icompleting-read args)))
10126 (defun org-completing-read-no-i (&rest args)
10127 (let (org-completion-use-ido org-completion-use-iswitchb)
10128 (apply 'org-completing-read args)))
10130 (defun org-iswitchb-completing-read (prompt choices &rest args)
10131 "Use iswitch as a completing-read replacement to choose from choices.
10132 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10133 from."
10134 (let* ((iswitchb-use-virtual-buffers nil)
10135 (iswitchb-make-buflist-hook
10136 (lambda ()
10137 (setq iswitchb-temp-buflist choices))))
10138 (iswitchb-read-buffer prompt)))
10140 (defun org-icompleting-read (&rest args)
10141 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10142 (org-without-partial-completion
10143 (if (and org-completion-use-ido
10144 (fboundp 'ido-completing-read)
10145 (boundp 'ido-mode) ido-mode
10146 (listp (second args)))
10147 (let ((ido-enter-matching-directory nil))
10148 (apply 'ido-completing-read (concat (car args))
10149 (if (consp (car (nth 1 args)))
10150 (mapcar 'car (nth 1 args))
10151 (nth 1 args))
10152 (cddr args)))
10153 (if (and org-completion-use-iswitchb
10154 (boundp 'iswitchb-mode) iswitchb-mode
10155 (listp (second args)))
10156 (apply 'org-iswitchb-completing-read (concat (car args))
10157 (if (consp (car (nth 1 args)))
10158 (mapcar 'car (nth 1 args))
10159 (nth 1 args))
10160 (cddr args))
10161 (apply 'completing-read args)))))
10163 (defun org-extract-attributes (s)
10164 "Extract the attributes cookie from a string and set as text property."
10165 (let (a attr (start 0) key value)
10166 (save-match-data
10167 (when (string-match "{{\\([^}]+\\)}}$" s)
10168 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10169 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10170 (setq key (match-string 1 a) value (match-string 2 a)
10171 start (match-end 0)
10172 attr (plist-put attr (intern key) value))))
10173 (org-add-props s nil 'org-attr attr))
10176 ;;; Opening/following a link
10178 (defvar org-link-search-failed nil)
10180 (defvar org-open-link-functions nil
10181 "Hook for functions finding a plain text link.
10182 These functions must take a single argument, the link content.
10183 They will be called for links that look like [[link text][description]]
10184 when LINK TEXT does not have a protocol like \"http:\" and does not look
10185 like a filename (e.g. \"./blue.png\").
10187 These functions will be called *before* Org attempts to resolve the
10188 link by doing text searches in the current buffer - so if you want a
10189 link \"[[target]]\" to still find \"<<target>>\", your function should
10190 handle this as a special case.
10192 When the function does handle the link, it must return a non-nil value.
10193 If it decides that it is not responsible for this link, it must return
10194 nil to indicate that that Org-mode can continue with other options
10195 like exact and fuzzy text search.")
10197 (defun org-next-link (&optional search-backward)
10198 "Move forward to the next link.
10199 If the link is in hidden text, expose it."
10200 (interactive "P")
10201 (when (and org-link-search-failed (eq this-command last-command))
10202 (goto-char (point-min))
10203 (message "Link search wrapped back to beginning of buffer"))
10204 (setq org-link-search-failed nil)
10205 (let* ((pos (point))
10206 (ct (org-context))
10207 (a (assoc :link ct))
10208 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10209 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10210 ((looking-at org-any-link-re)
10211 ;; Don't stay stuck at link without an org-link face
10212 (forward-char (if search-backward -1 1))))
10213 (if (funcall srch-fun org-any-link-re nil t)
10214 (progn
10215 (goto-char (match-beginning 0))
10216 (if (outline-invisible-p) (org-show-context)))
10217 (goto-char pos)
10218 (setq org-link-search-failed t)
10219 (message "No further link found"))))
10221 (defun org-previous-link ()
10222 "Move backward to the previous link.
10223 If the link is in hidden text, expose it."
10224 (interactive)
10225 (funcall 'org-next-link t))
10227 (defun org-translate-link (s)
10228 "Translate a link string if a translation function has been defined."
10229 (if (and org-link-translation-function
10230 (fboundp org-link-translation-function)
10231 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10232 (progn
10233 (setq s (funcall org-link-translation-function
10234 (match-string 1 s) (match-string 2 s)))
10235 (concat (car s) ":" (cdr s)))
10238 (defun org-translate-link-from-planner (type path)
10239 "Translate a link from Emacs Planner syntax so that Org can follow it.
10240 This is still an experimental function, your mileage may vary."
10241 (cond
10242 ((member type '("http" "https" "news" "ftp"))
10243 ;; standard Internet links are the same.
10244 nil)
10245 ((and (equal type "irc") (string-match "^//" path))
10246 ;; Planner has two / at the beginning of an irc link, we have 1.
10247 ;; We should have zero, actually....
10248 (setq path (substring path 1)))
10249 ((and (equal type "lisp") (string-match "^/" path))
10250 ;; Planner has a slash, we do not.
10251 (setq type "elisp" path (substring path 1)))
10252 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10253 ;; A typical message link. Planner has the id after the final slash,
10254 ;; we separate it with a hash mark
10255 (setq path (concat (match-string 1 path) "#"
10256 (org-remove-angle-brackets (match-string 2 path))))))
10257 (cons type path))
10259 (defun org-find-file-at-mouse (ev)
10260 "Open file link or URL at mouse."
10261 (interactive "e")
10262 (mouse-set-point ev)
10263 (org-open-at-point 'in-emacs))
10265 (defun org-open-at-mouse (ev)
10266 "Open file link or URL at mouse.
10267 See the docstring of `org-open-file' for details."
10268 (interactive "e")
10269 (mouse-set-point ev)
10270 (if (eq major-mode 'org-agenda-mode)
10271 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10272 (org-open-at-point))
10274 (defvar org-window-config-before-follow-link nil
10275 "The window configuration before following a link.
10276 This is saved in case the need arises to restore it.")
10278 (defvar org-open-link-marker (make-marker)
10279 "Marker pointing to the location where `org-open-at-point' was called.")
10281 ;;;###autoload
10282 (defun org-open-at-point-global ()
10283 "Follow a link like Org-mode does.
10284 This command can be called in any mode to follow a link that has
10285 Org-mode syntax."
10286 (interactive)
10287 (org-run-like-in-org-mode 'org-open-at-point))
10289 ;;;###autoload
10290 (defun org-open-link-from-string (s &optional arg reference-buffer)
10291 "Open a link in the string S, as if it was in Org-mode."
10292 (interactive "sLink: \nP")
10293 (let ((reference-buffer (or reference-buffer (current-buffer))))
10294 (with-temp-buffer
10295 (let ((org-inhibit-startup (not reference-buffer)))
10296 (org-mode)
10297 (insert s)
10298 (goto-char (point-min))
10299 (when reference-buffer
10300 (setq org-link-abbrev-alist-local
10301 (with-current-buffer reference-buffer
10302 org-link-abbrev-alist-local)))
10303 (org-open-at-point arg reference-buffer)))))
10305 (defvar org-open-at-point-functions nil
10306 "Hook that is run when following a link at point.
10308 Functions in this hook must return t if they identify and follow
10309 a link at point. If they don't find anything interesting at point,
10310 they must return nil.")
10312 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10313 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10314 (defun org-open-at-point (&optional arg reference-buffer)
10315 "Open link at or after point.
10316 If there is no link at point, this function will search forward up to
10317 the end of the current line.
10318 Normally, files will be opened by an appropriate application. If the
10319 optional prefix argument ARG is non-nil, Emacs will visit the file.
10320 With a double prefix argument, try to open outside of Emacs, in the
10321 application the system uses for this file type."
10322 (interactive "P")
10323 ;; if in a code block, then open the block's results
10324 (unless (call-interactively #'org-babel-open-src-block-result)
10325 (org-load-modules-maybe)
10326 (move-marker org-open-link-marker (point))
10327 (setq org-window-config-before-follow-link (current-window-configuration))
10328 (org-remove-occur-highlights nil nil t)
10329 (cond
10330 ((and (org-at-heading-p)
10331 (not (org-at-timestamp-p t))
10332 (not (org-in-regexp
10333 (concat org-plain-link-re "\\|"
10334 org-bracket-link-regexp "\\|"
10335 org-angle-link-re "\\|"
10336 "[ \t]:[^ \t\n]+:[ \t]*$")))
10337 (not (get-text-property (point) 'org-linked-text)))
10338 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10339 (lk0 (car lkall))
10340 (lk (if (stringp lk0) (list lk0) lk0))
10341 (lkend (cdr lkall)))
10342 (mapcar (lambda(l)
10343 (search-forward l nil lkend)
10344 (goto-char (match-beginning 0))
10345 (org-open-at-point))
10346 lk))
10347 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10348 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10349 ((and (org-at-timestamp-p t)
10350 (not (org-in-regexp org-bracket-link-regexp)))
10351 (org-follow-timestamp-link))
10352 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10353 (not (org-in-regexp org-any-link-re)))
10354 (org-footnote-action))
10356 (let (type path link line search (pos (point)))
10357 (catch 'match
10358 (save-excursion
10359 (or (org-in-regexp org-plain-link-re)
10360 (skip-chars-forward "^]\n\r"))
10361 (when (org-in-regexp org-bracket-link-regexp 1)
10362 (setq link (org-extract-attributes
10363 (org-link-unescape (org-match-string-no-properties 1))))
10364 (while (string-match " *\n *" link)
10365 (setq link (replace-match " " t t link)))
10366 (setq link (org-link-expand-abbrev link))
10367 (cond
10368 ((or (file-name-absolute-p link)
10369 (string-match "^\\.\\.?/" link))
10370 (setq type "file" path link))
10371 ((string-match org-link-re-with-space3 link)
10372 (setq type (match-string 1 link) path (match-string 2 link)))
10373 ((string-match "^help:+\\(.+\\)" link)
10374 (setq type "help" path (match-string 1 link)))
10375 (t (setq type "thisfile" path link)))
10376 (throw 'match t)))
10378 (when (get-text-property (point) 'org-linked-text)
10379 (setq type "thisfile"
10380 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10381 (1+ (point)) (point))
10382 path (buffer-substring
10383 (or (previous-single-property-change pos 'org-linked-text)
10384 (point-min))
10385 (or (next-single-property-change pos 'org-linked-text)
10386 (point-max)))
10387 ;; Ensure we will search for a <<<radio>>> link, not
10388 ;; a simple reference like <<ref>>
10389 path (concat "<" path))
10390 (throw 'match t))
10392 (save-excursion
10393 (when (or (org-in-regexp org-angle-link-re)
10394 (let ((match (org-in-regexp org-plain-link-re)))
10395 ;; Check a plain link is not within a bracket link
10396 (and match
10397 (save-excursion
10398 (save-match-data
10399 (progn
10400 (goto-char (car match))
10401 (not (org-in-regexp org-bracket-link-regexp)))))))
10402 (let ((line_ending (save-excursion (end-of-line) (point))))
10403 ;; We are in a line before a plain or bracket link
10404 (or (re-search-forward org-plain-link-re line_ending t)
10405 (re-search-forward org-bracket-link-regexp line_ending t))))
10406 (setq type (match-string 1)
10407 path (org-link-unescape (match-string 2)))
10408 (throw 'match t)))
10409 (save-excursion
10410 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10411 (setq type "tags"
10412 path (match-string 1))
10413 (while (string-match ":" path)
10414 (setq path (replace-match "+" t t path)))
10415 (throw 'match t)))
10416 (when (org-in-regexp "<\\([^><\n]+\\)>")
10417 (setq type "tree-match"
10418 path (match-string 1))
10419 (throw 'match t)))
10420 (unless path
10421 (user-error "No link found"))
10423 ;; switch back to reference buffer
10424 ;; needed when if called in a temporary buffer through
10425 ;; org-open-link-from-string
10426 (with-current-buffer (or reference-buffer (current-buffer))
10428 ;; Remove any trailing spaces in path
10429 (if (string-match " +\\'" path)
10430 (setq path (replace-match "" t t path)))
10431 (if (and org-link-translation-function
10432 (fboundp org-link-translation-function))
10433 ;; Check if we need to translate the link
10434 (let ((tmp (funcall org-link-translation-function type path)))
10435 (setq type (car tmp) path (cdr tmp))))
10437 (cond
10439 ((assoc type org-link-protocols)
10440 (funcall (nth 1 (assoc type org-link-protocols)) path))
10442 ((equal type "help")
10443 (let ((f-or-v (intern path)))
10444 (cond ((fboundp f-or-v)
10445 (describe-function f-or-v))
10446 ((boundp f-or-v)
10447 (describe-variable f-or-v))
10448 (t (error "Not a known function or variable")))))
10450 ((equal type "mailto")
10451 (let ((cmd (car org-link-mailto-program))
10452 (args (cdr org-link-mailto-program)) args1
10453 (address path) (subject "") a)
10454 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10455 (setq address (match-string 1 path)
10456 subject (org-link-escape (match-string 2 path))))
10457 (while args
10458 (cond
10459 ((not (stringp (car args))) (push (pop args) args1))
10460 (t (setq a (pop args))
10461 (if (string-match "%a" a)
10462 (setq a (replace-match address t t a)))
10463 (if (string-match "%s" a)
10464 (setq a (replace-match subject t t a)))
10465 (push a args1))))
10466 (apply cmd (nreverse args1))))
10468 ((member type '("http" "https" "ftp" "news"))
10469 (browse-url
10470 (concat type ":"
10471 (if (org-string-match-p
10472 (concat "[[:nonascii:]"
10473 org-link-escape-chars-browser "]")
10474 path)
10475 (org-link-escape path org-link-escape-chars-browser)
10476 path))))
10478 ((string= type "doi")
10479 (browse-url
10480 (concat org-doi-server-url
10481 (if (org-string-match-p
10482 (concat "[[:nonascii:]"
10483 org-link-escape-chars-browser "]")
10484 path)
10485 (org-link-escape path org-link-escape-chars-browser)
10486 path))))
10488 ((member type '("message"))
10489 (browse-url (concat type ":" path)))
10491 ((string= type "tags")
10492 (org-tags-view arg path))
10494 ((string= type "tree-match")
10495 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10497 ((string= type "file")
10498 (if (string-match "::\\([0-9]+\\)\\'" path)
10499 (setq line (string-to-number (match-string 1 path))
10500 path (substring path 0 (match-beginning 0)))
10501 (if (string-match "::\\(.+\\)\\'" path)
10502 (setq search (match-string 1 path)
10503 path (substring path 0 (match-beginning 0)))))
10504 (if (string-match "[*?{]" (file-name-nondirectory path))
10505 (dired path)
10506 (org-open-file path arg line search)))
10508 ((string= type "shell")
10509 (let ((buf (generate-new-buffer "*Org Shell Output"))
10510 (cmd path))
10511 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10512 (string-match org-confirm-shell-link-not-regexp cmd))
10513 (not org-confirm-shell-link-function)
10514 (funcall org-confirm-shell-link-function
10515 (format "Execute \"%s\" in shell? "
10516 (org-add-props cmd nil
10517 'face 'org-warning))))
10518 (progn
10519 (message "Executing %s" cmd)
10520 (shell-command cmd buf)
10521 (if (featurep 'midnight)
10522 (setq clean-buffer-list-kill-buffer-names
10523 (cons buf clean-buffer-list-kill-buffer-names))))
10524 (error "Abort"))))
10526 ((string= type "elisp")
10527 (let ((cmd path))
10528 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10529 (string-match org-confirm-elisp-link-not-regexp cmd))
10530 (not org-confirm-elisp-link-function)
10531 (funcall org-confirm-elisp-link-function
10532 (format "Execute \"%s\" as elisp? "
10533 (org-add-props cmd nil
10534 'face 'org-warning))))
10535 (message "%s => %s" cmd
10536 (if (equal (string-to-char cmd) ?\()
10537 (eval (read cmd))
10538 (call-interactively (read cmd))))
10539 (error "Abort"))))
10541 ((and (string= type "thisfile")
10542 (or (run-hook-with-args-until-success
10543 'org-open-link-functions path)
10544 (and link
10545 (string-match "^id:" link)
10546 (or (featurep 'org-id) (require 'org-id))
10547 (progn
10548 (funcall (nth 1 (assoc "id" org-link-protocols))
10549 (substring path 3))
10550 t)))))
10552 ((string= type "thisfile")
10553 (if arg
10554 (switch-to-buffer-other-window
10555 (org-get-buffer-for-internal-link (current-buffer)))
10556 (org-mark-ring-push))
10557 (let ((cmd `(org-link-search
10558 ,path
10559 ,(cond ((equal arg '(4)) ''occur)
10560 ((equal arg '(16)) ''org-occur))
10561 ,pos)))
10562 (condition-case nil (let ((org-link-search-inhibit-query t))
10563 (eval cmd))
10564 (error (progn (widen) (eval cmd))))))
10566 (t (browse-url-at-point)))))))
10567 (move-marker org-open-link-marker nil)
10568 (run-hook-with-args 'org-follow-link-hook)))
10570 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10571 "Offer links in the current entry and return the selected link.
10572 If there is only one link, return it.
10573 If NTH is an integer, return the NTH link found.
10574 If ZERO is a string, check also this string for a link, and if
10575 there is one, return it."
10576 (with-current-buffer buffer
10577 (save-excursion
10578 (save-restriction
10579 (widen)
10580 (goto-char marker)
10581 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10582 "\\(" org-angle-link-re "\\)\\|"
10583 "\\(" org-plain-link-re "\\)"))
10584 (cnt ?0)
10585 (in-emacs (if (integerp nth) nil nth))
10586 have-zero end links link c)
10587 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10588 (push (match-string 0 zero) links)
10589 (setq cnt (1- cnt) have-zero t))
10590 (save-excursion
10591 (org-back-to-heading t)
10592 (setq end (save-excursion (outline-next-heading) (point)))
10593 (while (re-search-forward re end t)
10594 (push (match-string 0) links))
10595 (setq links (org-uniquify (reverse links))))
10596 (cond
10597 ((null links)
10598 (message "No links"))
10599 ((equal (length links) 1)
10600 (setq link (car links)))
10601 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10602 (setq link (nth (if have-zero nth (1- nth)) links)))
10603 (t ; we have to select a link
10604 (save-excursion
10605 (save-window-excursion
10606 (delete-other-windows)
10607 (with-output-to-temp-buffer "*Select Link*"
10608 (mapc (lambda (l)
10609 (if (not (string-match org-bracket-link-regexp l))
10610 (princ (format "[%c] %s\n" (incf cnt)
10611 (org-remove-angle-brackets l)))
10612 (if (match-end 3)
10613 (princ (format "[%c] %s (%s)\n" (incf cnt)
10614 (match-string 3 l) (match-string 1 l)))
10615 (princ (format "[%c] %s\n" (incf cnt)
10616 (match-string 1 l))))))
10617 links))
10618 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10619 (message "Select link to open, RET to open all:")
10620 (setq c (read-char-exclusive))
10621 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10622 (when (equal c ?q) (error "Abort"))
10623 (if (equal c ?\C-m)
10624 (setq link links)
10625 (setq nth (- c ?0))
10626 (if have-zero (setq nth (1+ nth)))
10627 (unless (and (integerp nth) (>= (length links) nth))
10628 (user-error "Invalid link selection"))
10629 (setq link (nth (1- nth) links)))))
10630 (cons link end))))))
10632 ;; Add special file links that specify the way of opening
10634 (org-add-link-type "file+sys" 'org-open-file-with-system)
10635 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10636 (defun org-open-file-with-system (path)
10637 "Open file at PATH using the system way of opening it."
10638 (org-open-file path 'system))
10639 (defun org-open-file-with-emacs (path)
10640 "Open file at PATH in Emacs."
10641 (org-open-file path 'emacs))
10644 ;;; File search
10646 (defvar org-create-file-search-functions nil
10647 "List of functions to construct the right search string for a file link.
10648 These functions are called in turn with point at the location to
10649 which the link should point.
10651 A function in the hook should first test if it would like to
10652 handle this file type, for example by checking the `major-mode'
10653 or the file extension. If it decides not to handle this file, it
10654 should just return nil to give other functions a chance. If it
10655 does handle the file, it must return the search string to be used
10656 when following the link. The search string will be part of the
10657 file link, given after a double colon, and `org-open-at-point'
10658 will automatically search for it. If special measures must be
10659 taken to make the search successful, another function should be
10660 added to the companion hook `org-execute-file-search-functions',
10661 which see.
10663 A function in this hook may also use `setq' to set the variable
10664 `description' to provide a suggestion for the descriptive text to
10665 be used for this link when it gets inserted into an Org-mode
10666 buffer with \\[org-insert-link].")
10668 (defvar org-execute-file-search-functions nil
10669 "List of functions to execute a file search triggered by a link.
10671 Functions added to this hook must accept a single argument, the
10672 search string that was part of the file link, the part after the
10673 double colon. The function must first check if it would like to
10674 handle this search, for example by checking the `major-mode' or
10675 the file extension. If it decides not to handle this search, it
10676 should just return nil to give other functions a chance. If it
10677 does handle the search, it must return a non-nil value to keep
10678 other functions from trying.
10680 Each function can access the current prefix argument through the
10681 variable `current-prefix-arg'. Note that a single prefix is used
10682 to force opening a link in Emacs, so it may be good to only use a
10683 numeric or double prefix to guide the search function.
10685 In case this is needed, a function in this hook can also restore
10686 the window configuration before `org-open-at-point' was called using:
10688 (set-window-configuration org-window-config-before-follow-link)")
10690 (defun org-link-search (s &optional type avoid-pos stealth)
10691 "Search for a link search option.
10692 If S is surrounded by forward slashes, it is interpreted as a
10693 regular expression. In org-mode files, this will create an `org-occur'
10694 sparse tree. In ordinary files, `occur' will be used to list matches.
10695 If the current buffer is in `dired-mode', grep will be used to search
10696 in all files. If AVOID-POS is given, ignore matches near that position.
10698 When optional argument STEALTH is non-nil, do not modify
10699 visibility around point, thus ignoring
10700 `org-show-hierarchy-above', `org-show-following-heading' and
10701 `org-show-siblings' variables."
10702 (let ((case-fold-search t)
10703 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10704 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10705 (append '(("") (" ") ("\t") ("\n"))
10706 org-emphasis-alist)
10707 "\\|") "\\)"))
10708 (pos (point))
10709 (pre nil) (post nil)
10710 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10711 (cond
10712 ;; First check if there are any special search functions
10713 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10714 ;; Now try the builtin stuff
10715 ((and (equal (string-to-char s0) ?#)
10716 (> (length s0) 1)
10717 (save-excursion
10718 (goto-char (point-min))
10719 (and
10720 (re-search-forward
10721 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10722 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10723 (setq type 'dedicated
10724 pos (match-beginning 0))))
10725 ;; There is an exact target for this
10726 (goto-char pos)
10727 (org-back-to-heading t)))
10728 ((save-excursion
10729 (goto-char (point-min))
10730 (and
10731 (re-search-forward
10732 (concat "<<" (regexp-quote s0) ">>") nil t)
10733 (setq type 'dedicated
10734 pos (match-beginning 0))))
10735 ;; There is an exact target for this
10736 (goto-char pos))
10737 ((save-excursion
10738 (goto-char (point-min))
10739 (and
10740 (re-search-forward
10741 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10742 (setq type 'dedicated pos (match-beginning 0))))
10743 ;; Found an element with a matching #+name affiliated keyword.
10744 (goto-char pos))
10745 ((and (string-match "^(\\(.*\\))$" s0)
10746 (save-excursion
10747 (goto-char (point-min))
10748 (and
10749 (re-search-forward
10750 (concat "[^[]" (regexp-quote
10751 (format org-coderef-label-format
10752 (match-string 1 s0))))
10753 nil t)
10754 (setq type 'dedicated
10755 pos (1+ (match-beginning 0))))))
10756 ;; There is a coderef target for this
10757 (goto-char pos))
10758 ((string-match "^/\\(.*\\)/$" s)
10759 ;; A regular expression
10760 (cond
10761 ((derived-mode-p 'org-mode)
10762 (org-occur (match-string 1 s)))
10763 (t (org-do-occur (match-string 1 s)))))
10764 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10765 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10766 (goto-char (point-min))
10767 (cond
10768 ((let (case-fold-search)
10769 (re-search-forward (format org-complex-heading-regexp-format
10770 (regexp-quote s))
10771 nil t))
10772 ;; OK, found a match
10773 (setq type 'dedicated)
10774 (goto-char (match-beginning 0)))
10775 ((and (not org-link-search-inhibit-query)
10776 (eq org-link-search-must-match-exact-headline 'query-to-create)
10777 (y-or-n-p "No match - create this as a new heading? "))
10778 (goto-char (point-max))
10779 (or (bolp) (newline))
10780 (insert "* " s "\n")
10781 (beginning-of-line 0))
10783 (goto-char pos)
10784 (error "No match"))))
10786 ;; A normal search string
10787 (when (equal (string-to-char s) ?*)
10788 ;; Anchor on headlines, post may include tags.
10789 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10790 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10791 s (substring s 1)))
10792 (remove-text-properties
10793 0 (length s)
10794 '(face nil mouse-face nil keymap nil fontified nil) s)
10795 ;; Make a series of regular expressions to find a match
10796 (setq words (org-split-string s "[ \n\r\t]+")
10798 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10799 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10800 "\\)" markers)
10801 re2a_ (concat "\\(" (mapconcat 'downcase words
10802 "[ \t\r\n]+") "\\)[ \t\r\n]")
10803 re2a (concat "[ \t\r\n]" re2a_)
10804 re4_ (concat "\\(" (mapconcat 'downcase words
10805 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10806 re4 (concat "[^a-zA-Z_]" re4_)
10808 re1 (concat pre re2 post)
10809 re3 (concat pre (if pre re4_ re4) post)
10810 re5 (concat pre ".*" re4)
10811 re2 (concat pre re2)
10812 re2a (concat pre (if pre re2a_ re2a))
10813 re4 (concat pre (if pre re4_ re4))
10814 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10815 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10816 re5 "\\)"))
10817 (cond
10818 ((eq type 'org-occur) (org-occur reall))
10819 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10820 (t (goto-char (point-min))
10821 (setq type 'fuzzy)
10822 (if (or (and (org-search-not-self 1 re0 nil t)
10823 (setq type 'dedicated))
10824 (org-search-not-self 1 re1 nil t)
10825 (org-search-not-self 1 re2 nil t)
10826 (org-search-not-self 1 re2a nil t)
10827 (org-search-not-self 1 re3 nil t)
10828 (org-search-not-self 1 re4 nil t)
10829 (org-search-not-self 1 re5 nil t))
10830 (goto-char (match-beginning 1))
10831 (goto-char pos)
10832 (error "No match"))))))
10833 (and (derived-mode-p 'org-mode)
10834 (not stealth)
10835 (org-show-context 'link-search))
10836 type))
10838 (defun org-search-not-self (group &rest args)
10839 "Execute `re-search-forward', but only accept matches that do not
10840 enclose the position of `org-open-link-marker'."
10841 (let ((m org-open-link-marker))
10842 (catch 'exit
10843 (while (apply 're-search-forward args)
10844 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10845 (goto-char (match-end group))
10846 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10847 (> (match-beginning 0) (marker-position m))
10848 (< (match-end 0) (marker-position m)))
10849 (save-match-data
10850 (or (not (org-in-regexp
10851 org-bracket-link-analytic-regexp 1))
10852 (not (match-end 4)) ; no description
10853 (and (<= (match-beginning 4) (point))
10854 (>= (match-end 4) (point))))))
10855 (throw 'exit (point))))))))
10857 (defun org-get-buffer-for-internal-link (buffer)
10858 "Return a buffer to be used for displaying the link target of internal links."
10859 (cond
10860 ((not org-display-internal-link-with-indirect-buffer)
10861 buffer)
10862 ((string-match "(Clone)$" (buffer-name buffer))
10863 (message "Buffer is already a clone, not making another one")
10864 ;; we also do not modify visibility in this case
10865 buffer)
10866 (t ; make a new indirect buffer for displaying the link
10867 (let* ((bn (buffer-name buffer))
10868 (ibn (concat bn "(Clone)"))
10869 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10870 (with-current-buffer ib (org-overview))
10871 ib))))
10873 (defun org-do-occur (regexp &optional cleanup)
10874 "Call the Emacs command `occur'.
10875 If CLEANUP is non-nil, remove the printout of the regular expression
10876 in the *Occur* buffer. This is useful if the regex is long and not useful
10877 to read."
10878 (occur regexp)
10879 (when cleanup
10880 (let ((cwin (selected-window)) win beg end)
10881 (when (setq win (get-buffer-window "*Occur*"))
10882 (select-window win))
10883 (goto-char (point-min))
10884 (when (re-search-forward "match[a-z]+" nil t)
10885 (setq beg (match-end 0))
10886 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10887 (setq end (1- (match-beginning 0)))))
10888 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10889 (goto-char (point-min))
10890 (select-window cwin))))
10892 ;;; The mark ring for links jumps
10894 (defvar org-mark-ring nil
10895 "Mark ring for positions before jumps in Org-mode.")
10896 (defvar org-mark-ring-last-goto nil
10897 "Last position in the mark ring used to go back.")
10898 ;; Fill and close the ring
10899 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10900 (loop for i from 1 to org-mark-ring-length do
10901 (push (make-marker) org-mark-ring))
10902 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10903 org-mark-ring)
10905 (defun org-mark-ring-push (&optional pos buffer)
10906 "Put the current position or POS into the mark ring and rotate it."
10907 (interactive)
10908 (setq pos (or pos (point)))
10909 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10910 (move-marker (car org-mark-ring)
10911 (or pos (point))
10912 (or buffer (current-buffer)))
10913 (message "%s"
10914 (substitute-command-keys
10915 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10917 (defun org-mark-ring-goto (&optional n)
10918 "Jump to the previous position in the mark ring.
10919 With prefix arg N, jump back that many stored positions. When
10920 called several times in succession, walk through the entire ring.
10921 Org-mode commands jumping to a different position in the current file,
10922 or to another Org-mode file, automatically push the old position
10923 onto the ring."
10924 (interactive "p")
10925 (let (p m)
10926 (if (eq last-command this-command)
10927 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10928 (setq p org-mark-ring))
10929 (setq org-mark-ring-last-goto p)
10930 (setq m (car p))
10931 (org-pop-to-buffer-same-window (marker-buffer m))
10932 (goto-char m)
10933 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10935 (defun org-remove-angle-brackets (s)
10936 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10937 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10939 (defun org-add-angle-brackets (s)
10940 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10941 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10943 (defun org-remove-double-quotes (s)
10944 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10945 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10948 ;;; Following specific links
10950 (defun org-follow-timestamp-link ()
10951 "Open an agenda view for the time-stamp date/range at point."
10952 (cond
10953 ((org-at-date-range-p t)
10954 (let ((org-agenda-start-on-weekday)
10955 (t1 (match-string 1))
10956 (t2 (match-string 2)) tt1 tt2)
10957 (setq tt1 (time-to-days (org-time-string-to-time t1))
10958 tt2 (time-to-days (org-time-string-to-time t2)))
10959 (let ((org-agenda-buffer-tmp-name
10960 (format "*Org Agenda(a:%s)"
10961 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10962 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10963 ((org-at-timestamp-p t)
10964 (let ((org-agenda-buffer-tmp-name
10965 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10966 (org-agenda-list nil (time-to-days (org-time-string-to-time
10967 (substring (match-string 1) 0 10)))
10968 1)))
10969 (t (error "This should not happen"))))
10972 ;;; Following file links
10973 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10974 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10975 (declare-function mailcap-mime-info
10976 "mailcap" (string &optional request no-decode))
10977 (defvar org-wait nil)
10978 (defun org-open-file (path &optional in-emacs line search)
10979 "Open the file at PATH.
10980 First, this expands any special file name abbreviations. Then the
10981 configuration variable `org-file-apps' is checked if it contains an
10982 entry for this file type, and if yes, the corresponding command is launched.
10984 If no application is found, Emacs simply visits the file.
10986 With optional prefix argument IN-EMACS, Emacs will visit the file.
10987 With a double \\[universal-argument] \\[universal-argument] \
10988 prefix arg, Org tries to avoid opening in Emacs
10989 and to use an external application to visit the file.
10991 Optional LINE specifies a line to go to, optional SEARCH a string
10992 to search for. If LINE or SEARCH is given, the file will be
10993 opened in Emacs, unless an entry from org-file-apps that makes
10994 use of groups in a regexp matches.
10996 If you want to change the way frames are used when following a
10997 link, please customize `org-link-frame-setup'.
10999 If the file does not exist, an error is thrown."
11000 (let* ((file (if (equal path "")
11001 buffer-file-name
11002 (substitute-in-file-name (expand-file-name path))))
11003 (file-apps (append org-file-apps (org-default-apps)))
11004 (apps (org-remove-if
11005 'org-file-apps-entry-match-against-dlink-p file-apps))
11006 (apps-dlink (org-remove-if-not
11007 'org-file-apps-entry-match-against-dlink-p file-apps))
11008 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11009 (dirp (if remp nil (file-directory-p file)))
11010 (file (if (and dirp org-open-directory-means-index-dot-org)
11011 (concat (file-name-as-directory file) "index.org")
11012 file))
11013 (a-m-a-p (assq 'auto-mode apps))
11014 (dfile (downcase file))
11015 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
11016 (link (cond ((and (eq line nil)
11017 (eq search nil))
11018 file)
11019 (line
11020 (concat file "::" (number-to-string line)))
11021 (search
11022 (concat file "::" search))))
11023 (dlink (downcase link))
11024 (old-buffer (current-buffer))
11025 (old-pos (point))
11026 (old-mode major-mode)
11027 ext cmd link-match-data)
11028 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11029 (setq ext (match-string 1 dfile))
11030 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11031 (setq ext (match-string 1 dfile))))
11032 (cond
11033 ((member in-emacs '((16) system))
11034 (setq cmd (cdr (assoc 'system apps))))
11035 (in-emacs (setq cmd 'emacs))
11037 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11038 (and dirp (cdr (assoc 'directory apps)))
11039 ; first, try matching against apps-dlink
11040 ; if we get a match here, store the match data for later
11041 (let ((match (assoc-default dlink apps-dlink
11042 'string-match)))
11043 (if match
11044 (progn (setq link-match-data (match-data))
11045 match)
11046 (progn (setq in-emacs (or in-emacs line search))
11047 nil))) ; if we have no match in apps-dlink,
11048 ; always open the file in emacs if line or search
11049 ; is given (for backwards compatibility)
11050 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11051 'string-match)
11052 (cdr (assoc ext apps))
11053 (cdr (assoc t apps))))))
11054 (when (eq cmd 'system)
11055 (setq cmd (cdr (assoc 'system apps))))
11056 (when (eq cmd 'default)
11057 (setq cmd (cdr (assoc t apps))))
11058 (when (eq cmd 'mailcap)
11059 (require 'mailcap)
11060 (mailcap-parse-mailcaps)
11061 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11062 (command (mailcap-mime-info mime-type)))
11063 (if (stringp command)
11064 (setq cmd command)
11065 (setq cmd 'emacs))))
11066 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11067 (not (file-exists-p file))
11068 (not org-open-non-existing-files))
11069 (user-error "No such file: %s" file))
11070 (cond
11071 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11072 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11073 (while (string-match "['\"]%s['\"]" cmd)
11074 (setq cmd (replace-match "%s" t t cmd)))
11075 (while (string-match "%s" cmd)
11076 (setq cmd (replace-match
11077 (save-match-data
11078 (shell-quote-argument
11079 (convert-standard-filename file)))
11080 t t cmd)))
11082 ;; Replace "%1", "%2" etc. in command with group matches from regex
11083 (save-match-data
11084 (let ((match-index 1)
11085 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11086 (set-match-data link-match-data)
11087 (while (<= match-index number-of-groups)
11088 (let ((regex (concat "%" (number-to-string match-index)))
11089 (replace-with (match-string match-index dlink)))
11090 (while (string-match regex cmd)
11091 (setq cmd (replace-match replace-with t t cmd))))
11092 (setq match-index (+ match-index 1)))))
11094 (save-window-excursion
11095 (message "Running %s...done" cmd)
11096 (start-process-shell-command cmd nil cmd)
11097 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11098 ((or (stringp cmd)
11099 (eq cmd 'emacs))
11100 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11101 (widen)
11102 (if line (org-goto-line line)
11103 (if search (org-link-search search))))
11104 ((consp cmd)
11105 (let ((file (convert-standard-filename file)))
11106 (save-match-data
11107 (set-match-data link-match-data)
11108 (eval cmd))))
11109 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11110 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11111 (or (not (equal old-buffer (current-buffer)))
11112 (not (equal old-pos (point))))
11113 (org-mark-ring-push old-pos old-buffer))))
11115 (defun org-file-apps-entry-match-against-dlink-p (entry)
11116 "This function returns non-nil if `entry' uses a regular
11117 expression which should be matched against the whole link by
11118 org-open-file.
11120 It assumes that is the case when the entry uses a regular
11121 expression which has at least one grouping construct and the
11122 action is either a lisp form or a command string containing
11123 '%1', i.e. using at least one subexpression match as a
11124 parameter."
11125 (let ((selector (car entry))
11126 (action (cdr entry)))
11127 (if (stringp selector)
11128 (and (> (regexp-opt-depth selector) 0)
11129 (or (and (stringp action)
11130 (string-match "%[0-9]" action))
11131 (consp action)))
11132 nil)))
11134 (defun org-default-apps ()
11135 "Return the default applications for this operating system."
11136 (cond
11137 ((eq system-type 'darwin)
11138 org-file-apps-defaults-macosx)
11139 ((eq system-type 'windows-nt)
11140 org-file-apps-defaults-windowsnt)
11141 (t org-file-apps-defaults-gnu)))
11143 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11144 "Convert extensions to regular expressions in the cars of LIST.
11145 Also, weed out any non-string entries, because the return value is used
11146 only for regexp matching.
11147 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11148 point to the symbol `emacs', indicating that the file should
11149 be opened in Emacs."
11150 (append
11151 (delq nil
11152 (mapcar (lambda (x)
11153 (if (not (stringp (car x)))
11155 (if (string-match "\\W" (car x))
11157 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11158 list))
11159 (if add-auto-mode
11160 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11162 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11163 (defun org-file-remote-p (file)
11164 "Test whether FILE specifies a location on a remote system.
11165 Return non-nil if the location is indeed remote.
11167 For example, the filename \"/user@host:/foo\" specifies a location
11168 on the system \"/user@host:\"."
11169 (cond ((fboundp 'file-remote-p)
11170 (file-remote-p file))
11171 ((fboundp 'tramp-handle-file-remote-p)
11172 (tramp-handle-file-remote-p file))
11173 ((and (boundp 'ange-ftp-name-format)
11174 (string-match (car ange-ftp-name-format) file))
11175 t)))
11178 ;;;; Refiling
11180 (defun org-get-org-file ()
11181 "Read a filename, with default directory `org-directory'."
11182 (let ((default (or org-default-notes-file remember-data-file)))
11183 (read-file-name (format "File name [%s]: " default)
11184 (file-name-as-directory org-directory)
11185 default)))
11187 (defun org-notes-order-reversed-p ()
11188 "Check if the current file should receive notes in reversed order."
11189 (cond
11190 ((not org-reverse-note-order) nil)
11191 ((eq t org-reverse-note-order) t)
11192 ((not (listp org-reverse-note-order)) nil)
11193 (t (catch 'exit
11194 (let ((all org-reverse-note-order)
11195 entry)
11196 (while (setq entry (pop all))
11197 (if (string-match (car entry) buffer-file-name)
11198 (throw 'exit (cdr entry))))
11199 nil)))))
11201 (defvar org-refile-target-table nil
11202 "The list of refile targets, created by `org-refile'.")
11204 (defvar org-agenda-new-buffers nil
11205 "Buffers created to visit agenda files.")
11207 (defvar org-refile-cache nil
11208 "Cache for refile targets.")
11210 (defvar org-refile-markers nil
11211 "All the markers used for caching refile locations.")
11213 (defun org-refile-marker (pos)
11214 "Get a new refile marker, but only if caching is in use."
11215 (if (not org-refile-use-cache)
11217 (let ((m (make-marker)))
11218 (move-marker m pos)
11219 (push m org-refile-markers)
11220 m)))
11222 (defun org-refile-cache-clear ()
11223 "Clear the refile cache and disable all the markers."
11224 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11225 (setq org-refile-markers nil)
11226 (setq org-refile-cache nil)
11227 (message "Refile cache has been cleared"))
11229 (defun org-refile-cache-check-set (set)
11230 "Check if all the markers in the cache still have live buffers."
11231 (let (marker)
11232 (catch 'exit
11233 (while (and set (setq marker (nth 3 (pop set))))
11234 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11235 (when (and marker (null (marker-buffer marker)))
11236 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11237 (sit-for 3)
11238 (throw 'exit nil)))
11239 t)))
11241 (defun org-refile-cache-put (set &rest identifiers)
11242 "Push the refile targets SET into the cache, under IDENTIFIERS."
11243 (let* ((key (sha1 (prin1-to-string identifiers)))
11244 (entry (assoc key org-refile-cache)))
11245 (if entry
11246 (setcdr entry set)
11247 (push (cons key set) org-refile-cache))))
11249 (defun org-refile-cache-get (&rest identifiers)
11250 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11251 (cond
11252 ((not org-refile-cache) nil)
11253 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11255 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11256 org-refile-cache))))
11257 (and set (org-refile-cache-check-set set) set)))))
11259 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11260 "Produce a table with refile targets."
11261 (let ((case-fold-search nil)
11262 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11263 (entries (or org-refile-targets '((nil . (:level . 1)))))
11264 targets tgs txt re files f desc descre fast-path-p level pos0)
11265 (message "Getting targets...")
11266 (with-current-buffer (or default-buffer (current-buffer))
11267 (while (setq entry (pop entries))
11268 (setq files (car entry) desc (cdr entry))
11269 (setq fast-path-p nil)
11270 (cond
11271 ((null files) (setq files (list (current-buffer))))
11272 ((eq files 'org-agenda-files)
11273 (setq files (org-agenda-files 'unrestricted)))
11274 ((and (symbolp files) (fboundp files))
11275 (setq files (funcall files)))
11276 ((and (symbolp files) (boundp files))
11277 (setq files (symbol-value files))))
11278 (if (stringp files) (setq files (list files)))
11279 (cond
11280 ((eq (car desc) :tag)
11281 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11282 ((eq (car desc) :todo)
11283 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11284 ((eq (car desc) :regexp)
11285 (setq descre (cdr desc)))
11286 ((eq (car desc) :level)
11287 (setq descre (concat "^\\*\\{" (number-to-string
11288 (if org-odd-levels-only
11289 (1- (* 2 (cdr desc)))
11290 (cdr desc)))
11291 "\\}[ \t]")))
11292 ((eq (car desc) :maxlevel)
11293 (setq fast-path-p t)
11294 (setq descre (concat "^\\*\\{1," (number-to-string
11295 (if org-odd-levels-only
11296 (1- (* 2 (cdr desc)))
11297 (cdr desc)))
11298 "\\}[ \t]")))
11299 (t (error "Bad refiling target description %s" desc)))
11300 (while (setq f (pop files))
11301 (with-current-buffer
11302 (if (bufferp f) f (org-get-agenda-file-buffer f))
11304 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11305 (progn
11306 (if (bufferp f) (setq f (buffer-file-name
11307 (buffer-base-buffer f))))
11308 (setq f (and f (expand-file-name f)))
11309 (if (eq org-refile-use-outline-path 'file)
11310 (push (list (file-name-nondirectory f) f nil nil) tgs))
11311 (save-excursion
11312 (save-restriction
11313 (widen)
11314 (goto-char (point-min))
11315 (while (re-search-forward descre nil t)
11316 (goto-char (setq pos0 (point-at-bol)))
11317 (catch 'next
11318 (when org-refile-target-verify-function
11319 (save-match-data
11320 (or (funcall org-refile-target-verify-function)
11321 (throw 'next t))))
11322 (when (and (looking-at org-complex-heading-regexp)
11323 (not (member (match-string 4) excluded-entries))
11324 (match-string 4))
11325 (setq level (org-reduced-level
11326 (- (match-end 1) (match-beginning 1)))
11327 txt (org-link-display-format (match-string 4))
11328 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11329 re (format org-complex-heading-regexp-format
11330 (regexp-quote (match-string 4))))
11331 (when org-refile-use-outline-path
11332 (setq txt (mapconcat
11333 'org-protect-slash
11334 (append
11335 (if (eq org-refile-use-outline-path
11336 'file)
11337 (list (file-name-nondirectory
11338 (buffer-file-name
11339 (buffer-base-buffer))))
11340 (if (eq org-refile-use-outline-path
11341 'full-file-path)
11342 (list (buffer-file-name
11343 (buffer-base-buffer)))))
11344 (org-get-outline-path fast-path-p
11345 level txt)
11346 (list txt))
11347 "/")))
11348 (push (list txt f re (org-refile-marker (point)))
11349 tgs)))
11350 (when (= (point) pos0)
11351 ;; verification function has not moved point
11352 (goto-char (point-at-eol))))))))
11353 (when org-refile-use-cache
11354 (org-refile-cache-put tgs (buffer-file-name) descre))
11355 (setq targets (append tgs targets))))))
11356 (message "Getting targets...done")
11357 (nreverse targets)))
11359 (defun org-protect-slash (s)
11360 (while (string-match "/" s)
11361 (setq s (replace-match "\\" t t s)))
11364 (defvar org-olpa (make-vector 20 nil))
11366 (defun org-get-outline-path (&optional fastp level heading)
11367 "Return the outline path to the current entry, as a list.
11369 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11370 routine which makes outline path derivations for an entire file,
11371 avoiding backtracing. Refile target collection makes use of that."
11372 (if fastp
11373 (progn
11374 (if (> level 19)
11375 (error "Outline path failure, more than 19 levels"))
11376 (loop for i from level upto 19 do
11377 (aset org-olpa i nil))
11378 (prog1
11379 (delq nil (append org-olpa nil))
11380 (aset org-olpa level heading)))
11381 (let (rtn case-fold-search)
11382 (save-excursion
11383 (save-restriction
11384 (widen)
11385 (while (org-up-heading-safe)
11386 (when (looking-at org-complex-heading-regexp)
11387 (push (org-trim
11388 (replace-regexp-in-string
11389 ;; Remove statistical/checkboxes cookies
11390 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11391 (org-match-string-no-properties 4)))
11392 rtn)))
11393 rtn)))))
11395 (defun org-format-outline-path (path &optional width prefix separator)
11396 "Format the outline path PATH for display.
11397 WIDTH is the maximum number of characters that is available.
11398 PREFIX is a prefix to be included in the returned string,
11399 such as the file name.
11400 SEPARATOR is inserted between the different parts of the path,
11401 the default is \"/\"."
11402 (setq width (or width 79))
11403 (if prefix (setq width (- width (length prefix))))
11404 (if (not path)
11405 (or prefix "")
11406 (let* ((nsteps (length path))
11407 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11408 (maxwidth (if (<= total-width width)
11409 10000 ;; everything fits
11410 ;; we need to shorten the level headings
11411 (/ (- width nsteps) nsteps)))
11412 (org-odd-levels-only nil)
11413 (n 0)
11414 (total (1+ (length prefix))))
11415 (setq maxwidth (max maxwidth 10))
11416 (concat prefix
11417 (if prefix (or separator "/"))
11418 (mapconcat
11419 (lambda (h)
11420 (setq n (1+ n))
11421 (if (and (= n nsteps) (< maxwidth 10000))
11422 (setq maxwidth (- total-width total)))
11423 (if (< (length h) maxwidth)
11424 (progn (setq total (+ total (length h) 1)) h)
11425 (setq h (substring h 0 (- maxwidth 2))
11426 total (+ total maxwidth 1))
11427 (if (string-match "[ \t]+\\'" h)
11428 (setq h (substring h 0 (match-beginning 0))))
11429 (setq h (concat h "..")))
11430 (org-add-props h nil 'face
11431 (nth (% (1- n) org-n-level-faces)
11432 org-level-faces))
11434 path (or separator "/"))))))
11436 (defun org-display-outline-path (&optional file current separator just-return-string)
11437 "Display the current outline path in the echo area.
11439 If FILE is non-nil, prepend the output with the file name.
11440 If CURRENT is non-nil, append the current heading to the output.
11441 SEPARATOR is passed through to `org-format-outline-path'. It separates
11442 the different parts of the path and defaults to \"/\".
11443 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11444 (interactive "P")
11445 (let* (case-fold-search
11446 (bfn (buffer-file-name (buffer-base-buffer)))
11447 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11448 res)
11449 (if current (setq path (append path
11450 (save-excursion
11451 (org-back-to-heading t)
11452 (if (looking-at org-complex-heading-regexp)
11453 (list (match-string 4)))))))
11454 (setq res
11455 (org-format-outline-path
11456 path
11457 (1- (frame-width))
11458 (and file bfn (concat (file-name-nondirectory bfn) separator))
11459 separator))
11460 (if just-return-string
11461 (org-no-properties res)
11462 (org-unlogged-message "%s" res))))
11464 (defvar org-refile-history nil
11465 "History for refiling operations.")
11467 (defvar org-after-refile-insert-hook nil
11468 "Hook run after `org-refile' has inserted its stuff at the new location.
11469 Note that this is still *before* the stuff will be removed from
11470 the *old* location.")
11472 (defvar org-capture-last-stored-marker)
11473 (defvar org-refile-keep nil
11474 "Non-nil means `org-refile' will copy instead of refile.")
11476 (defun org-copy ()
11477 "Like `org-refile', but copy."
11478 (interactive)
11479 (let ((org-refile-keep t))
11480 (funcall 'org-refile nil nil nil "Copy")))
11482 (defun org-refile (&optional goto default-buffer rfloc msg)
11483 "Move the entry or entries at point to another heading.
11484 The list of target headings is compiled using the information in
11485 `org-refile-targets', which see.
11487 At the target location, the entry is filed as a subitem of the target
11488 heading. Depending on `org-reverse-note-order', the new subitem will
11489 either be the first or the last subitem.
11491 If there is an active region, all entries in that region will be moved.
11492 However, the region must fulfill the requirement that the first heading
11493 is the first one sets the top-level of the moved text - at most siblings
11494 below it are allowed.
11496 With prefix arg GOTO, the command will only visit the target location
11497 and not actually move anything.
11499 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11500 go to the location where the last refiling operation has put the subtree.
11502 With a numeric prefix argument of `2', refile to the running clock.
11504 With a numeric prefix argument of `3', emulate `org-refile-keep'
11505 being set to `t' and copy to the target location, don't move it.
11506 Beware that keeping refiled entries may result in duplicated ID
11507 properties.
11509 RFLOC can be a refile location obtained in a different way.
11511 MSG is a string to replace \"Refile\" in the default prompt with
11512 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11514 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11516 If you are using target caching (see `org-refile-use-cache'),
11517 you have to clear the target cache in order to find new targets.
11518 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11519 prefix argument (`C-u C-u C-u C-c C-w')."
11521 (interactive "P")
11522 (if (member goto '(0 (64)))
11523 (org-refile-cache-clear)
11524 (let* ((actionmsg (cond (msg msg)
11525 ((equal goto 3) "Refile (and keep)")
11526 (t "Refile")))
11527 (cbuf (current-buffer))
11528 (regionp (org-region-active-p))
11529 (region-start (and regionp (region-beginning)))
11530 (region-end (and regionp (region-end)))
11531 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11532 (org-refile-keep (if (equal goto 3) t org-refile-keep))
11533 pos it nbuf file re level reversed)
11534 (setq last-command nil)
11535 (when regionp
11536 (goto-char region-start)
11537 (or (bolp) (goto-char (point-at-bol)))
11538 (setq region-start (point))
11539 (unless (or (org-kill-is-subtree-p
11540 (buffer-substring region-start region-end))
11541 (prog1 org-refile-active-region-within-subtree
11542 (let ((s (point-at-eol)))
11543 (org-toggle-heading)
11544 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11545 (user-error "The region is not a (sequence of) subtree(s)")))
11546 (if (equal goto '(16))
11547 (org-refile-goto-last-stored)
11548 (when (or
11549 (and (equal goto 2)
11550 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11551 (prog1
11552 (setq it (list (or org-clock-heading "running clock")
11553 (buffer-file-name
11554 (marker-buffer org-clock-hd-marker))
11556 (marker-position org-clock-hd-marker)))
11557 (setq goto nil)))
11558 (setq it (or rfloc
11559 (let (heading-text)
11560 (save-excursion
11561 (unless (and goto (listp goto))
11562 (org-back-to-heading t)
11563 (setq heading-text
11564 (nth 4 (org-heading-components))))
11566 (org-refile-get-location
11567 (cond ((and goto (listp goto)) "Goto")
11568 (regionp (concat actionmsg " region to"))
11569 (t (concat actionmsg " subtree \""
11570 heading-text "\" to")))
11571 default-buffer
11572 (and (not (equal '(4) goto))
11573 org-refile-allow-creating-parent-nodes)
11574 goto))))))
11575 (setq file (nth 1 it)
11576 re (nth 2 it)
11577 pos (nth 3 it))
11578 (if (and (not goto)
11580 (equal (buffer-file-name) file)
11581 (if regionp
11582 (and (>= pos region-start)
11583 (<= pos region-end))
11584 (and (>= pos (point))
11585 (< pos (save-excursion
11586 (org-end-of-subtree t t))))))
11587 (error "Cannot refile to position inside the tree or region"))
11589 (setq nbuf (or (find-buffer-visiting file)
11590 (find-file-noselect file)))
11591 (if (and goto (not (equal goto 3)))
11592 (progn
11593 (org-pop-to-buffer-same-window nbuf)
11594 (goto-char pos)
11595 (org-show-context 'org-goto))
11596 (if regionp
11597 (progn
11598 (org-kill-new (buffer-substring region-start region-end))
11599 (org-save-markers-in-region region-start region-end))
11600 (org-copy-subtree 1 nil t))
11601 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11602 (find-file-noselect file)))
11603 (setq reversed (org-notes-order-reversed-p))
11604 (save-excursion
11605 (save-restriction
11606 (widen)
11607 (if pos
11608 (progn
11609 (goto-char pos)
11610 (looking-at org-outline-regexp)
11611 (setq level (org-get-valid-level (funcall outline-level) 1))
11612 (goto-char
11613 (if reversed
11614 (or (outline-next-heading) (point-max))
11615 (or (save-excursion (org-get-next-sibling))
11616 (org-end-of-subtree t t)
11617 (point-max)))))
11618 (setq level 1)
11619 (if (not reversed)
11620 (goto-char (point-max))
11621 (goto-char (point-min))
11622 (or (outline-next-heading) (goto-char (point-max)))))
11623 (if (not (bolp)) (newline))
11624 (org-paste-subtree level)
11625 (when org-log-refile
11626 (org-add-log-setup 'refile nil nil 'findpos org-log-refile)
11627 (unless (eq org-log-refile 'note)
11628 (save-excursion (org-add-log-note))))
11629 (and org-auto-align-tags
11630 (let ((org-loop-over-headlines-in-active-region nil))
11631 (org-set-tags nil t)))
11632 (let ((bookmark-name (plist-get org-bookmark-names-plist
11633 :last-refile)))
11634 (when bookmark-name
11635 (with-demoted-errors
11636 (bookmark-set bookmark-name))))
11637 ;; If we are refiling for capture, make sure that the
11638 ;; last-capture pointers point here
11639 (when (org-bound-and-true-p org-refile-for-capture)
11640 (let ((bookmark-name (plist-get org-bookmark-names-plist
11641 :last-capture-marker)))
11642 (when bookmark-name
11643 (with-demoted-errors
11644 (bookmark-set bookmark-name))))
11645 (move-marker org-capture-last-stored-marker (point)))
11646 (if (fboundp 'deactivate-mark) (deactivate-mark))
11647 (run-hooks 'org-after-refile-insert-hook))))
11648 (unless org-refile-keep
11649 (if regionp
11650 (delete-region (point) (+ (point) (- region-end region-start)))
11651 (delete-region
11652 (and (org-back-to-heading t) (point))
11653 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11654 (when (featurep 'org-inlinetask)
11655 (org-inlinetask-remove-END-maybe))
11656 (setq org-markers-to-move nil)
11657 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11659 (defun org-refile-goto-last-stored ()
11660 "Go to the location where the last refile was stored."
11661 (interactive)
11662 (bookmark-jump "org-refile-last-stored")
11663 (message "This is the location of the last refile"))
11665 (defun org-refile--get-location (refloc tbl)
11666 "When user refile to REFLOC, find the associated target in TBL.
11667 Also check `org-refile-target-table'."
11668 (car (delq
11670 (mapcar
11671 (lambda (r) (or (assoc r tbl)
11672 (assoc r org-refile-target-table)))
11673 (list (replace-regexp-in-string "/$" "" refloc)
11674 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11676 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11677 no-exclude)
11678 "Prompt the user for a refile location, using PROMPT.
11679 PROMPT should not be suffixed with a colon and a space, because
11680 this function appends the default value from
11681 `org-refile-history' automatically, if that is not empty.
11682 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11683 this is used for the GOTO interface."
11684 (let ((org-refile-targets org-refile-targets)
11685 (org-refile-use-outline-path org-refile-use-outline-path)
11686 excluded-entries)
11687 (when (and (derived-mode-p 'org-mode)
11688 (not org-refile-use-cache)
11689 (not no-exclude))
11690 (org-map-tree
11691 (lambda()
11692 (setq excluded-entries
11693 (append excluded-entries (list (org-get-heading t t)))))))
11694 (setq org-refile-target-table
11695 (org-refile-get-targets default-buffer excluded-entries)))
11696 (unless org-refile-target-table
11697 (user-error "No refile targets"))
11698 (let* ((cbuf (current-buffer))
11699 (partial-completion-mode nil)
11700 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11701 (cfunc (if (and org-refile-use-outline-path
11702 org-outline-path-complete-in-steps)
11703 'org-olpath-completing-read
11704 'org-icompleting-read))
11705 (extra (if org-refile-use-outline-path "/" ""))
11706 (cbnex (concat (buffer-name) extra))
11707 (filename (and cfn (expand-file-name cfn)))
11708 (tbl (mapcar
11709 (lambda (x)
11710 (if (and (not (member org-refile-use-outline-path
11711 '(file full-file-path)))
11712 (not (equal filename (nth 1 x))))
11713 (cons (concat (car x) extra " ("
11714 (file-name-nondirectory (nth 1 x)) ")")
11715 (cdr x))
11716 (cons (concat (car x) extra) (cdr x))))
11717 org-refile-target-table))
11718 (completion-ignore-case t)
11719 cdef
11720 (prompt (concat prompt
11721 (or (and (car org-refile-history)
11722 (concat " (default " (car org-refile-history) ")"))
11723 (and (assoc cbnex tbl) (setq cdef cbnex)
11724 (concat " (default " cbnex ")"))) ": "))
11725 pa answ parent-target child parent old-hist)
11726 (setq old-hist org-refile-history)
11727 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11728 nil 'org-refile-history (or cdef (car org-refile-history))))
11729 (if (setq pa (org-refile--get-location answ tbl))
11730 (progn
11731 (org-refile-check-position pa)
11732 (when (or (not org-refile-history)
11733 (not (eq old-hist org-refile-history))
11734 (not (equal (car pa) (car org-refile-history))))
11735 (setq org-refile-history
11736 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11737 org-refile-history
11738 (cdr org-refile-history))))
11739 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11740 (pop org-refile-history)))
11742 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11743 (progn
11744 (setq parent (match-string 1 answ)
11745 child (match-string 2 answ))
11746 (setq parent-target (org-refile--get-location parent tbl))
11747 (when (and parent-target
11748 (or (eq new-nodes t)
11749 (and (eq new-nodes 'confirm)
11750 (y-or-n-p (format "Create new node \"%s\"? "
11751 child)))))
11752 (org-refile-new-child parent-target child)))
11753 (user-error "Invalid target location")))))
11755 (declare-function org-string-nw-p "org-macs" (s))
11756 (defun org-refile-check-position (refile-pointer)
11757 "Check if the refile pointer matches the headline to which it points."
11758 (let* ((file (nth 1 refile-pointer))
11759 (re (nth 2 refile-pointer))
11760 (pos (nth 3 refile-pointer))
11761 buffer)
11762 (if (and (not (markerp pos)) (not file))
11763 (user-error "Please save the buffer to a file before refiling")
11764 (when (org-string-nw-p re)
11765 (setq buffer (if (markerp pos)
11766 (marker-buffer pos)
11767 (or (find-buffer-visiting file)
11768 (find-file-noselect file))))
11769 (with-current-buffer buffer
11770 (save-excursion
11771 (save-restriction
11772 (widen)
11773 (goto-char pos)
11774 (beginning-of-line 1)
11775 (unless (org-looking-at-p re)
11776 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11778 (defun org-refile-new-child (parent-target child)
11779 "Use refile target PARENT-TARGET to add new CHILD below it."
11780 (unless parent-target
11781 (error "Cannot find parent for new node"))
11782 (let ((file (nth 1 parent-target))
11783 (pos (nth 3 parent-target))
11784 level)
11785 (with-current-buffer (or (find-buffer-visiting file)
11786 (find-file-noselect file))
11787 (save-excursion
11788 (save-restriction
11789 (widen)
11790 (if pos
11791 (goto-char pos)
11792 (goto-char (point-max))
11793 (if (not (bolp)) (newline)))
11794 (when (looking-at org-outline-regexp)
11795 (setq level (funcall outline-level))
11796 (org-end-of-subtree t t))
11797 (org-back-over-empty-lines)
11798 (insert "\n" (make-string
11799 (if pos (org-get-valid-level level 1) 1) ?*)
11800 " " child "\n")
11801 (beginning-of-line 0)
11802 (list (concat (car parent-target) "/" child) file "" (point)))))))
11804 (defun org-olpath-completing-read (prompt collection &rest args)
11805 "Read an outline path like a file name."
11806 (let ((thetable collection)
11807 (org-completion-use-ido nil) ; does not work with ido.
11808 (org-completion-use-iswitchb nil)) ; or iswitchb
11809 (apply
11810 'org-icompleting-read prompt
11811 (lambda (string predicate &optional flag)
11812 (let (rtn r f (l (length string)))
11813 (cond
11814 ((eq flag nil)
11815 ;; try completion
11816 (try-completion string thetable))
11817 ((eq flag t)
11818 ;; all-completions
11819 (setq rtn (all-completions string thetable predicate))
11820 (mapcar
11821 (lambda (x)
11822 (setq r (substring x l))
11823 (if (string-match " ([^)]*)$" x)
11824 (setq f (match-string 0 x))
11825 (setq f ""))
11826 (if (string-match "/" r)
11827 (concat string (substring r 0 (match-end 0)) f)
11829 rtn))
11830 ((eq flag 'lambda)
11831 ;; exact match?
11832 (assoc string thetable)))))
11833 args)))
11835 ;;;; Dynamic blocks
11837 (defun org-find-dblock (name)
11838 "Find the first dynamic block with name NAME in the buffer.
11839 If not found, stay at current position and return nil."
11840 (let ((case-fold-search t) pos)
11841 (save-excursion
11842 (goto-char (point-min))
11843 (setq pos (and (re-search-forward
11844 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11845 (match-beginning 0))))
11846 (if pos (goto-char pos))
11847 pos))
11849 (defconst org-dblock-start-re
11850 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11851 "Matches the start line of a dynamic block, with parameters.")
11853 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11854 "Matches the end of a dynamic block.")
11856 (defun org-create-dblock (plist)
11857 "Create a dynamic block section, with parameters taken from PLIST.
11858 PLIST must contain a :name entry which is used as name of the block."
11859 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11860 (end-of-line 1)
11861 (newline))
11862 (let ((col (current-column))
11863 (name (plist-get plist :name)))
11864 (insert "#+BEGIN: " name)
11865 (while plist
11866 (if (eq (car plist) :name)
11867 (setq plist (cddr plist))
11868 (insert " " (prin1-to-string (pop plist)))))
11869 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11870 (beginning-of-line -2)))
11872 (defun org-prepare-dblock ()
11873 "Prepare dynamic block for refresh.
11874 This empties the block, puts the cursor at the insert position and returns
11875 the property list including an extra property :name with the block name."
11876 (unless (looking-at org-dblock-start-re)
11877 (user-error "Not at a dynamic block"))
11878 (let* ((begdel (1+ (match-end 0)))
11879 (name (org-no-properties (match-string 1)))
11880 (params (append (list :name name)
11881 (read (concat "(" (match-string 3) ")")))))
11882 (save-excursion
11883 (beginning-of-line 1)
11884 (skip-chars-forward " \t")
11885 (setq params (plist-put params :indentation-column (current-column))))
11886 (unless (re-search-forward org-dblock-end-re nil t)
11887 (error "Dynamic block not terminated"))
11888 (setq params
11889 (append params
11890 (list :content (buffer-substring
11891 begdel (match-beginning 0)))))
11892 (delete-region begdel (match-beginning 0))
11893 (goto-char begdel)
11894 (open-line 1)
11895 params))
11897 (defun org-map-dblocks (&optional command)
11898 "Apply COMMAND to all dynamic blocks in the current buffer.
11899 If COMMAND is not given, use `org-update-dblock'."
11900 (let ((cmd (or command 'org-update-dblock)))
11901 (save-excursion
11902 (goto-char (point-min))
11903 (while (re-search-forward org-dblock-start-re nil t)
11904 (goto-char (match-beginning 0))
11905 (save-excursion
11906 (condition-case nil
11907 (funcall cmd)
11908 (error (message "Error during update of dynamic block"))))
11909 (unless (re-search-forward org-dblock-end-re nil t)
11910 (error "Dynamic block not terminated"))))))
11912 (defun org-dblock-update (&optional arg)
11913 "User command for updating dynamic blocks.
11914 Update the dynamic block at point. With prefix ARG, update all dynamic
11915 blocks in the buffer."
11916 (interactive "P")
11917 (if arg
11918 (org-update-all-dblocks)
11919 (or (looking-at org-dblock-start-re)
11920 (org-beginning-of-dblock))
11921 (org-update-dblock)))
11923 (defun org-update-dblock ()
11924 "Update the dynamic block at point.
11925 This means to empty the block, parse for parameters and then call
11926 the correct writing function."
11927 (interactive)
11928 (save-window-excursion
11929 (let* ((pos (point))
11930 (line (org-current-line))
11931 (params (org-prepare-dblock))
11932 (name (plist-get params :name))
11933 (indent (plist-get params :indentation-column))
11934 (cmd (intern (concat "org-dblock-write:" name))))
11935 (message "Updating dynamic block `%s' at line %d..." name line)
11936 (funcall cmd params)
11937 (message "Updating dynamic block `%s' at line %d...done" name line)
11938 (goto-char pos)
11939 (when (and indent (> indent 0))
11940 (setq indent (make-string indent ?\ ))
11941 (save-excursion
11942 (org-beginning-of-dblock)
11943 (forward-line 1)
11944 (while (not (looking-at org-dblock-end-re))
11945 (insert indent)
11946 (beginning-of-line 2))
11947 (when (looking-at org-dblock-end-re)
11948 (and (looking-at "[ \t]+")
11949 (replace-match ""))
11950 (insert indent)))))))
11952 (defun org-beginning-of-dblock ()
11953 "Find the beginning of the dynamic block at point.
11954 Error if there is no such block at point."
11955 (let ((pos (point))
11956 beg)
11957 (end-of-line 1)
11958 (if (and (re-search-backward org-dblock-start-re nil t)
11959 (setq beg (match-beginning 0))
11960 (re-search-forward org-dblock-end-re nil t)
11961 (> (match-end 0) pos))
11962 (goto-char beg)
11963 (goto-char pos)
11964 (error "Not in a dynamic block"))))
11966 (defun org-update-all-dblocks ()
11967 "Update all dynamic blocks in the buffer.
11968 This function can be used in a hook."
11969 (interactive)
11970 (when (derived-mode-p 'org-mode)
11971 (org-map-dblocks 'org-update-dblock)))
11974 ;;;; Completion
11976 (declare-function org-export-backend-name "org-export" (cl-x))
11977 (declare-function org-export-backend-options "org-export" (cl-x))
11978 (defun org-get-export-keywords ()
11979 "Return a list of all currently understood export keywords.
11980 Export keywords include options, block names, attributes and
11981 keywords relative to each registered export back-end."
11982 (let (keywords)
11983 (dolist (backend
11984 (org-bound-and-true-p org-export--registered-backends)
11985 (delq nil keywords))
11986 ;; Back-end name (for keywords, like #+LATEX:)
11987 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11988 (dolist (option-entry (org-export-backend-options backend))
11989 ;; Back-end options.
11990 (push (nth 1 option-entry) keywords)))))
11992 (defconst org-options-keywords
11993 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11994 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11995 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11996 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11997 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11999 (defcustom org-structure-template-alist
12000 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC" "<src lang=\"?\">\n\n</src>")
12001 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE" "<example>\n?\n</example>")
12002 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE" "<quote>\n?\n</quote>")
12003 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE" "<verse>\n?\n</verse>")
12004 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM" "<verbatim>\n?\n</verbatim>")
12005 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER" "<center>\n?\n</center>")
12006 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
12007 "<literal style=\"latex\">\n?\n</literal>")
12008 ("L" "#+LaTeX: " "<literal style=\"latex\">?</literal>")
12009 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
12010 "<literal style=\"html\">\n?\n</literal>")
12011 ("H" "#+HTML: " "<literal style=\"html\">?</literal>")
12012 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII" "")
12013 ("A" "#+ASCII: " "")
12014 ("i" "#+INDEX: ?" "#+INDEX: ?")
12015 ("I" "#+INCLUDE: %file ?"
12016 "<include file=%file markup=\"?\">"))
12017 "Structure completion elements.
12018 This is a list of abbreviation keys and values. The value gets inserted
12019 if you type `<' followed by the key and then press the completion key,
12020 usually `M-TAB'. %file will be replaced by a file name after prompting
12021 for the file using completion. The cursor will be placed at the position
12022 of the `?` in the template.
12023 There are two templates for each key, the first uses the original Org syntax,
12024 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12025 the default when the /org-mtags.el/ module has been loaded. See also the
12026 variable `org-mtags-prefer-muse-templates'."
12027 :group 'org-completion
12028 :type '(repeat
12029 (list
12030 (string :tag "Key")
12031 (string :tag "Template")
12032 (string :tag "Muse Template"))))
12034 (defun org-try-structure-completion ()
12035 "Try to complete a structure template before point.
12036 This looks for strings like \"<e\" on an otherwise empty line and
12037 expands them."
12038 (let ((l (buffer-substring (point-at-bol) (point)))
12040 (when (and (looking-at "[ \t]*$")
12041 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12042 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12043 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12044 (match-beginning 1)) a)
12045 t)))
12047 (defun org-complete-expand-structure-template (start cell)
12048 "Expand a structure template."
12049 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
12050 (rpl (nth (if musep 2 1) cell))
12051 (ind ""))
12052 (delete-region start (point))
12053 (when (string-match "\\`#\\+" rpl)
12054 (cond
12055 ((bolp))
12056 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12057 (setq ind (buffer-substring (point-at-bol) (point))))
12058 (t (newline))))
12059 (setq start (point))
12060 (if (string-match "%file" rpl)
12061 (setq rpl (replace-match
12062 (concat
12063 "\""
12064 (save-match-data
12065 (abbreviate-file-name (read-file-name "Include file: ")))
12066 "\"")
12067 t t rpl)))
12068 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12069 (concat "\n" ind)))
12070 (insert rpl)
12071 (if (re-search-backward "\\?" start t) (delete-char 1))))
12073 ;;;; TODO, DEADLINE, Comments
12075 (defun org-toggle-comment ()
12076 "Change the COMMENT state of an entry."
12077 (interactive)
12078 (save-excursion
12079 (org-back-to-heading)
12080 (let (case-fold-search)
12081 (cond
12082 ((looking-at (format org-heading-keyword-regexp-format
12083 org-comment-string))
12084 (goto-char (match-end 1))
12085 (looking-at (concat " +" org-comment-string))
12086 (replace-match "" t t)
12087 (when (eolp) (insert " ")))
12088 ((looking-at org-outline-regexp)
12089 (goto-char (match-end 0))
12090 (insert org-comment-string " "))))))
12092 (defvar org-last-todo-state-is-todo nil
12093 "This is non-nil when the last TODO state change led to a TODO state.
12094 If the last change removed the TODO tag or switched to DONE, then
12095 this is nil.")
12097 (defvar org-setting-tags nil) ; dynamically skipped
12099 (defvar org-todo-setup-filter-hook nil
12100 "Hook for functions that pre-filter todo specs.
12101 Each function takes a todo spec and returns either nil or the spec
12102 transformed into canonical form." )
12104 (defvar org-todo-get-default-hook nil
12105 "Hook for functions that get a default item for todo.
12106 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12107 nil or a string to be used for the todo mark." )
12109 (defvar org-agenda-headline-snapshot-before-repeat)
12111 (defun org-current-effective-time ()
12112 "Return current time adjusted for `org-extend-today-until' variable."
12113 (let* ((ct (org-current-time))
12114 (dct (decode-time ct))
12115 (ct1
12116 (cond
12117 (org-use-last-clock-out-time-as-effective-time
12118 (or (org-clock-get-last-clock-out-time) ct))
12119 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12120 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12121 (t ct))))
12122 ct1))
12124 (defun org-todo-yesterday (&optional arg)
12125 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12126 (interactive "P")
12127 (if (eq major-mode 'org-agenda-mode)
12128 (apply 'org-agenda-todo-yesterday arg)
12129 (let* ((hour (third (decode-time
12130 (org-current-time))))
12131 (org-extend-today-until (1+ hour)))
12132 (org-todo arg))))
12134 (defvar org-block-entry-blocking ""
12135 "First entry preventing the TODO state change.")
12137 (defun org-todo (&optional arg)
12138 "Change the TODO state of an item.
12139 The state of an item is given by a keyword at the start of the heading,
12140 like
12141 *** TODO Write paper
12142 *** DONE Call mom
12144 The different keywords are specified in the variable `org-todo-keywords'.
12145 By default the available states are \"TODO\" and \"DONE\".
12146 So for this example: when the item starts with TODO, it is changed to DONE.
12147 When it starts with DONE, the DONE is removed. And when neither TODO nor
12148 DONE are present, add TODO at the beginning of the heading.
12150 With \\[universal-argument] prefix arg, use completion to determine the new \
12151 state.
12152 With numeric prefix arg, switch to that state.
12153 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12154 keywords (nextset).
12155 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12156 With a numeric prefix arg of 0, inhibit note taking for the change.
12158 For calling through lisp, arg is also interpreted in the following way:
12159 'none -> empty state
12160 \"\"(empty string) -> switch to empty state
12161 'done -> switch to DONE
12162 'nextset -> switch to the next set of keywords
12163 'previousset -> switch to the previous set of keywords
12164 \"WAITING\" -> switch to the specified keyword, but only if it
12165 really is a member of `org-todo-keywords'."
12166 (interactive "P")
12167 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12168 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12169 'region-start-level 'region))
12170 org-loop-over-headlines-in-active-region)
12171 (org-map-entries
12172 `(org-todo ,arg)
12173 org-loop-over-headlines-in-active-region
12174 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12175 (if (equal arg '(16)) (setq arg 'nextset))
12176 (let ((org-blocker-hook org-blocker-hook)
12177 commentp
12178 case-fold-search)
12179 (when (equal arg '(64))
12180 (setq arg nil org-blocker-hook nil))
12181 (when (and org-blocker-hook
12182 (or org-inhibit-blocking
12183 (org-entry-get nil "NOBLOCKING")))
12184 (setq org-blocker-hook nil))
12185 (save-excursion
12186 (catch 'exit
12187 (org-back-to-heading t)
12188 (when (looking-at (concat "^\\*+ " org-comment-string))
12189 (org-toggle-comment)
12190 (setq commentp t))
12191 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12192 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12193 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12194 (let* ((match-data (match-data))
12195 (startpos (point-at-bol))
12196 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12197 (org-log-done org-log-done)
12198 (org-log-repeat org-log-repeat)
12199 (org-todo-log-states org-todo-log-states)
12200 (org-inhibit-logging
12201 (if (equal arg 0)
12202 (progn (setq arg nil) 'note) org-inhibit-logging))
12203 (this (match-string 1))
12204 (hl-pos (match-beginning 0))
12205 (head (org-get-todo-sequence-head this))
12206 (ass (assoc head org-todo-kwd-alist))
12207 (interpret (nth 1 ass))
12208 (done-word (nth 3 ass))
12209 (final-done-word (nth 4 ass))
12210 (org-last-state (or this ""))
12211 (completion-ignore-case t)
12212 (member (member this org-todo-keywords-1))
12213 (tail (cdr member))
12214 (org-state (cond
12215 ((and org-todo-key-trigger
12216 (or (and (equal arg '(4))
12217 (eq org-use-fast-todo-selection 'prefix))
12218 (and (not arg) org-use-fast-todo-selection
12219 (not (eq org-use-fast-todo-selection
12220 'prefix)))))
12221 ;; Use fast selection
12222 (org-fast-todo-selection))
12223 ((and (equal arg '(4))
12224 (or (not org-use-fast-todo-selection)
12225 (not org-todo-key-trigger)))
12226 ;; Read a state with completion
12227 (org-icompleting-read
12228 "State: " (mapcar 'list org-todo-keywords-1)
12229 nil t))
12230 ((eq arg 'right)
12231 (if this
12232 (if tail (car tail) nil)
12233 (car org-todo-keywords-1)))
12234 ((eq arg 'left)
12235 (if (equal member org-todo-keywords-1)
12237 (if this
12238 (nth (- (length org-todo-keywords-1)
12239 (length tail) 2)
12240 org-todo-keywords-1)
12241 (org-last org-todo-keywords-1))))
12242 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12243 (setq arg nil))) ; hack to fall back to cycling
12244 (arg
12245 ;; user or caller requests a specific state
12246 (cond
12247 ((equal arg "") nil)
12248 ((eq arg 'none) nil)
12249 ((eq arg 'done) (or done-word (car org-done-keywords)))
12250 ((eq arg 'nextset)
12251 (or (car (cdr (member head org-todo-heads)))
12252 (car org-todo-heads)))
12253 ((eq arg 'previousset)
12254 (let ((org-todo-heads (reverse org-todo-heads)))
12255 (or (car (cdr (member head org-todo-heads)))
12256 (car org-todo-heads))))
12257 ((car (member arg org-todo-keywords-1)))
12258 ((stringp arg)
12259 (user-error "State `%s' not valid in this file" arg))
12260 ((nth (1- (prefix-numeric-value arg))
12261 org-todo-keywords-1))))
12262 ((null member) (or head (car org-todo-keywords-1)))
12263 ((equal this final-done-word) nil) ;; -> make empty
12264 ((null tail) nil) ;; -> first entry
12265 ((memq interpret '(type priority))
12266 (if (eq this-command last-command)
12267 (car tail)
12268 (if (> (length tail) 0)
12269 (or done-word (car org-done-keywords))
12270 nil)))
12272 (car tail))))
12273 (org-state (or
12274 (run-hook-with-args-until-success
12275 'org-todo-get-default-hook org-state org-last-state)
12276 org-state))
12277 (next (if org-state (concat " " org-state " ") " "))
12278 (change-plist (list :type 'todo-state-change :from this :to org-state
12279 :position startpos))
12280 dolog now-done-p)
12281 (when org-blocker-hook
12282 (setq org-last-todo-state-is-todo
12283 (not (member this org-done-keywords)))
12284 (unless (save-excursion
12285 (save-match-data
12286 (org-with-wide-buffer
12287 (run-hook-with-args-until-failure
12288 'org-blocker-hook change-plist))))
12289 (if (org-called-interactively-p 'interactive)
12290 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12291 this org-state org-block-entry-blocking)
12292 ;; fail silently
12293 (message "TODO state change from %s to %s blocked (by \"%s\")"
12294 this org-state org-block-entry-blocking)
12295 (throw 'exit nil))))
12296 (store-match-data match-data)
12297 (replace-match next t t)
12298 (unless (pos-visible-in-window-p hl-pos)
12299 (message "TODO state changed to %s" (org-trim next)))
12300 (unless head
12301 (setq head (org-get-todo-sequence-head org-state)
12302 ass (assoc head org-todo-kwd-alist)
12303 interpret (nth 1 ass)
12304 done-word (nth 3 ass)
12305 final-done-word (nth 4 ass)))
12306 (when (memq arg '(nextset previousset))
12307 (message "Keyword-Set %d/%d: %s"
12308 (- (length org-todo-sets) -1
12309 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12310 (length org-todo-sets)
12311 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12312 (setq org-last-todo-state-is-todo
12313 (not (member org-state org-done-keywords)))
12314 (setq now-done-p (and (member org-state org-done-keywords)
12315 (not (member this org-done-keywords))))
12316 (and logging (org-local-logging logging))
12317 (when (and (or org-todo-log-states org-log-done)
12318 (not (eq org-inhibit-logging t))
12319 (not (memq arg '(nextset previousset))))
12320 ;; we need to look at recording a time and note
12321 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12322 (nth 2 (assoc this org-todo-log-states))))
12323 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12324 (setq dolog 'time))
12325 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12326 (and org-state
12327 (member org-state org-not-done-keywords)
12328 (not (member this org-not-done-keywords))))
12329 ;; This is now a todo state and was not one before
12330 ;; If there was a CLOSED time stamp, get rid of it.
12331 (org-add-planning-info nil nil 'closed))
12332 (when (and now-done-p org-log-done)
12333 ;; It is now done, and it was not done before
12334 (org-add-planning-info 'closed (org-current-effective-time))
12335 (if (and (not dolog) (eq 'note org-log-done))
12336 (org-add-log-setup 'done org-state this 'findpos 'note)))
12337 (when (and org-state dolog)
12338 ;; This is a non-nil state, and we need to log it
12339 (org-add-log-setup 'state org-state this 'findpos dolog)))
12340 ;; Fixup tag positioning
12341 (org-todo-trigger-tag-changes org-state)
12342 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12343 (when org-provide-todo-statistics
12344 (org-update-parent-todo-statistics))
12345 (run-hooks 'org-after-todo-state-change-hook)
12346 (if (and arg (not (member org-state org-done-keywords)))
12347 (setq head (org-get-todo-sequence-head org-state)))
12348 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12349 ;; Do we need to trigger a repeat?
12350 (when now-done-p
12351 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12352 ;; This is for the agenda, take a snapshot of the headline.
12353 (save-match-data
12354 (setq org-agenda-headline-snapshot-before-repeat
12355 (org-get-heading))))
12356 (org-auto-repeat-maybe org-state))
12357 ;; Fixup cursor location if close to the keyword
12358 (if (and (outline-on-heading-p)
12359 (not (bolp))
12360 (save-excursion (beginning-of-line 1)
12361 (looking-at org-todo-line-regexp))
12362 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12363 (progn
12364 (goto-char (or (match-end 2) (match-end 1)))
12365 (and (looking-at " ") (just-one-space))))
12366 (when org-trigger-hook
12367 (save-excursion
12368 (run-hook-with-args 'org-trigger-hook change-plist)))
12369 (when commentp (org-toggle-comment))))))))
12371 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12372 "Block turning an entry into a TODO, using the hierarchy.
12373 This checks whether the current task should be blocked from state
12374 changes. Such blocking occurs when:
12376 1. The task has children which are not all in a completed state.
12378 2. A task has a parent with the property :ORDERED:, and there
12379 are siblings prior to the current task with incomplete
12380 status.
12382 3. The parent of the task is blocked because it has siblings that should
12383 be done first, or is child of a block grandparent TODO entry."
12385 (if (not org-enforce-todo-dependencies)
12386 t ; if locally turned off don't block
12387 (catch 'dont-block
12388 ;; If this is not a todo state change, or if this entry is already DONE,
12389 ;; do not block
12390 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12391 (member (plist-get change-plist :from)
12392 (cons 'done org-done-keywords))
12393 (member (plist-get change-plist :to)
12394 (cons 'todo org-not-done-keywords))
12395 (not (plist-get change-plist :to)))
12396 (throw 'dont-block t))
12397 ;; If this task has children, and any are undone, it's blocked
12398 (save-excursion
12399 (org-back-to-heading t)
12400 (let ((this-level (funcall outline-level)))
12401 (outline-next-heading)
12402 (let ((child-level (funcall outline-level)))
12403 (while (and (not (eobp))
12404 (> child-level this-level))
12405 ;; this todo has children, check whether they are all
12406 ;; completed
12407 (if (and (not (org-entry-is-done-p))
12408 (org-entry-is-todo-p))
12409 (progn (setq org-block-entry-blocking (org-get-heading))
12410 (throw 'dont-block nil)))
12411 (outline-next-heading)
12412 (setq child-level (funcall outline-level))))))
12413 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12414 ;; any previous siblings are undone, it's blocked
12415 (save-excursion
12416 (org-back-to-heading t)
12417 (let* ((pos (point))
12418 (parent-pos (and (org-up-heading-safe) (point))))
12419 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12420 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12421 (forward-line 1)
12422 (re-search-forward org-not-done-heading-regexp pos t))
12423 (setq org-block-entry-blocking (match-string 0))
12424 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12425 ;; Search further up the hierarchy, to see if an ancestor is blocked
12426 (while t
12427 (goto-char parent-pos)
12428 (if (not (looking-at org-not-done-heading-regexp))
12429 (throw 'dont-block t)) ; do not block, parent is not a TODO
12430 (setq pos (point))
12431 (setq parent-pos (and (org-up-heading-safe) (point)))
12432 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12433 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12434 (forward-line 1)
12435 (re-search-forward org-not-done-heading-regexp pos t)
12436 (setq org-block-entry-blocking (org-get-heading)))
12437 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12439 (defcustom org-track-ordered-property-with-tag nil
12440 "Should the ORDERED property also be shown as a tag?
12441 The ORDERED property decides if an entry should require subtasks to be
12442 completed in sequence. Since a property is not very visible, setting
12443 this option means that toggling the ORDERED property with the command
12444 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12445 not relevant for the behavior, but it makes things more visible.
12447 Note that toggling the tag with tags commands will not change the property
12448 and therefore not influence behavior!
12450 This can be t, meaning the tag ORDERED should be used, It can also be a
12451 string to select a different tag for this task."
12452 :group 'org-todo
12453 :type '(choice
12454 (const :tag "No tracking" nil)
12455 (const :tag "Track with ORDERED tag" t)
12456 (string :tag "Use other tag")))
12458 (defun org-toggle-ordered-property ()
12459 "Toggle the ORDERED property of the current entry.
12460 For better visibility, you can track the value of this property with a tag.
12461 See variable `org-track-ordered-property-with-tag'."
12462 (interactive)
12463 (let* ((t1 org-track-ordered-property-with-tag)
12464 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12465 (save-excursion
12466 (org-back-to-heading)
12467 (if (org-entry-get nil "ORDERED")
12468 (progn
12469 (org-delete-property "ORDERED" "PROPERTIES")
12470 (and tag (org-toggle-tag tag 'off))
12471 (message "Subtasks can be completed in arbitrary order"))
12472 (org-entry-put nil "ORDERED" "t")
12473 (and tag (org-toggle-tag tag 'on))
12474 (message "Subtasks must be completed in sequence")))))
12476 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12477 (defun org-block-todo-from-checkboxes (change-plist)
12478 "Block turning an entry into a TODO, using checkboxes.
12479 This checks whether the current task should be blocked from state
12480 changes because there are unchecked boxes in this entry."
12481 (if (not org-enforce-todo-checkbox-dependencies)
12482 t ; if locally turned off don't block
12483 (catch 'dont-block
12484 ;; If this is not a todo state change, or if this entry is already DONE,
12485 ;; do not block
12486 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12487 (member (plist-get change-plist :from)
12488 (cons 'done org-done-keywords))
12489 (member (plist-get change-plist :to)
12490 (cons 'todo org-not-done-keywords))
12491 (not (plist-get change-plist :to)))
12492 (throw 'dont-block t))
12493 ;; If this task has checkboxes that are not checked, it's blocked
12494 (save-excursion
12495 (org-back-to-heading t)
12496 (let ((beg (point)) end)
12497 (outline-next-heading)
12498 (setq end (point))
12499 (goto-char beg)
12500 (if (org-list-search-forward
12501 (concat (org-item-beginning-re)
12502 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12503 "\\[[- ]\\]")
12504 end t)
12505 (progn
12506 (if (boundp 'org-blocked-by-checkboxes)
12507 (setq org-blocked-by-checkboxes t))
12508 (throw 'dont-block nil)))))
12509 t))) ; do not block
12511 (defun org-entry-blocked-p ()
12512 "Is the current entry blocked?"
12513 (org-with-silent-modifications
12514 (if (org-entry-get nil "NOBLOCKING")
12515 nil ;; Never block this entry
12516 (not (run-hook-with-args-until-failure
12517 'org-blocker-hook
12518 (list :type 'todo-state-change
12519 :position (point)
12520 :from 'todo
12521 :to 'done))))))
12523 (defun org-update-statistics-cookies (all)
12524 "Update the statistics cookie, either from TODO or from checkboxes.
12525 This should be called with the cursor in a line with a statistics cookie."
12526 (interactive "P")
12527 (if all
12528 (progn
12529 (org-update-checkbox-count 'all)
12530 (org-map-entries 'org-update-parent-todo-statistics))
12531 (if (not (org-at-heading-p))
12532 (org-update-checkbox-count)
12533 (let ((pos (point-marker))
12534 end l1 l2)
12535 (ignore-errors (org-back-to-heading t))
12536 (if (not (org-at-heading-p))
12537 (org-update-checkbox-count)
12538 (setq l1 (org-outline-level))
12539 (setq end (save-excursion
12540 (outline-next-heading)
12541 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12542 (point)))
12543 (if (and (save-excursion
12544 (re-search-forward
12545 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12546 (not (save-excursion (re-search-forward
12547 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12548 (org-update-checkbox-count)
12549 (if (and l2 (> l2 l1))
12550 (progn
12551 (goto-char end)
12552 (org-update-parent-todo-statistics))
12553 (goto-char pos)
12554 (beginning-of-line 1)
12555 (while (re-search-forward
12556 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12557 (point-at-eol) t)
12558 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12559 (goto-char pos)
12560 (move-marker pos nil)))))
12562 (defvar org-entry-property-inherited-from) ;; defined below
12563 (defun org-update-parent-todo-statistics ()
12564 "Update any statistics cookie in the parent of the current headline.
12565 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12566 the entire subtree and this will travel up the hierarchy and update
12567 statistics everywhere."
12568 (let* ((prop (save-excursion (org-up-heading-safe)
12569 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12570 (recursive (or (not org-hierarchical-todo-statistics)
12571 (and prop (string-match "\\<recursive\\>" prop))))
12572 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12574 (first t)
12575 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12576 level ltoggle l1 new ndel
12577 (cnt-all 0) (cnt-done 0) is-percent kwd
12578 checkbox-beg ov ovs ove cookie-present)
12579 (catch 'exit
12580 (save-excursion
12581 (beginning-of-line 1)
12582 (setq ltoggle (funcall outline-level))
12583 ;; Three situations are to consider:
12585 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12586 ;; to the top-level ancestor on the headline;
12588 ;; 2. If parent has "recursive" property, repeat up to the
12589 ;; headline setting that property, taking inheritance into
12590 ;; account;
12592 ;; 3. Else, move up to direct parent and proceed only once.
12593 (while (and (setq level (org-up-heading-safe))
12594 (or recursive first)
12595 (>= (point) lim))
12596 (setq first nil cookie-present nil)
12597 (unless (and level
12598 (not (string-match
12599 "\\<checkbox\\>"
12600 (downcase (or (org-entry-get nil "COOKIE_DATA")
12601 "")))))
12602 (throw 'exit nil))
12603 (while (re-search-forward box-re (point-at-eol) t)
12604 (setq cnt-all 0 cnt-done 0 cookie-present t)
12605 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12606 (save-match-data
12607 (unless (outline-next-heading) (throw 'exit nil))
12608 (while (and (looking-at org-complex-heading-regexp)
12609 (> (setq l1 (length (match-string 1))) level))
12610 (setq kwd (and (or recursive (= l1 ltoggle))
12611 (match-string 2)))
12612 (if (or (eq org-provide-todo-statistics 'all-headlines)
12613 (and (listp org-provide-todo-statistics)
12614 (or (member kwd org-provide-todo-statistics)
12615 (member kwd org-done-keywords))))
12616 (setq cnt-all (1+ cnt-all))
12617 (if (eq org-provide-todo-statistics t)
12618 (and kwd (setq cnt-all (1+ cnt-all)))))
12619 (and (member kwd org-done-keywords)
12620 (setq cnt-done (1+ cnt-done)))
12621 (outline-next-heading)))
12622 (setq new
12623 (if is-percent
12624 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12625 (format "[%d/%d]" cnt-done cnt-all))
12626 ndel (- (match-end 0) checkbox-beg))
12627 ;; handle overlays when updating cookie from column view
12628 (when (setq ov (car (overlays-at checkbox-beg)))
12629 (setq ovs (overlay-start ov) ove (overlay-end ov))
12630 (delete-overlay ov))
12631 (goto-char checkbox-beg)
12632 (insert new)
12633 (delete-region (point) (+ (point) ndel))
12634 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12635 (when ov (move-overlay ov ovs ove)))
12636 (when cookie-present
12637 (run-hook-with-args 'org-after-todo-statistics-hook
12638 cnt-done (- cnt-all cnt-done))))))
12639 (run-hooks 'org-todo-statistics-hook)))
12641 (defvar org-after-todo-statistics-hook nil
12642 "Hook that is called after a TODO statistics cookie has been updated.
12643 Each function is called with two arguments: the number of not-done entries
12644 and the number of done entries.
12646 For example, the following function, when added to this hook, will switch
12647 an entry to DONE when all children are done, and back to TODO when new
12648 entries are set to a TODO status. Note that this hook is only called
12649 when there is a statistics cookie in the headline!
12651 (defun org-summary-todo (n-done n-not-done)
12652 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12653 (let (org-log-done org-log-states) ; turn off logging
12654 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12657 (defvar org-todo-statistics-hook nil
12658 "Hook that is run whenever Org thinks TODO statistics should be updated.
12659 This hook runs even if there is no statistics cookie present, in which case
12660 `org-after-todo-statistics-hook' would not run.")
12662 (defun org-todo-trigger-tag-changes (state)
12663 "Apply the changes defined in `org-todo-state-tags-triggers'."
12664 (let ((l org-todo-state-tags-triggers)
12665 changes)
12666 (when (or (not state) (equal state ""))
12667 (setq changes (append changes (cdr (assoc "" l)))))
12668 (when (and (stringp state) (> (length state) 0))
12669 (setq changes (append changes (cdr (assoc state l)))))
12670 (when (member state org-not-done-keywords)
12671 (setq changes (append changes (cdr (assoc 'todo l)))))
12672 (when (member state org-done-keywords)
12673 (setq changes (append changes (cdr (assoc 'done l)))))
12674 (dolist (c changes)
12675 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12677 (defun org-local-logging (value)
12678 "Get logging settings from a property VALUE."
12679 (let* (words w a)
12680 ;; directly set the variables, they are already local.
12681 (setq org-log-done nil
12682 org-log-repeat nil
12683 org-todo-log-states nil)
12684 (setq words (org-split-string value))
12685 (while (setq w (pop words))
12686 (cond
12687 ((setq a (assoc w org-startup-options))
12688 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12689 (set (nth 1 a) (nth 2 a))))
12690 ((setq a (org-extract-log-state-settings w))
12691 (and (member (car a) org-todo-keywords-1)
12692 (push a org-todo-log-states)))))))
12694 (defun org-get-todo-sequence-head (kwd)
12695 "Return the head of the TODO sequence to which KWD belongs.
12696 If KWD is not set, check if there is a text property remembering the
12697 right sequence."
12698 (let (p)
12699 (cond
12700 ((not kwd)
12701 (or (get-text-property (point-at-bol) 'org-todo-head)
12702 (progn
12703 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12704 nil (point-at-eol)))
12705 (get-text-property p 'org-todo-head))))
12706 ((not (member kwd org-todo-keywords-1))
12707 (car org-todo-keywords-1))
12708 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12710 (defun org-fast-todo-selection ()
12711 "Fast TODO keyword selection with single keys.
12712 Returns the new TODO keyword, or nil if no state change should occur."
12713 (let* ((fulltable org-todo-key-alist)
12714 (done-keywords org-done-keywords) ;; needed for the faces.
12715 (maxlen (apply 'max (mapcar
12716 (lambda (x)
12717 (if (stringp (car x)) (string-width (car x)) 0))
12718 fulltable)))
12719 (expert nil)
12720 (fwidth (+ maxlen 3 1 3))
12721 (ncol (/ (- (window-width) 4) fwidth))
12722 tg cnt e c tbl
12723 groups ingroup)
12724 (save-excursion
12725 (save-window-excursion
12726 (if expert
12727 (set-buffer (get-buffer-create " *Org todo*"))
12728 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12729 (erase-buffer)
12730 (org-set-local 'org-done-keywords done-keywords)
12731 (setq tbl fulltable cnt 0)
12732 (while (setq e (pop tbl))
12733 (cond
12734 ((equal e '(:startgroup))
12735 (push '() groups) (setq ingroup t)
12736 (when (not (= cnt 0))
12737 (setq cnt 0)
12738 (insert "\n"))
12739 (insert "{ "))
12740 ((equal e '(:endgroup))
12741 (setq ingroup nil cnt 0)
12742 (insert "}\n"))
12743 ((equal e '(:newline))
12744 (when (not (= cnt 0))
12745 (setq cnt 0)
12746 (insert "\n")
12747 (setq e (car tbl))
12748 (while (equal (car tbl) '(:newline))
12749 (insert "\n")
12750 (setq tbl (cdr tbl)))))
12752 (setq tg (car e) c (cdr e))
12753 (if ingroup (push tg (car groups)))
12754 (setq tg (org-add-props tg nil 'face
12755 (org-get-todo-face tg)))
12756 (if (and (= cnt 0) (not ingroup)) (insert " "))
12757 (insert "[" c "] " tg (make-string
12758 (- fwidth 4 (length tg)) ?\ ))
12759 (when (= (setq cnt (1+ cnt)) ncol)
12760 (insert "\n")
12761 (if ingroup (insert " "))
12762 (setq cnt 0)))))
12763 (insert "\n")
12764 (goto-char (point-min))
12765 (if (not expert) (org-fit-window-to-buffer))
12766 (message "[a-z..]:Set [SPC]:clear")
12767 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12768 (cond
12769 ((or (= c ?\C-g)
12770 (and (= c ?q) (not (rassoc c fulltable))))
12771 (setq quit-flag t))
12772 ((= c ?\ ) nil)
12773 ((setq e (rassoc c fulltable) tg (car e))
12775 (t (setq quit-flag t)))))))
12777 (defun org-entry-is-todo-p ()
12778 (member (org-get-todo-state) org-not-done-keywords))
12780 (defun org-entry-is-done-p ()
12781 (member (org-get-todo-state) org-done-keywords))
12783 (defun org-get-todo-state ()
12784 "Return the TODO keyword of the current subtree."
12785 (save-excursion
12786 (org-back-to-heading t)
12787 (and (looking-at org-todo-line-regexp)
12788 (match-end 2)
12789 (match-string 2))))
12791 (defun org-at-date-range-p (&optional inactive-ok)
12792 "Is the cursor inside a date range?"
12793 (interactive)
12794 (save-excursion
12795 (catch 'exit
12796 (let ((pos (point)))
12797 (skip-chars-backward "^[<\r\n")
12798 (skip-chars-backward "<[")
12799 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12800 (>= (match-end 0) pos)
12801 (throw 'exit t))
12802 (skip-chars-backward "^<[\r\n")
12803 (skip-chars-backward "<[")
12804 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12805 (>= (match-end 0) pos)
12806 (throw 'exit t)))
12807 nil)))
12809 (defun org-get-repeat (&optional tagline)
12810 "Check if there is a deadline/schedule with repeater in this entry."
12811 (save-match-data
12812 (save-excursion
12813 (org-back-to-heading t)
12814 (and (re-search-forward (if tagline
12815 (concat tagline "\\s-*" org-repeat-re)
12816 org-repeat-re)
12817 (org-entry-end-position) t)
12818 (match-string-no-properties 1)))))
12820 (defvar org-last-changed-timestamp)
12821 (defvar org-last-inserted-timestamp)
12822 (defvar org-log-post-message)
12823 (defvar org-log-note-purpose)
12824 (defvar org-log-note-how)
12825 (defvar org-log-note-extra)
12826 (defun org-auto-repeat-maybe (done-word)
12827 "Check if the current headline contains a repeated deadline/schedule.
12828 If yes, set TODO state back to what it was and change the base date
12829 of repeating deadline/scheduled time stamps to new date.
12830 This function is run automatically after each state change to a DONE state."
12831 ;; last-state is dynamically scoped into this function
12832 (let* ((repeat (org-get-repeat))
12833 (aa (assoc org-last-state org-todo-kwd-alist))
12834 (interpret (nth 1 aa))
12835 (head (nth 2 aa))
12836 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12837 (msg "Entry repeats: ")
12838 (org-log-done nil)
12839 (org-todo-log-states nil)
12840 re type n what ts time to-state)
12841 (when repeat
12842 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12843 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12844 org-todo-repeat-to-state))
12845 (unless (and to-state (member to-state org-todo-keywords-1))
12846 (setq to-state (if (eq interpret 'type) org-last-state head)))
12847 (org-todo to-state)
12848 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12849 (org-entry-put nil "LAST_REPEAT" (format-time-string
12850 (org-time-stamp-format t t))))
12851 (when org-log-repeat
12852 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12853 (memq 'org-add-log-note post-command-hook))
12854 ;; OK, we are already setup for some record
12855 (if (eq org-log-repeat 'note)
12856 ;; make sure we take a note, not only a time stamp
12857 (setq org-log-note-how 'note))
12858 ;; Set up for taking a record
12859 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12860 org-last-state
12861 'findpos org-log-repeat)))
12862 (org-back-to-heading t)
12863 (org-add-planning-info nil nil 'closed)
12864 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12865 org-deadline-time-regexp "\\)\\|\\("
12866 org-ts-regexp "\\)"))
12867 (while (re-search-forward
12868 re (save-excursion (outline-next-heading) (point)) t)
12869 (setq type (if (match-end 1) org-scheduled-string
12870 (if (match-end 3) org-deadline-string "Plain:"))
12871 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12872 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12873 (setq n (string-to-number (match-string 2 ts))
12874 what (match-string 3 ts))
12875 (if (equal what "w") (setq n (* n 7) what "d"))
12876 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12877 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12878 ;; Preparation, see if we need to modify the start date for the change
12879 (when (match-end 1)
12880 (setq time (save-match-data (org-time-string-to-time ts)))
12881 (cond
12882 ((equal (match-string 1 ts) ".")
12883 ;; Shift starting date to today
12884 (org-timestamp-change
12885 (- (org-today) (time-to-days time))
12886 'day))
12887 ((equal (match-string 1 ts) "+")
12888 (let ((nshiftmax 10) (nshift 0))
12889 (while (or (= nshift 0)
12890 (<= (time-to-days time)
12891 (time-to-days (current-time))))
12892 (when (= (incf nshift) nshiftmax)
12893 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12894 (error "Abort")))
12895 (org-timestamp-change n (cdr (assoc what whata)))
12896 (org-at-timestamp-p t)
12897 (setq ts (match-string 1))
12898 (setq time (save-match-data (org-time-string-to-time ts)))))
12899 (org-timestamp-change (- n) (cdr (assoc what whata)))
12900 ;; rematch, so that we have everything in place for the real shift
12901 (org-at-timestamp-p t)
12902 (setq ts (match-string 1))
12903 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12904 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12905 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12906 (setq org-log-post-message msg)
12907 (message "%s" msg))))
12909 (defun org-show-todo-tree (arg)
12910 "Make a compact tree which shows all headlines marked with TODO.
12911 The tree will show the lines where the regexp matches, and all higher
12912 headlines above the match.
12913 With a \\[universal-argument] prefix, prompt for a regexp to match.
12914 With a numeric prefix N, construct a sparse tree for the Nth element
12915 of `org-todo-keywords-1'."
12916 (interactive "P")
12917 (let ((case-fold-search nil)
12918 (kwd-re
12919 (cond ((null arg) org-not-done-regexp)
12920 ((equal arg '(4))
12921 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12922 (mapcar 'list org-todo-keywords-1))))
12923 (concat "\\("
12924 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12925 "\\)\\>")))
12926 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12927 (regexp-quote (nth (1- (prefix-numeric-value arg))
12928 org-todo-keywords-1)))
12929 (t (user-error "Invalid prefix argument: %s" arg)))))
12930 (message "%d TODO entries found"
12931 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12933 (defun org-deadline (arg &optional time)
12934 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12935 With one universal prefix argument, remove any deadline from the item.
12936 With two universal prefix arguments, prompt for a warning delay.
12937 With argument TIME, set the deadline at the corresponding date. TIME
12938 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12939 (interactive "P")
12940 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12941 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12942 'region-start-level 'region))
12943 org-loop-over-headlines-in-active-region)
12944 (org-map-entries
12945 `(org-deadline ',arg ,time)
12946 org-loop-over-headlines-in-active-region
12947 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12948 (let* ((old-date (org-entry-get nil "DEADLINE"))
12949 (old-date-time (if old-date (org-time-string-to-time old-date)))
12950 (repeater (and old-date
12951 (string-match
12952 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12953 old-date)
12954 (match-string 1 old-date))))
12955 (cond
12956 ((equal arg '(4))
12957 (when (and old-date org-log-redeadline)
12958 (org-add-log-setup 'deldeadline nil old-date 'findpos
12959 org-log-redeadline))
12960 (org-remove-timestamp-with-keyword org-deadline-string)
12961 (message "Item no longer has a deadline."))
12962 ((equal arg '(16))
12963 (save-excursion
12964 (org-back-to-heading t)
12965 (if (re-search-forward
12966 org-deadline-time-regexp
12967 (save-excursion (outline-next-heading) (point)) t)
12968 (let* ((rpl0 (match-string 1))
12969 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12970 (replace-match
12971 (concat org-deadline-string
12972 " <" rpl
12973 (format " -%dd"
12974 (abs
12975 (- (time-to-days
12976 (save-match-data
12977 (org-read-date nil t nil "Warn starting from" old-date-time)))
12978 (time-to-days old-date-time))))
12979 ">") t t))
12980 (user-error "No deadline information to update"))))
12982 (org-add-planning-info 'deadline time 'closed)
12983 (when (and old-date org-log-redeadline
12984 (not (equal old-date
12985 (substring org-last-inserted-timestamp 1 -1))))
12986 (org-add-log-setup 'redeadline nil old-date 'findpos
12987 org-log-redeadline))
12988 (when repeater
12989 (save-excursion
12990 (org-back-to-heading t)
12991 (when (re-search-forward (concat org-deadline-string " "
12992 org-last-inserted-timestamp)
12993 (save-excursion
12994 (outline-next-heading) (point)) t)
12995 (goto-char (1- (match-end 0)))
12996 (insert " " repeater)
12997 (setq org-last-inserted-timestamp
12998 (concat (substring org-last-inserted-timestamp 0 -1)
12999 " " repeater
13000 (substring org-last-inserted-timestamp -1))))))
13001 (message "Deadline on %s" org-last-inserted-timestamp))))))
13003 (defun org-schedule (arg &optional time)
13004 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13005 With one universal prefix argument, remove any scheduling date from the item.
13006 With two universal prefix arguments, prompt for a delay cookie.
13007 With argument TIME, scheduled at the corresponding date. TIME can
13008 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13009 (interactive "P")
13010 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13011 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13012 'region-start-level 'region))
13013 org-loop-over-headlines-in-active-region)
13014 (org-map-entries
13015 `(org-schedule ',arg ,time)
13016 org-loop-over-headlines-in-active-region
13017 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13018 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13019 (old-date-time (if old-date (org-time-string-to-time old-date)))
13020 (repeater (and old-date
13021 (string-match
13022 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13023 old-date)
13024 (match-string 1 old-date))))
13025 (cond
13026 ((equal arg '(4))
13027 (progn
13028 (when (and old-date org-log-reschedule)
13029 (org-add-log-setup 'delschedule nil old-date 'findpos
13030 org-log-reschedule))
13031 (org-remove-timestamp-with-keyword org-scheduled-string)
13032 (message "Item is no longer scheduled.")))
13033 ((equal arg '(16))
13034 (save-excursion
13035 (org-back-to-heading t)
13036 (if (re-search-forward
13037 org-scheduled-time-regexp
13038 (save-excursion (outline-next-heading) (point)) t)
13039 (let* ((rpl0 (match-string 1))
13040 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13041 (replace-match
13042 (concat org-scheduled-string
13043 " <" rpl
13044 (format " -%dd"
13045 (abs
13046 (- (time-to-days
13047 (save-match-data
13048 (org-read-date nil t nil "Delay until" old-date-time)))
13049 (time-to-days old-date-time))))
13050 ">") t t))
13051 (user-error "No scheduled information to update"))))
13053 (org-add-planning-info 'scheduled time 'closed)
13054 (when (and old-date org-log-reschedule
13055 (not (equal old-date
13056 (substring org-last-inserted-timestamp 1 -1))))
13057 (org-add-log-setup 'reschedule nil old-date 'findpos
13058 org-log-reschedule))
13059 (when repeater
13060 (save-excursion
13061 (org-back-to-heading t)
13062 (when (re-search-forward (concat org-scheduled-string " "
13063 org-last-inserted-timestamp)
13064 (save-excursion
13065 (outline-next-heading) (point)) t)
13066 (goto-char (1- (match-end 0)))
13067 (insert " " repeater)
13068 (setq org-last-inserted-timestamp
13069 (concat (substring org-last-inserted-timestamp 0 -1)
13070 " " repeater
13071 (substring org-last-inserted-timestamp -1))))))
13072 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13074 (defun org-get-scheduled-time (pom &optional inherit)
13075 "Get the scheduled time as a time tuple, of a format suitable
13076 for calling org-schedule with, or if there is no scheduling,
13077 returns nil."
13078 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13079 (when time
13080 (apply 'encode-time (org-parse-time-string time)))))
13082 (defun org-get-deadline-time (pom &optional inherit)
13083 "Get the deadline as a time tuple, of a format suitable for
13084 calling org-deadline with, or if there is no scheduling, returns
13085 nil."
13086 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13087 (when time
13088 (apply 'encode-time (org-parse-time-string time)))))
13090 (defun org-remove-timestamp-with-keyword (keyword)
13091 "Remove all time stamps with KEYWORD in the current entry."
13092 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13093 beg)
13094 (save-excursion
13095 (org-back-to-heading t)
13096 (setq beg (point))
13097 (outline-next-heading)
13098 (while (re-search-backward re beg t)
13099 (replace-match "")
13100 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13101 (equal (char-before) ?\ ))
13102 (backward-delete-char 1)
13103 (if (string-match "^[ \t]*$" (buffer-substring
13104 (point-at-bol) (point-at-eol)))
13105 (delete-region (point-at-bol)
13106 (min (point-max) (1+ (point-at-eol))))))))))
13108 (defvar org-time-was-given) ; dynamically scoped parameter
13109 (defvar org-end-time-was-given) ; dynamically scoped parameter
13111 (defun org-add-planning-info (what &optional time &rest remove)
13112 "Insert new timestamp with keyword in the line directly after the headline.
13113 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13114 If non is given, the user is prompted for a date.
13115 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13116 be removed."
13117 (interactive)
13118 (let (org-time-was-given org-end-time-was-given ts
13119 end default-time default-input)
13121 (catch 'exit
13122 (when (and (memq what '(scheduled deadline))
13123 (or (not time)
13124 (and (stringp time)
13125 (string-match "^[-+]+[0-9]" time))))
13126 ;; Try to get a default date/time from existing timestamp
13127 (save-excursion
13128 (org-back-to-heading t)
13129 (setq end (save-excursion (outline-next-heading) (point)))
13130 (when (re-search-forward (if (eq what 'scheduled)
13131 org-scheduled-time-regexp
13132 org-deadline-time-regexp)
13133 end t)
13134 (setq ts (match-string 1)
13135 default-time
13136 (apply 'encode-time (org-parse-time-string ts))
13137 default-input (and ts (org-get-compact-tod ts))))))
13138 (when what
13139 (setq time
13140 (if (stringp time)
13141 ;; This is a string (relative or absolute), set proper date
13142 (apply 'encode-time
13143 (org-read-date-analyze
13144 time default-time (decode-time default-time)))
13145 ;; If necessary, get the time from the user
13146 (or time (org-read-date nil 'to-time nil nil
13147 default-time default-input)))))
13149 (when (and org-insert-labeled-timestamps-at-point
13150 (member what '(scheduled deadline)))
13151 (insert
13152 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13153 (org-insert-time-stamp time org-time-was-given
13154 nil nil nil (list org-end-time-was-given))
13155 (setq what nil))
13156 (save-excursion
13157 (save-restriction
13158 (let (col list elt ts buffer-invisibility-spec)
13159 (org-back-to-heading t)
13160 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13161 (goto-char (match-end 1))
13162 (setq col (current-column))
13163 (goto-char (match-end 0))
13164 (if (eobp) (insert "\n") (forward-char 1))
13165 (when (and (not what)
13166 (not (looking-at
13167 (concat "[ \t]*"
13168 org-keyword-time-not-clock-regexp))))
13169 ;; Nothing to add, nothing to remove...... :-)
13170 (throw 'exit nil))
13171 (if (and (not (looking-at org-outline-regexp))
13172 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13173 "[^\r\n]*"))
13174 (not (equal (match-string 1) org-clock-string)))
13175 (narrow-to-region (match-beginning 0) (match-end 0))
13176 (insert-before-markers "\n")
13177 (backward-char 1)
13178 (narrow-to-region (point) (point))
13179 (and org-adapt-indentation (org-indent-to-column col)))
13180 ;; Check if we have to remove something.
13181 (setq list (cons what remove))
13182 (while list
13183 (setq elt (pop list))
13184 (when (or (and (eq elt 'scheduled)
13185 (re-search-forward org-scheduled-time-regexp nil t))
13186 (and (eq elt 'deadline)
13187 (re-search-forward org-deadline-time-regexp nil t))
13188 (and (eq elt 'closed)
13189 (re-search-forward org-closed-time-regexp nil t)))
13190 (replace-match "")
13191 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13192 (and (looking-at "[ \t]+") (replace-match ""))
13193 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13194 (when what
13195 (insert
13196 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13197 (cond ((eq what 'scheduled) org-scheduled-string)
13198 ((eq what 'deadline) org-deadline-string)
13199 ((eq what 'closed) org-closed-string))
13200 " ")
13201 (setq ts (org-insert-time-stamp
13202 time
13203 (or org-time-was-given
13204 (and (eq what 'closed) org-log-done-with-time))
13205 (eq what 'closed)
13206 nil nil (list org-end-time-was-given)))
13207 (insert
13208 (if (not (or (bolp) (eq (char-before) ?\ )
13209 (memq (char-after) '(32 10))
13210 (eobp))) " " ""))
13211 (end-of-line 1))
13212 (goto-char (point-min))
13213 (widen)
13214 (if (and (looking-at "[ \t]*\n")
13215 (equal (char-before) ?\n))
13216 (delete-region (1- (point)) (point-at-eol)))
13217 ts))))))
13219 (defvar org-log-note-marker (make-marker))
13220 (defvar org-log-note-purpose nil)
13221 (defvar org-log-note-state nil)
13222 (defvar org-log-note-previous-state nil)
13223 (defvar org-log-note-how nil)
13224 (defvar org-log-note-extra nil)
13225 (defvar org-log-note-window-configuration nil)
13226 (defvar org-log-note-return-to (make-marker))
13227 (defvar org-log-note-effective-time nil
13228 "Remembered current time so that dynamically scoped
13229 `org-extend-today-until' affects tha timestamps in state change
13230 log")
13232 (defvar org-log-post-message nil
13233 "Message to be displayed after a log note has been stored.
13234 The auto-repeater uses this.")
13236 (defun org-add-note ()
13237 "Add a note to the current entry.
13238 This is done in the same way as adding a state change note."
13239 (interactive)
13240 (org-add-log-setup 'note nil nil 'findpos nil))
13242 (defvar org-property-end-re)
13243 (defun org-add-log-setup (&optional purpose state prev-state
13244 findpos how extra)
13245 "Set up the post command hook to take a note.
13246 If this is about to TODO state change, the new state is expected in STATE.
13247 When FINDPOS is non-nil, find the correct position for the note in
13248 the current entry. If not, assume that it can be inserted at point.
13249 HOW is an indicator what kind of note should be created.
13250 EXTRA is additional text that will be inserted into the notes buffer."
13251 (let* ((org-log-into-drawer (org-log-into-drawer))
13252 (drawer (cond ((stringp org-log-into-drawer)
13253 org-log-into-drawer)
13254 (org-log-into-drawer "LOGBOOK"))))
13255 (save-restriction
13256 (save-excursion
13257 (when findpos
13258 (org-back-to-heading t)
13259 (narrow-to-region (point) (save-excursion
13260 (outline-next-heading) (point)))
13261 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13262 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13263 "[^\r\n]*\\)?"))
13264 (goto-char (match-end 0))
13265 (cond
13266 (drawer
13267 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13268 nil t)
13269 (progn
13270 (goto-char (match-end 0))
13271 (or org-log-states-order-reversed
13272 (and (re-search-forward org-property-end-re nil t)
13273 (goto-char (1- (match-beginning 0))))))
13274 (insert "\n:" drawer ":\n:END:")
13275 (beginning-of-line 0)
13276 (org-indent-line)
13277 (beginning-of-line 2)
13278 (org-indent-line)
13279 (end-of-line 0)))
13280 ((and org-log-state-notes-insert-after-drawers
13281 (save-excursion
13282 (forward-line) (looking-at org-drawer-regexp)))
13283 (forward-line)
13284 (while (looking-at org-drawer-regexp)
13285 (goto-char (match-end 0))
13286 (re-search-forward org-property-end-re (point-max) t)
13287 (forward-line))
13288 (forward-line -1)))
13289 (unless org-log-states-order-reversed
13290 (and (= (char-after) ?\n) (forward-char 1))
13291 (org-skip-over-state-notes)
13292 (skip-chars-backward " \t\n\r")))
13293 (move-marker org-log-note-marker (point))
13294 (setq org-log-note-purpose purpose
13295 org-log-note-state state
13296 org-log-note-previous-state prev-state
13297 org-log-note-how how
13298 org-log-note-extra extra
13299 org-log-note-effective-time (org-current-effective-time))
13300 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13302 (defun org-skip-over-state-notes ()
13303 "Skip past the list of State notes in an entry."
13304 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13305 (when (ignore-errors (goto-char (org-in-item-p)))
13306 (let* ((struct (org-list-struct))
13307 (prevs (org-list-prevs-alist struct)))
13308 (while (looking-at "[ \t]*- State")
13309 (goto-char (or (org-list-get-next-item (point) struct prevs)
13310 (org-list-get-item-end (point) struct)))))))
13312 (defun org-add-log-note (&optional purpose)
13313 "Pop up a window for taking a note, and add this note later at point."
13314 (remove-hook 'post-command-hook 'org-add-log-note)
13315 (setq org-log-note-window-configuration (current-window-configuration))
13316 (delete-other-windows)
13317 (move-marker org-log-note-return-to (point))
13318 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13319 (goto-char org-log-note-marker)
13320 (org-switch-to-buffer-other-window "*Org Note*")
13321 (erase-buffer)
13322 (if (memq org-log-note-how '(time state))
13323 (let (current-prefix-arg) (org-store-log-note))
13324 (let ((org-inhibit-startup t)) (org-mode))
13325 (insert (format "# Insert note for %s.
13326 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13327 (cond
13328 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13329 ((eq org-log-note-purpose 'done) "closed todo item")
13330 ((eq org-log-note-purpose 'state)
13331 (format "state change from \"%s\" to \"%s\""
13332 (or org-log-note-previous-state "")
13333 (or org-log-note-state "")))
13334 ((eq org-log-note-purpose 'reschedule)
13335 "rescheduling")
13336 ((eq org-log-note-purpose 'delschedule)
13337 "no longer scheduled")
13338 ((eq org-log-note-purpose 'redeadline)
13339 "changing deadline")
13340 ((eq org-log-note-purpose 'deldeadline)
13341 "removing deadline")
13342 ((eq org-log-note-purpose 'refile)
13343 "refiling")
13344 ((eq org-log-note-purpose 'note)
13345 "this entry")
13346 (t (error "This should not happen")))))
13347 (if org-log-note-extra (insert org-log-note-extra))
13348 (org-set-local 'org-finish-function 'org-store-log-note)
13349 (run-hooks 'org-log-buffer-setup-hook)))
13351 (defvar org-note-abort nil) ; dynamically scoped
13352 (defun org-store-log-note ()
13353 "Finish taking a log note, and insert it to where it belongs."
13354 (let ((txt (buffer-string)))
13355 (kill-buffer (current-buffer))
13356 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13357 lines ind bul)
13358 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13359 (setq txt (replace-match "" t t txt)))
13360 (if (string-match "\\s-+\\'" txt)
13361 (setq txt (replace-match "" t t txt)))
13362 (setq lines (org-split-string txt "\n"))
13363 (when (and note (string-match "\\S-" note))
13364 (setq note
13365 (org-replace-escapes
13366 note
13367 (list (cons "%u" (user-login-name))
13368 (cons "%U" user-full-name)
13369 (cons "%t" (format-time-string
13370 (org-time-stamp-format 'long 'inactive)
13371 org-log-note-effective-time))
13372 (cons "%T" (format-time-string
13373 (org-time-stamp-format 'long nil)
13374 org-log-note-effective-time))
13375 (cons "%d" (format-time-string
13376 (org-time-stamp-format nil 'inactive)
13377 org-log-note-effective-time))
13378 (cons "%D" (format-time-string
13379 (org-time-stamp-format nil nil)
13380 org-log-note-effective-time))
13381 (cons "%s" (if org-log-note-state
13382 (concat "\"" org-log-note-state "\"")
13383 ""))
13384 (cons "%S" (if org-log-note-previous-state
13385 (concat "\"" org-log-note-previous-state "\"")
13386 "\"\"")))))
13387 (if lines (setq note (concat note " \\\\")))
13388 (push note lines))
13389 (when (or current-prefix-arg org-note-abort)
13390 (when org-log-into-drawer
13391 (org-remove-empty-drawer-at
13392 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13393 org-log-note-marker))
13394 (setq lines nil))
13395 (when lines
13396 (with-current-buffer (marker-buffer org-log-note-marker)
13397 (save-excursion
13398 (goto-char org-log-note-marker)
13399 (move-marker org-log-note-marker nil)
13400 (end-of-line 1)
13401 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13402 (setq ind (save-excursion
13403 (if (ignore-errors (goto-char (org-in-item-p)))
13404 (let ((struct (org-list-struct)))
13405 (org-list-get-ind
13406 (org-list-get-top-point struct) struct))
13407 (skip-chars-backward " \r\t\n")
13408 (cond
13409 ((and (org-at-heading-p)
13410 org-adapt-indentation)
13411 (1+ (org-current-level)))
13412 ((org-at-heading-p) 0)
13413 (t (org-get-indentation))))))
13414 (setq bul (org-list-bullet-string "-"))
13415 (org-indent-line-to ind)
13416 (insert bul (pop lines))
13417 (let ((ind-body (+ (length bul) ind)))
13418 (while lines
13419 (insert "\n")
13420 (org-indent-line-to ind-body)
13421 (insert (pop lines))))
13422 (message "Note stored")
13423 (org-back-to-heading t)
13424 (org-cycle-hide-drawers 'children))
13425 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13426 ;; from within `org-add-log-note' because `buffer-undo-list'
13427 ;; is then modified outside of `org-with-remote-undo'.
13428 (when (eq this-command 'org-agenda-todo)
13429 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13430 ;; Don't add undo information when called from `org-agenda-todo'
13431 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13432 (set-window-configuration org-log-note-window-configuration)
13433 (with-current-buffer (marker-buffer org-log-note-return-to)
13434 (goto-char org-log-note-return-to))
13435 (move-marker org-log-note-return-to nil)
13436 (and org-log-post-message (message "%s" org-log-post-message))))
13438 (defun org-remove-empty-drawer-at (drawer pos)
13439 "Remove an empty drawer DRAWER at position POS.
13440 POS may also be a marker."
13441 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13442 (save-excursion
13443 (save-restriction
13444 (widen)
13445 (goto-char pos)
13446 (if (org-in-regexp
13447 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13448 (replace-match ""))))))
13450 (defvar org-ts-type nil)
13451 (defun org-sparse-tree (&optional arg type)
13452 "Create a sparse tree, prompt for the details.
13453 This command can create sparse trees. You first need to select the type
13454 of match used to create the tree:
13456 t Show all TODO entries.
13457 T Show entries with a specific TODO keyword.
13458 m Show entries selected by a tags/property match.
13459 p Enter a property name and its value (both with completion on existing
13460 names/values) and show entries with that property.
13461 r Show entries matching a regular expression (`/' can be used as well).
13462 b Show deadlines and scheduled items before a date.
13463 a Show deadlines and scheduled items after a date.
13464 d Show deadlines due within `org-deadline-warning-days'.
13465 D Show deadlines and scheduled items between a date range."
13466 (interactive "P")
13467 (let (ans kwd value ts-type)
13468 (setq type (or type org-sparse-tree-default-date-type))
13469 (setq org-ts-type type)
13470 (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"
13471 (cond ((eq type 'all) "all timestamps")
13472 ((eq type 'scheduled) "only scheduled")
13473 ((eq type 'deadline) "only deadline")
13474 ((eq type 'active) "only active timestamps")
13475 ((eq type 'inactive) "only inactive timestamps")
13476 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13477 ((eq type 'closed) "with a closed time-stamp")
13478 (t "scheduled/deadline")))
13479 (setq ans (read-char-exclusive))
13480 (cond
13481 ((equal ans ?c)
13482 (org-sparse-tree
13483 arg (cadr (member type '(scheduled-or-deadline
13484 all scheduled deadline active inactive closed)))))
13485 ((equal ans ?d)
13486 (call-interactively 'org-check-deadlines))
13487 ((equal ans ?b)
13488 (call-interactively 'org-check-before-date))
13489 ((equal ans ?a)
13490 (call-interactively 'org-check-after-date))
13491 ((equal ans ?D)
13492 (call-interactively 'org-check-dates-range))
13493 ((equal ans ?t)
13494 (call-interactively 'org-show-todo-tree))
13495 ((equal ans ?T)
13496 (org-show-todo-tree '(4)))
13497 ((member ans '(?T ?m))
13498 (call-interactively 'org-match-sparse-tree))
13499 ((member ans '(?p ?P))
13500 (setq kwd (org-icompleting-read "Property: "
13501 (mapcar 'list (org-buffer-property-keys))))
13502 (setq value (org-icompleting-read "Value: "
13503 (mapcar 'list (org-property-values kwd))))
13504 (unless (string-match "\\`{.*}\\'" value)
13505 (setq value (concat "\"" value "\"")))
13506 (org-match-sparse-tree arg (concat kwd "=" value)))
13507 ((member ans '(?r ?R ?/))
13508 (call-interactively 'org-occur))
13509 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13511 (defvar org-occur-highlights nil
13512 "List of overlays used for occur matches.")
13513 (make-variable-buffer-local 'org-occur-highlights)
13514 (defvar org-occur-parameters nil
13515 "Parameters of the active org-occur calls.
13516 This is a list, each call to org-occur pushes as cons cell,
13517 containing the regular expression and the callback, onto the list.
13518 The list can contain several entries if `org-occur' has been called
13519 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13520 will only contain one set of parameters. When the highlights are
13521 removed (for example with `C-c C-c', or with the next edit (depending
13522 on `org-remove-highlights-with-change'), this variable is emptied
13523 as well.")
13524 (make-variable-buffer-local 'org-occur-parameters)
13526 (defun org-occur (regexp &optional keep-previous callback)
13527 "Make a compact tree which shows all matches of REGEXP.
13528 The tree will show the lines where the regexp matches, and all higher
13529 headlines above the match. It will also show the heading after the match,
13530 to make sure editing the matching entry is easy.
13531 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13532 call to `org-occur' will be kept, to allow stacking of calls to this
13533 command.
13534 If CALLBACK is non-nil, it is a function which is called to confirm
13535 that the match should indeed be shown."
13536 (interactive "sRegexp: \nP")
13537 (when (equal regexp "")
13538 (user-error "Regexp cannot be empty"))
13539 (unless keep-previous
13540 (org-remove-occur-highlights nil nil t))
13541 (push (cons regexp callback) org-occur-parameters)
13542 (let ((cnt 0))
13543 (save-excursion
13544 (goto-char (point-min))
13545 (if (or (not keep-previous) ; do not want to keep
13546 (not org-occur-highlights)) ; no previous matches
13547 ;; hide everything
13548 (org-overview))
13549 (while (re-search-forward regexp nil t)
13550 (when (or (not callback)
13551 (save-match-data (funcall callback)))
13552 (setq cnt (1+ cnt))
13553 (when org-highlight-sparse-tree-matches
13554 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13555 (org-show-context 'occur-tree))))
13556 (when org-remove-highlights-with-change
13557 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13558 nil 'local))
13559 (unless org-sparse-tree-open-archived-trees
13560 (org-hide-archived-subtrees (point-min) (point-max)))
13561 (run-hooks 'org-occur-hook)
13562 (if (org-called-interactively-p 'interactive)
13563 (message "%d match(es) for regexp %s" cnt regexp))
13564 cnt))
13566 (defun org-occur-next-match (&optional n reset)
13567 "Function for `next-error-function' to find sparse tree matches.
13568 N is the number of matches to move, when negative move backwards.
13569 RESET is entirely ignored - this function always goes back to the
13570 starting point when no match is found."
13571 (let* ((limit (if (< n 0) (point-min) (point-max)))
13572 (search-func (if (< n 0)
13573 'previous-single-char-property-change
13574 'next-single-char-property-change))
13575 (n (abs n))
13576 (pos (point))
13578 (catch 'exit
13579 (while (setq p1 (funcall search-func (point) 'org-type))
13580 (when (equal p1 limit)
13581 (goto-char pos)
13582 (error "No more matches"))
13583 (when (equal (get-char-property p1 'org-type) 'org-occur)
13584 (setq n (1- n))
13585 (when (= n 0)
13586 (goto-char p1)
13587 (throw 'exit (point))))
13588 (goto-char p1))
13589 (goto-char p1)
13590 (error "No more matches"))))
13592 (defun org-show-context (&optional key)
13593 "Make sure point and context are visible.
13594 How much context is shown depends upon the variables
13595 `org-show-hierarchy-above', `org-show-following-heading',
13596 `org-show-entry-below' and `org-show-siblings'."
13597 (let ((heading-p (org-at-heading-p t))
13598 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13599 (following-p (org-get-alist-option org-show-following-heading key))
13600 (entry-p (org-get-alist-option org-show-entry-below key))
13601 (siblings-p (org-get-alist-option org-show-siblings key)))
13602 ;; Show heading or entry text
13603 (if (and heading-p (not entry-p))
13604 (org-flag-heading nil) ; only show the heading
13605 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13606 (org-show-hidden-entry))) ; show entire entry
13607 (when following-p
13608 ;; Show next sibling, or heading below text
13609 (save-excursion
13610 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13611 (org-flag-heading nil))))
13612 (when siblings-p (org-show-siblings))
13613 (when hierarchy-p
13614 ;; show all higher headings, possibly with siblings
13615 (save-excursion
13616 (while (and (condition-case nil
13617 (progn (org-up-heading-all 1) t)
13618 (error nil))
13619 (not (bobp)))
13620 (org-flag-heading nil)
13621 (when siblings-p (org-show-siblings)))))
13622 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13624 (defvar org-reveal-start-hook nil
13625 "Hook run before revealing a location.")
13627 (defun org-reveal (&optional siblings)
13628 "Show current entry, hierarchy above it, and the following headline.
13629 This can be used to show a consistent set of context around locations
13630 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13631 not t for the search context.
13633 With optional argument SIBLINGS, on each level of the hierarchy all
13634 siblings are shown. This repairs the tree structure to what it would
13635 look like when opened with hierarchical calls to `org-cycle'.
13636 With double optional argument \\[universal-argument] \\[universal-argument], \
13637 go to the parent and show the
13638 entire tree."
13639 (interactive "P")
13640 (run-hooks 'org-reveal-start-hook)
13641 (let ((org-show-hierarchy-above t)
13642 (org-show-following-heading t)
13643 (org-show-siblings (if siblings t org-show-siblings)))
13644 (org-show-context nil))
13645 (when (equal siblings '(16))
13646 (save-excursion
13647 (when (org-up-heading-safe)
13648 (org-show-subtree)
13649 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13651 (defun org-highlight-new-match (beg end)
13652 "Highlight from BEG to END and mark the highlight is an occur headline."
13653 (let ((ov (make-overlay beg end)))
13654 (overlay-put ov 'face 'secondary-selection)
13655 (overlay-put ov 'org-type 'org-occur)
13656 (push ov org-occur-highlights)))
13658 (defun org-remove-occur-highlights (&optional beg end noremove)
13659 "Remove the occur highlights from the buffer.
13660 BEG and END are ignored. If NOREMOVE is nil, remove this function
13661 from the `before-change-functions' in the current buffer."
13662 (interactive)
13663 (unless org-inhibit-highlight-removal
13664 (mapc 'delete-overlay org-occur-highlights)
13665 (setq org-occur-highlights nil)
13666 (setq org-occur-parameters nil)
13667 (unless noremove
13668 (remove-hook 'before-change-functions
13669 'org-remove-occur-highlights 'local))))
13671 ;;;; Priorities
13673 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13674 "Regular expression matching the priority indicator.")
13676 (defvar org-remove-priority-next-time nil)
13678 (defun org-priority-up ()
13679 "Increase the priority of the current item."
13680 (interactive)
13681 (org-priority 'up))
13683 (defun org-priority-down ()
13684 "Decrease the priority of the current item."
13685 (interactive)
13686 (org-priority 'down))
13688 (defun org-priority (&optional action show)
13689 "Change the priority of an item.
13690 ACTION can be `set', `up', `down', or a character."
13691 (interactive "P")
13692 (if (equal action '(4))
13693 (org-show-priority)
13694 (unless org-enable-priority-commands
13695 (user-error "Priority commands are disabled"))
13696 (setq action (or action 'set))
13697 (let (current new news have remove)
13698 (save-excursion
13699 (org-back-to-heading t)
13700 (if (looking-at org-priority-regexp)
13701 (setq current (string-to-char (match-string 2))
13702 have t))
13703 (cond
13704 ((eq action 'remove)
13705 (setq remove t new ?\ ))
13706 ((or (eq action 'set)
13707 (if (featurep 'xemacs) (characterp action) (integerp action)))
13708 (if (not (eq action 'set))
13709 (setq new action)
13710 (message "Priority %c-%c, SPC to remove: "
13711 org-highest-priority org-lowest-priority)
13712 (save-match-data
13713 (setq new (read-char-exclusive))))
13714 (if (and (= (upcase org-highest-priority) org-highest-priority)
13715 (= (upcase org-lowest-priority) org-lowest-priority))
13716 (setq new (upcase new)))
13717 (cond ((equal new ?\ ) (setq remove t))
13718 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13719 (user-error "Priority must be between `%c' and `%c'"
13720 org-highest-priority org-lowest-priority))))
13721 ((eq action 'up)
13722 (setq new (if have
13723 (1- current) ; normal cycling
13724 ;; last priority was empty
13725 (if (eq last-command this-command)
13726 org-lowest-priority ; wrap around empty to lowest
13727 ;; default
13728 (if org-priority-start-cycle-with-default
13729 org-default-priority
13730 (1- org-default-priority))))))
13731 ((eq action 'down)
13732 (setq new (if have
13733 (1+ current) ; normal cycling
13734 ;; last priority was empty
13735 (if (eq last-command this-command)
13736 org-highest-priority ; wrap around empty to highest
13737 ;; default
13738 (if org-priority-start-cycle-with-default
13739 org-default-priority
13740 (1+ org-default-priority))))))
13741 (t (user-error "Invalid action")))
13742 (if (or (< (upcase new) org-highest-priority)
13743 (> (upcase new) org-lowest-priority))
13744 (if (and (memq action '(up down))
13745 (not have) (not (eq last-command this-command)))
13746 ;; `new' is from default priority
13747 (error
13748 "The default can not be set, see `org-default-priority' why")
13749 ;; normal cycling: `new' is beyond highest/lowest priority
13750 ;; and is wrapped around to the empty priority
13751 (setq remove t)))
13752 (setq news (format "%c" new))
13753 (if have
13754 (if remove
13755 (replace-match "" t t nil 1)
13756 (replace-match news t t nil 2))
13757 (if remove
13758 (user-error "No priority cookie found in line")
13759 (let ((case-fold-search nil))
13760 (looking-at org-todo-line-regexp))
13761 (if (match-end 2)
13762 (progn
13763 (goto-char (match-end 2))
13764 (insert " [#" news "]"))
13765 (goto-char (match-beginning 3))
13766 (insert "[#" news "] "))))
13767 (org-preserve-lc (org-set-tags nil 'align)))
13768 (if remove
13769 (message "Priority removed")
13770 (message "Priority of current item set to %s" news)))))
13772 (defun org-show-priority ()
13773 "Show the priority of the current item.
13774 This priority is composed of the main priority given with the [#A] cookies,
13775 and by additional input from the age of a schedules or deadline entry."
13776 (interactive)
13777 (let ((pri (if (eq major-mode 'org-agenda-mode)
13778 (org-get-at-bol 'priority)
13779 (save-excursion
13780 (save-match-data
13781 (beginning-of-line)
13782 (and (looking-at org-heading-regexp)
13783 (org-get-priority (match-string 0))))))))
13784 (message "Priority is %d" (if pri pri -1000))))
13786 (defun org-get-priority (s)
13787 "Find priority cookie and return priority."
13788 (save-match-data
13789 (if (functionp org-get-priority-function)
13790 (funcall org-get-priority-function)
13791 (if (not (string-match org-priority-regexp s))
13792 (* 1000 (- org-lowest-priority org-default-priority))
13793 (* 1000 (- org-lowest-priority
13794 (string-to-char (match-string 2 s))))))))
13796 ;;;; Tags
13798 (defvar org-agenda-archives-mode)
13799 (defvar org-map-continue-from nil
13800 "Position from where mapping should continue.
13801 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13803 (defvar org-scanner-tags nil
13804 "The current tag list while the tags scanner is running.")
13805 (defvar org-trust-scanner-tags nil
13806 "Should `org-get-tags-at' use the tags for the scanner.
13807 This is for internal dynamical scoping only.
13808 When this is non-nil, the function `org-get-tags-at' will return the value
13809 of `org-scanner-tags' instead of building the list by itself. This
13810 can lead to large speed-ups when the tags scanner is used in a file with
13811 many entries, and when the list of tags is retrieved, for example to
13812 obtain a list of properties. Building the tags list for each entry in such
13813 a file becomes an N^2 operation - but with this variable set, it scales
13814 as N.")
13816 (defun org-scan-tags (action matcher todo-only &optional start-level)
13817 "Sca headline tags with inheritance and produce output ACTION.
13819 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13820 or `agenda' to produce an entry list for an agenda view. It can also be
13821 a Lisp form or a function that should be called at each matched headline, in
13822 this case the return value is a list of all return values from these calls.
13824 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13825 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13826 only lines with a not-done TODO keyword are included in the output.
13827 This should be the same variable that was scoped into
13828 and set by `org-make-tags-matcher' when it constructed MATCHER.
13830 START-LEVEL can be a string with asterisks, reducing the scope to
13831 headlines matching this string."
13832 (require 'org-agenda)
13833 (let* ((re (concat "^"
13834 (if start-level
13835 ;; Get the correct level to match
13836 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13837 org-outline-regexp)
13838 " *\\(\\<\\("
13839 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13840 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13841 (props (list 'face 'default
13842 'done-face 'org-agenda-done
13843 'undone-face 'default
13844 'mouse-face 'highlight
13845 'org-not-done-regexp org-not-done-regexp
13846 'org-todo-regexp org-todo-regexp
13847 'org-complex-heading-regexp org-complex-heading-regexp
13848 'help-echo
13849 (format "mouse-2 or RET jump to org file %s"
13850 (abbreviate-file-name
13851 (or (buffer-file-name (buffer-base-buffer))
13852 (buffer-name (buffer-base-buffer)))))))
13853 (org-map-continue-from nil)
13854 lspos tags tags-list
13855 (tags-alist (list (cons 0 org-file-tags)))
13856 (llast 0) rtn rtn1 level category i txt
13857 todo marker entry priority)
13858 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13859 (setq action (list 'lambda nil action)))
13860 (save-excursion
13861 (goto-char (point-min))
13862 (when (eq action 'sparse-tree)
13863 (org-overview)
13864 (org-remove-occur-highlights))
13865 (while (let (case-fold-search)
13866 (re-search-forward re nil t))
13867 (setq org-map-continue-from nil)
13868 (catch :skip
13869 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13870 tags (if (match-end 4) (org-match-string-no-properties 4)))
13871 (goto-char (setq lspos (match-beginning 0)))
13872 (setq level (org-reduced-level (org-outline-level))
13873 category (org-get-category))
13874 (setq i llast llast level)
13875 ;; remove tag lists from same and sublevels
13876 (while (>= i level)
13877 (when (setq entry (assoc i tags-alist))
13878 (setq tags-alist (delete entry tags-alist)))
13879 (setq i (1- i)))
13880 ;; add the next tags
13881 (when tags
13882 (setq tags (org-split-string tags ":")
13883 tags-alist
13884 (cons (cons level tags) tags-alist)))
13885 ;; compile tags for current headline
13886 (setq tags-list
13887 (if org-use-tag-inheritance
13888 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13889 tags)
13890 org-scanner-tags tags-list)
13891 (when org-use-tag-inheritance
13892 (setcdr (car tags-alist)
13893 (mapcar (lambda (x)
13894 (setq x (copy-sequence x))
13895 (org-add-prop-inherited x))
13896 (cdar tags-alist))))
13897 (when (and tags org-use-tag-inheritance
13898 (or (not (eq t org-use-tag-inheritance))
13899 org-tags-exclude-from-inheritance))
13900 ;; selective inheritance, remove uninherited ones
13901 (setcdr (car tags-alist)
13902 (org-remove-uninherited-tags (cdar tags-alist))))
13903 (when (and
13905 ;; eval matcher only when the todo condition is OK
13906 (and (or (not todo-only) (member todo org-not-done-keywords))
13907 (let ((case-fold-search t) (org-trust-scanner-tags t))
13908 (eval matcher)))
13910 ;; Call the skipper, but return t if it does not skip,
13911 ;; so that the `and' form continues evaluating
13912 (progn
13913 (unless (eq action 'sparse-tree) (org-agenda-skip))
13916 ;; Check if timestamps are deselecting this entry
13917 (or (not todo-only)
13918 (and (member todo org-not-done-keywords)
13919 (or (not org-agenda-tags-todo-honor-ignore-options)
13920 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13922 ;; select this headline
13923 (cond
13924 ((eq action 'sparse-tree)
13925 (and org-highlight-sparse-tree-matches
13926 (org-get-heading) (match-end 0)
13927 (org-highlight-new-match
13928 (match-beginning 1) (match-end 1)))
13929 (org-show-context 'tags-tree))
13930 ((eq action 'agenda)
13931 (setq txt (org-agenda-format-item
13933 (concat
13934 (if (eq org-tags-match-list-sublevels 'indented)
13935 (make-string (1- level) ?.) "")
13936 (org-get-heading))
13937 level category
13938 tags-list)
13939 priority (org-get-priority txt))
13940 (goto-char lspos)
13941 (setq marker (org-agenda-new-marker))
13942 (org-add-props txt props
13943 'org-marker marker 'org-hd-marker marker 'org-category category
13944 'todo-state todo
13945 'priority priority 'type "tagsmatch")
13946 (push txt rtn))
13947 ((functionp action)
13948 (setq org-map-continue-from nil)
13949 (save-excursion
13950 (setq rtn1 (funcall action))
13951 (push rtn1 rtn)))
13952 (t (user-error "Invalid action")))
13954 ;; if we are to skip sublevels, jump to end of subtree
13955 (unless org-tags-match-list-sublevels
13956 (org-end-of-subtree t)
13957 (backward-char 1))))
13958 ;; Get the correct position from where to continue
13959 (if org-map-continue-from
13960 (goto-char org-map-continue-from)
13961 (and (= (point) lspos) (end-of-line 1)))))
13962 (when (and (eq action 'sparse-tree)
13963 (not org-sparse-tree-open-archived-trees))
13964 (org-hide-archived-subtrees (point-min) (point-max)))
13965 (nreverse rtn)))
13967 (defun org-remove-uninherited-tags (tags)
13968 "Remove all tags that are not inherited from the list TAGS."
13969 (cond
13970 ((eq org-use-tag-inheritance t)
13971 (if org-tags-exclude-from-inheritance
13972 (org-delete-all org-tags-exclude-from-inheritance tags)
13973 tags))
13974 ((not org-use-tag-inheritance) nil)
13975 ((stringp org-use-tag-inheritance)
13976 (delq nil (mapcar
13977 (lambda (x)
13978 (if (and (string-match org-use-tag-inheritance x)
13979 (not (member x org-tags-exclude-from-inheritance)))
13980 x nil))
13981 tags)))
13982 ((listp org-use-tag-inheritance)
13983 (delq nil (mapcar
13984 (lambda (x)
13985 (if (member x org-use-tag-inheritance) x nil))
13986 tags)))))
13988 (defun org-match-sparse-tree (&optional todo-only match)
13989 "Create a sparse tree according to tags string MATCH.
13990 MATCH can contain positive and negative selection of tags, like
13991 \"+WORK+URGENT-WITHBOSS\".
13992 If optional argument TODO-ONLY is non-nil, only select lines that are
13993 also TODO lines."
13994 (interactive "P")
13995 (org-agenda-prepare-buffers (list (current-buffer)))
13996 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13998 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14000 (defvar org-cached-props nil)
14001 (defun org-cached-entry-get (pom property)
14002 (if (or (eq t org-use-property-inheritance)
14003 (and (stringp org-use-property-inheritance)
14004 (string-match org-use-property-inheritance property))
14005 (and (listp org-use-property-inheritance)
14006 (member property org-use-property-inheritance)))
14007 ;; Caching is not possible, check it directly
14008 (org-entry-get pom property 'inherit)
14009 ;; Get all properties, so that we can do complicated checks easily
14010 (cdr (assoc property (or org-cached-props
14011 (setq org-cached-props
14012 (org-entry-properties pom)))))))
14014 (defun org-global-tags-completion-table (&optional files)
14015 "Return the list of all tags in all agenda buffer/files.
14016 Optional FILES argument is a list of files which can be used
14017 instead of the agenda files."
14018 (save-excursion
14019 (org-uniquify
14020 (delq nil
14021 (apply 'append
14022 (mapcar
14023 (lambda (file)
14024 (set-buffer (find-file-noselect file))
14025 (append (org-get-buffer-tags)
14026 (mapcar (lambda (x) (if (stringp (car-safe x))
14027 (list (car-safe x)) nil))
14028 org-tag-alist)))
14029 (if (and files (car files))
14030 files
14031 (org-agenda-files))))))))
14033 (defun org-make-tags-matcher (match)
14034 "Create the TAGS/TODO matcher form for the selection string MATCH.
14036 The variable `todo-only' is scoped dynamically into this function.
14037 It will be set to t if the matcher restricts matching to TODO entries,
14038 otherwise will not be touched.
14040 Returns a cons of the selection string MATCH and the constructed
14041 lisp form implementing the matcher. The matcher is to be evaluated
14042 at an Org entry, with point on the headline, and returns t if the
14043 entry matches the selection string MATCH. The returned lisp form
14044 references two variables with information about the entry, which
14045 must be bound around the form's evaluation: todo, the TODO keyword
14046 at the entry (or nil of none); and tags-list, the list of all tags
14047 at the entry including inherited ones. Additionally, the category
14048 of the entry (if any) must be specified as the text property
14049 'org-category on the headline.
14051 See also `org-scan-tags'.
14053 (declare (special todo-only))
14054 (unless (boundp 'todo-only)
14055 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14056 (unless match
14057 ;; Get a new match request, with completion against the global
14058 ;; tags table and the local tags in current buffer
14059 (let ((org-last-tags-completion-table
14060 (org-uniquify
14061 (delq nil (append (org-get-buffer-tags)
14062 (org-global-tags-completion-table))))))
14063 (setq match (org-completing-read-no-i
14064 "Match: " 'org-tags-completion-function nil nil nil
14065 'org-tags-history))))
14067 ;; Parse the string and create a lisp form
14068 (let ((match0 match)
14069 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14070 minus tag mm
14071 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14072 orterms term orlist re-p str-p level-p level-op time-p
14073 prop-p pn pv po gv rest (start 0) (ss 0))
14074 ;; Expand group tags
14075 (setq match (org-tags-expand match))
14077 ;; Check if there is a TODO part of this match, which would be the
14078 ;; part after a "/". TO make sure that this slash is not part of
14079 ;; a property value to be matched against, we also check that there
14080 ;; is no " after that slash.
14081 ;; First, find the last slash
14082 (while (string-match "/+" match ss)
14083 (setq start (match-beginning 0) ss (match-end 0)))
14084 (if (and (string-match "/+" match start)
14085 (not (save-match-data (string-match "\"" match start))))
14086 ;; match contains also a todo-matching request
14087 (progn
14088 (setq tagsmatch (substring match 0 (match-beginning 0))
14089 todomatch (substring match (match-end 0)))
14090 (if (string-match "^!" todomatch)
14091 (setq todo-only t todomatch (substring todomatch 1)))
14092 (if (string-match "^\\s-*$" todomatch)
14093 (setq todomatch nil)))
14094 ;; only matching tags
14095 (setq tagsmatch match todomatch nil))
14097 ;; Make the tags matcher
14098 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14099 (setq tagsmatcher t)
14100 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14101 (while (setq term (pop orterms))
14102 (while (and (equal (substring term -1) "\\") orterms)
14103 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14104 (while (string-match re term)
14105 (setq rest (substring term (match-end 0))
14106 minus (and (match-end 1)
14107 (equal (match-string 1 term) "-"))
14108 tag (save-match-data (replace-regexp-in-string
14109 "\\\\-" "-"
14110 (match-string 2 term)))
14111 re-p (equal (string-to-char tag) ?{)
14112 level-p (match-end 4)
14113 prop-p (match-end 5)
14114 mm (cond
14115 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14116 (level-p
14117 (setq level-op (org-op-to-function (match-string 3 term)))
14118 `(,level-op level ,(string-to-number
14119 (match-string 4 term))))
14120 (prop-p
14121 (setq pn (match-string 5 term)
14122 po (match-string 6 term)
14123 pv (match-string 7 term)
14124 re-p (equal (string-to-char pv) ?{)
14125 str-p (equal (string-to-char pv) ?\")
14126 time-p (save-match-data
14127 (string-match "^\"[[<].*[]>]\"$" pv))
14128 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14129 (if time-p (setq pv (org-matcher-time pv)))
14130 (setq po (org-op-to-function po (if time-p 'time str-p)))
14131 (cond
14132 ((equal pn "CATEGORY")
14133 (setq gv '(get-text-property (point) 'org-category)))
14134 ((equal pn "TODO")
14135 (setq gv 'todo))
14137 (setq gv `(org-cached-entry-get nil ,pn))))
14138 (if re-p
14139 (if (eq po 'org<>)
14140 `(not (string-match ,pv (or ,gv "")))
14141 `(string-match ,pv (or ,gv "")))
14142 (if str-p
14143 `(,po (or ,gv "") ,pv)
14144 `(,po (string-to-number (or ,gv ""))
14145 ,(string-to-number pv) ))))
14146 (t `(member ,tag tags-list)))
14147 mm (if minus (list 'not mm) mm)
14148 term rest)
14149 (push mm tagsmatcher))
14150 (push (if (> (length tagsmatcher) 1)
14151 (cons 'and tagsmatcher)
14152 (car tagsmatcher))
14153 orlist)
14154 (setq tagsmatcher nil))
14155 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14156 (setq tagsmatcher
14157 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14158 ;; Make the todo matcher
14159 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14160 (setq todomatcher t)
14161 (setq orterms (org-split-string todomatch "|") orlist nil)
14162 (while (setq term (pop orterms))
14163 (while (string-match re term)
14164 (setq minus (and (match-end 1)
14165 (equal (match-string 1 term) "-"))
14166 kwd (match-string 2 term)
14167 re-p (equal (string-to-char kwd) ?{)
14168 term (substring term (match-end 0))
14169 mm (if re-p
14170 `(string-match ,(substring kwd 1 -1) todo)
14171 (list 'equal 'todo kwd))
14172 mm (if minus (list 'not mm) mm))
14173 (push mm todomatcher))
14174 (push (if (> (length todomatcher) 1)
14175 (cons 'and todomatcher)
14176 (car todomatcher))
14177 orlist)
14178 (setq todomatcher nil))
14179 (setq todomatcher (if (> (length orlist) 1)
14180 (cons 'or orlist) (car orlist))))
14182 ;; Return the string and lisp forms of the matcher
14183 (setq matcher (if todomatcher
14184 (list 'and tagsmatcher todomatcher)
14185 tagsmatcher))
14186 (when todo-only
14187 (setq matcher (list 'and '(member todo org-not-done-keywords)
14188 matcher)))
14189 (cons match0 matcher)))
14191 (defun org-tags-expand (match &optional single-as-list downcased)
14192 "Expand group tags in MATCH.
14194 This replaces every group tag in MATCH with a regexp tag search.
14195 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14196 will be replaced like this:
14198 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14199 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14200 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14202 Replacing by a regexp preserves the structure of the match.
14203 E.g., this expansion
14205 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14207 will match anything tagged with \"Lab\" and \"Home\", or tagged
14208 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14210 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14211 assumed to be a single group tag, and the function will return
14212 the list of tags in this group.
14214 When DOWNCASE is non-nil, expand downcased TAGS."
14215 (if org-group-tags
14216 (let* ((case-fold-search t)
14217 (stable org-mode-syntax-table)
14218 (tal (or org-tag-groups-alist-for-agenda
14219 org-tag-groups-alist))
14220 (tal (if downcased
14221 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14222 (tml (mapcar 'car tal))
14223 (rtnmatch match) rpl)
14224 ;; @ and _ are allowed as word-components in tags
14225 (modify-syntax-entry ?@ "w" stable)
14226 (modify-syntax-entry ?_ "w" stable)
14227 (while (and tml
14228 (with-syntax-table stable
14229 (string-match
14230 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14231 (regexp-opt tml) "\\>\\)") rtnmatch)))
14232 (let* ((dir (match-string 1 rtnmatch))
14233 (tag (match-string 2 rtnmatch))
14234 (tag (if downcased (downcase tag) tag)))
14235 (setq tml (delete tag tml))
14236 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14237 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14238 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14239 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14240 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14241 (if single-as-list
14242 (or (reverse rpl) (list rtnmatch))
14243 rtnmatch))
14244 (if single-as-list (list (if downcased (downcase match) match))
14245 match)))
14247 (defun org-op-to-function (op &optional stringp)
14248 "Turn an operator into the appropriate function."
14249 (setq op
14250 (cond
14251 ((equal op "<" ) '(< string< org-time<))
14252 ((equal op ">" ) '(> org-string> org-time>))
14253 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14254 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14255 ((member op '("=" "==")) '(= string= org-time=))
14256 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14257 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14259 (defun org<> (a b) (not (= a b)))
14260 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14261 (defun org-string>= (a b) (not (string< a b)))
14262 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14263 (defun org-string<> (a b) (not (string= a b)))
14264 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14265 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14266 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14267 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14268 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14269 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14270 (defun org-2ft (s)
14271 "Convert S to a floating point time.
14272 If S is already a number, just return it. If it is a string, parse
14273 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14274 (cond
14275 ((numberp s) s)
14276 ((stringp s)
14277 (condition-case nil
14278 (float-time (apply 'encode-time (org-parse-time-string s)))
14279 (error 0.)))
14280 (t 0.)))
14282 (defun org-time-today ()
14283 "Time in seconds today at 0:00.
14284 Returns the float number of seconds since the beginning of the
14285 epoch to the beginning of today (00:00)."
14286 (float-time (apply 'encode-time
14287 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14289 (defun org-matcher-time (s)
14290 "Interpret a time comparison value."
14291 (save-match-data
14292 (cond
14293 ((string= s "<now>") (float-time))
14294 ((string= s "<today>") (org-time-today))
14295 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14296 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14297 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14298 (+ (org-time-today)
14299 (* (string-to-number (match-string 1 s))
14300 (cdr (assoc (match-string 2 s)
14301 '(("d" . 86400.0) ("w" . 604800.0)
14302 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14303 (t (org-2ft s)))))
14305 (defun org-match-any-p (re list)
14306 "Does re match any element of list?"
14307 (setq list (mapcar (lambda (x) (string-match re x)) list))
14308 (delq nil list))
14310 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14311 (defvar org-tags-overlay (make-overlay 1 1))
14312 (org-detach-overlay org-tags-overlay)
14314 (defun org-get-local-tags-at (&optional pos)
14315 "Get a list of tags defined in the current headline."
14316 (org-get-tags-at pos 'local))
14318 (defun org-get-local-tags ()
14319 "Get a list of tags defined in the current headline."
14320 (org-get-tags-at nil 'local))
14322 (defun org-get-tags-at (&optional pos local)
14323 "Get a list of all headline tags applicable at POS.
14324 POS defaults to point. If tags are inherited, the list contains
14325 the targets in the same sequence as the headlines appear, i.e.
14326 the tags of the current headline come last.
14327 When LOCAL is non-nil, only return tags from the current headline,
14328 ignore inherited ones."
14329 (interactive)
14330 (if (and org-trust-scanner-tags
14331 (or (not pos) (equal pos (point)))
14332 (not local))
14333 org-scanner-tags
14334 (let (tags ltags lastpos parent)
14335 (save-excursion
14336 (save-restriction
14337 (widen)
14338 (goto-char (or pos (point)))
14339 (save-match-data
14340 (catch 'done
14341 (condition-case nil
14342 (progn
14343 (org-back-to-heading t)
14344 (while (not (equal lastpos (point)))
14345 (setq lastpos (point))
14346 (when (looking-at
14347 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14348 (setq ltags (org-split-string
14349 (org-match-string-no-properties 1) ":"))
14350 (when parent
14351 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14352 (setq tags (append
14353 (if parent
14354 (org-remove-uninherited-tags ltags)
14355 ltags)
14356 tags)))
14357 (or org-use-tag-inheritance (throw 'done t))
14358 (if local (throw 'done t))
14359 (or (org-up-heading-safe) (error nil))
14360 (setq parent t)))
14361 (error nil)))))
14362 (if local
14363 tags
14364 (reverse (delete-dups
14365 (reverse (append
14366 (org-remove-uninherited-tags
14367 org-file-tags) tags)))))))))
14369 (defun org-add-prop-inherited (s)
14370 (add-text-properties 0 (length s) '(inherited t) s)
14373 (defun org-toggle-tag (tag &optional onoff)
14374 "Toggle the tag TAG for the current line.
14375 If ONOFF is `on' or `off', don't toggle but set to this state."
14376 (let (res current)
14377 (save-excursion
14378 (org-back-to-heading t)
14379 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14380 (point-at-eol) t)
14381 (progn
14382 (setq current (match-string 1))
14383 (replace-match ""))
14384 (setq current ""))
14385 (setq current (nreverse (org-split-string current ":")))
14386 (cond
14387 ((eq onoff 'on)
14388 (setq res t)
14389 (or (member tag current) (push tag current)))
14390 ((eq onoff 'off)
14391 (or (not (member tag current)) (setq current (delete tag current))))
14392 (t (if (member tag current)
14393 (setq current (delete tag current))
14394 (setq res t)
14395 (push tag current))))
14396 (end-of-line 1)
14397 (if current
14398 (progn
14399 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14400 (org-set-tags nil t))
14401 (delete-horizontal-space))
14402 (run-hooks 'org-after-tags-change-hook))
14403 res))
14405 (defun org-align-tags-here (to-col)
14406 ;; Assumes that this is a headline
14407 "Align tags on the current headline to TO-COL."
14408 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14409 (beginning-of-line 1)
14410 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14411 (< pos (match-beginning 2)))
14412 (progn
14413 (setq tags-l (- (match-end 2) (match-beginning 2)))
14414 (goto-char (match-beginning 1))
14415 (insert " ")
14416 (delete-region (point) (1+ (match-beginning 2)))
14417 (setq ncol (max (current-column)
14418 (1+ col)
14419 (if (> to-col 0)
14420 to-col
14421 (- (abs to-col) tags-l))))
14422 (setq p (point))
14423 (insert (make-string (- ncol (current-column)) ?\ ))
14424 (setq ncol (current-column))
14425 (when indent-tabs-mode (tabify p (point-at-eol)))
14426 (org-move-to-column (min ncol col)))
14427 (goto-char pos))))
14429 (defun org-set-tags-command (&optional arg just-align)
14430 "Call the set-tags command for the current entry."
14431 (interactive "P")
14432 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14433 (org-set-tags arg just-align)
14434 (save-excursion
14435 (unless (and (org-region-active-p)
14436 org-loop-over-headlines-in-active-region)
14437 (org-back-to-heading t))
14438 (org-set-tags arg just-align))))
14440 (defun org-set-tags-to (data)
14441 "Set the tags of the current entry to DATA, replacing the current tags.
14442 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14443 If DATA is nil or the empty string, any tags will be removed."
14444 (interactive "sTags: ")
14445 (setq data
14446 (cond
14447 ((eq data nil) "")
14448 ((equal data "") "")
14449 ((stringp data)
14450 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14451 ":"))
14452 ((listp data)
14453 (concat ":" (mapconcat 'identity data ":") ":"))))
14454 (when data
14455 (save-excursion
14456 (org-back-to-heading t)
14457 (when (looking-at org-complex-heading-regexp)
14458 (if (match-end 5)
14459 (progn
14460 (goto-char (match-beginning 5))
14461 (insert data)
14462 (delete-region (point) (point-at-eol))
14463 (org-set-tags nil 'align))
14464 (goto-char (point-at-eol))
14465 (insert " " data)
14466 (org-set-tags nil 'align)))
14467 (beginning-of-line 1)
14468 (if (looking-at ".*?\\([ \t]+\\)$")
14469 (delete-region (match-beginning 1) (match-end 1))))))
14471 (defun org-align-all-tags ()
14472 "Align the tags i all headings."
14473 (interactive)
14474 (save-excursion
14475 (or (ignore-errors (org-back-to-heading t))
14476 (outline-next-heading))
14477 (if (org-at-heading-p)
14478 (org-set-tags t)
14479 (message "No headings"))))
14481 (defvar org-indent-indentation-per-level)
14482 (defun org-set-tags (&optional arg just-align)
14483 "Set the tags for the current headline.
14484 With prefix ARG, realign all tags in headings in the current buffer.
14485 When JUST-ALIGN is non-nil, only align tags."
14486 (interactive "P")
14487 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14488 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14489 'region-start-level 'region))
14490 org-loop-over-headlines-in-active-region)
14491 (org-map-entries
14492 ;; We don't use ARG and JUST-ALIGN here because these args
14493 ;; are not useful when looping over headlines.
14494 `(org-set-tags)
14495 org-loop-over-headlines-in-active-region
14496 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14497 (let* ((re org-outline-regexp-bol)
14498 (current (unless arg (org-get-tags-string)))
14499 (col (current-column))
14500 (org-setting-tags t)
14501 table current-tags inherited-tags ; computed below when needed
14502 tags p0 c0 c1 rpl di tc level)
14503 (if arg
14504 (save-excursion
14505 (goto-char (point-min))
14506 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14507 (while (re-search-forward re nil t)
14508 (org-set-tags nil t)
14509 (end-of-line 1)))
14510 (message "All tags realigned to column %d" org-tags-column))
14511 (if just-align
14512 (setq tags current)
14513 ;; Get a new set of tags from the user
14514 (save-excursion
14515 (setq table (append org-tag-persistent-alist
14516 (or org-tag-alist (org-get-buffer-tags))
14517 (and
14518 org-complete-tags-always-offer-all-agenda-tags
14519 (org-global-tags-completion-table
14520 (org-agenda-files))))
14521 org-last-tags-completion-table table
14522 current-tags (org-split-string current ":")
14523 inherited-tags (nreverse
14524 (nthcdr (length current-tags)
14525 (nreverse (org-get-tags-at))))
14526 tags
14527 (if (or (eq t org-use-fast-tag-selection)
14528 (and org-use-fast-tag-selection
14529 (delq nil (mapcar 'cdr table))))
14530 (org-fast-tag-selection
14531 current-tags inherited-tags table
14532 (if org-fast-tag-selection-include-todo
14533 org-todo-key-alist))
14534 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14535 (org-trim
14536 (org-icompleting-read "Tags: "
14537 'org-tags-completion-function
14538 nil nil current 'org-tags-history))))))
14539 (while (string-match "[-+&]+" tags)
14540 ;; No boolean logic, just a list
14541 (setq tags (replace-match ":" t t tags))))
14543 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14545 (if org-tags-sort-function
14546 (setq tags (mapconcat 'identity
14547 (sort (org-split-string
14548 tags (org-re "[^[:alnum:]_@#%]+"))
14549 org-tags-sort-function) ":")))
14551 (if (string-match "\\`[\t ]*\\'" tags)
14552 (setq tags "")
14553 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14554 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14556 ;; Insert new tags at the correct column
14557 (beginning-of-line 1)
14558 (setq level (or (and (looking-at org-outline-regexp)
14559 (- (match-end 0) (point) 1))
14561 (cond
14562 ((and (equal current "") (equal tags "")))
14563 ((re-search-forward
14564 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14565 (point-at-eol) t)
14566 (if (equal tags "")
14567 (setq rpl "")
14568 (goto-char (match-beginning 0))
14569 (setq c0 (current-column)
14570 ;; compute offset for the case of org-indent-mode active
14571 di (if (org-bound-and-true-p org-indent-mode)
14572 (* (1- org-indent-indentation-per-level) (1- level))
14574 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14575 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14576 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14577 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14578 (replace-match rpl t t)
14579 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14580 tags)
14581 (t (error "Tags alignment failed")))
14582 (org-move-to-column col)
14583 (unless just-align
14584 (run-hooks 'org-after-tags-change-hook))))))
14586 (defun org-change-tag-in-region (beg end tag off)
14587 "Add or remove TAG for each entry in the region.
14588 This works in the agenda, and also in an org-mode buffer."
14589 (interactive
14590 (list (region-beginning) (region-end)
14591 (let ((org-last-tags-completion-table
14592 (if (derived-mode-p 'org-mode)
14593 (org-uniquify
14594 (delq nil (append (org-get-buffer-tags)
14595 (org-global-tags-completion-table))))
14596 (org-global-tags-completion-table))))
14597 (org-icompleting-read
14598 "Tag: " 'org-tags-completion-function nil nil nil
14599 'org-tags-history))
14600 (progn
14601 (message "[s]et or [r]emove? ")
14602 (equal (read-char-exclusive) ?r))))
14603 (if (fboundp 'deactivate-mark) (deactivate-mark))
14604 (let ((agendap (equal major-mode 'org-agenda-mode))
14605 l1 l2 m buf pos newhead (cnt 0))
14606 (goto-char end)
14607 (setq l2 (1- (org-current-line)))
14608 (goto-char beg)
14609 (setq l1 (org-current-line))
14610 (loop for l from l1 to l2 do
14611 (org-goto-line l)
14612 (setq m (get-text-property (point) 'org-hd-marker))
14613 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14614 (and agendap m))
14615 (setq buf (if agendap (marker-buffer m) (current-buffer))
14616 pos (if agendap m (point)))
14617 (with-current-buffer buf
14618 (save-excursion
14619 (save-restriction
14620 (goto-char pos)
14621 (setq cnt (1+ cnt))
14622 (org-toggle-tag tag (if off 'off 'on))
14623 (setq newhead (org-get-heading)))))
14624 (and agendap (org-agenda-change-all-lines newhead m))))
14625 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14627 (defun org-tags-completion-function (string predicate &optional flag)
14628 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14629 (confirm (lambda (x) (stringp (car x)))))
14630 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14631 (setq s1 (match-string 1 string)
14632 s2 (match-string 2 string))
14633 (setq s1 "" s2 string))
14634 (cond
14635 ((eq flag nil)
14636 ;; try completion
14637 (setq rtn (try-completion s2 ctable confirm))
14638 (if (stringp rtn)
14639 (setq rtn
14640 (concat s1 s2 (substring rtn (length s2))
14641 (if (and org-add-colon-after-tag-completion
14642 (assoc rtn ctable))
14643 ":" ""))))
14644 rtn)
14645 ((eq flag t)
14646 ;; all-completions
14647 (all-completions s2 ctable confirm))
14648 ((eq flag 'lambda)
14649 ;; exact match?
14650 (assoc s2 ctable)))))
14652 (defun org-fast-tag-insert (kwd tags face &optional end)
14653 "Insert KDW, and the TAGS, the latter with face FACE.
14654 Also insert END."
14655 (insert (format "%-12s" (concat kwd ":"))
14656 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14657 (or end "")))
14659 (defun org-fast-tag-show-exit (flag)
14660 (save-excursion
14661 (org-goto-line 3)
14662 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14663 (replace-match ""))
14664 (when flag
14665 (end-of-line 1)
14666 (org-move-to-column (- (window-width) 19) t)
14667 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14669 (defun org-set-current-tags-overlay (current prefix)
14670 "Add an overlay to CURRENT tag with PREFIX."
14671 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14672 (if (featurep 'xemacs)
14673 (org-overlay-display org-tags-overlay (concat prefix s)
14674 'secondary-selection)
14675 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14676 (org-overlay-display org-tags-overlay (concat prefix s)))))
14678 (defvar org-last-tag-selection-key nil)
14679 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14680 "Fast tag selection with single keys.
14681 CURRENT is the current list of tags in the headline, INHERITED is the
14682 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14683 possibly with grouping information. TODO-TABLE is a similar table with
14684 TODO keywords, should these have keys assigned to them.
14685 If the keys are nil, a-z are automatically assigned.
14686 Returns the new tags string, or nil to not change the current settings."
14687 (let* ((fulltable (append table todo-table))
14688 (maxlen (apply 'max (mapcar
14689 (lambda (x)
14690 (if (stringp (car x)) (string-width (car x)) 0))
14691 fulltable)))
14692 (buf (current-buffer))
14693 (expert (eq org-fast-tag-selection-single-key 'expert))
14694 (buffer-tags nil)
14695 (fwidth (+ maxlen 3 1 3))
14696 (ncol (/ (- (window-width) 4) fwidth))
14697 (i-face 'org-done)
14698 (c-face 'org-todo)
14699 tg cnt e c char c1 c2 ntable tbl rtn
14700 ov-start ov-end ov-prefix
14701 (exit-after-next org-fast-tag-selection-single-key)
14702 (done-keywords org-done-keywords)
14703 groups ingroup)
14704 (save-excursion
14705 (beginning-of-line 1)
14706 (if (looking-at
14707 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14708 (setq ov-start (match-beginning 1)
14709 ov-end (match-end 1)
14710 ov-prefix "")
14711 (setq ov-start (1- (point-at-eol))
14712 ov-end (1+ ov-start))
14713 (skip-chars-forward "^\n\r")
14714 (setq ov-prefix
14715 (concat
14716 (buffer-substring (1- (point)) (point))
14717 (if (> (current-column) org-tags-column)
14719 (make-string (- org-tags-column (current-column)) ?\ ))))))
14720 (move-overlay org-tags-overlay ov-start ov-end)
14721 (save-window-excursion
14722 (if expert
14723 (set-buffer (get-buffer-create " *Org tags*"))
14724 (delete-other-windows)
14725 (split-window-vertically)
14726 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14727 (erase-buffer)
14728 (org-set-local 'org-done-keywords done-keywords)
14729 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14730 (org-fast-tag-insert "Current" current c-face "\n\n")
14731 (org-fast-tag-show-exit exit-after-next)
14732 (org-set-current-tags-overlay current ov-prefix)
14733 (setq tbl fulltable char ?a cnt 0)
14734 (while (setq e (pop tbl))
14735 (cond
14736 ((equal (car e) :startgroup)
14737 (push '() groups) (setq ingroup t)
14738 (when (not (= cnt 0))
14739 (setq cnt 0)
14740 (insert "\n"))
14741 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14742 ((equal (car e) :endgroup)
14743 (setq ingroup nil cnt 0)
14744 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14745 ((equal e '(:newline))
14746 (when (not (= cnt 0))
14747 (setq cnt 0)
14748 (insert "\n")
14749 (setq e (car tbl))
14750 (while (equal (car tbl) '(:newline))
14751 (insert "\n")
14752 (setq tbl (cdr tbl)))))
14753 ((equal e '(:grouptags)) nil)
14755 (setq tg (copy-sequence (car e)) c2 nil)
14756 (if (cdr e)
14757 (setq c (cdr e))
14758 ;; automatically assign a character.
14759 (setq c1 (string-to-char
14760 (downcase (substring
14761 tg (if (= (string-to-char tg) ?@) 1 0)))))
14762 (if (or (rassoc c1 ntable) (rassoc c1 table))
14763 (while (or (rassoc char ntable) (rassoc char table))
14764 (setq char (1+ char)))
14765 (setq c2 c1))
14766 (setq c (or c2 char)))
14767 (if ingroup (push tg (car groups)))
14768 (setq tg (org-add-props tg nil 'face
14769 (cond
14770 ((not (assoc tg table))
14771 (org-get-todo-face tg))
14772 ((member tg current) c-face)
14773 ((member tg inherited) i-face))))
14774 (if (equal (caar tbl) :grouptags)
14775 (org-add-props tg nil 'face 'org-tag-group))
14776 (if (and (= cnt 0) (not ingroup)) (insert " "))
14777 (insert "[" c "] " tg (make-string
14778 (- fwidth 4 (length tg)) ?\ ))
14779 (push (cons tg c) ntable)
14780 (when (= (setq cnt (1+ cnt)) ncol)
14781 (insert "\n")
14782 (if ingroup (insert " "))
14783 (setq cnt 0)))))
14784 (setq ntable (nreverse ntable))
14785 (insert "\n")
14786 (goto-char (point-min))
14787 (if (not expert) (org-fit-window-to-buffer))
14788 (setq rtn
14789 (catch 'exit
14790 (while t
14791 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14792 (if (not groups) "no " "")
14793 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14794 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14795 (setq org-last-tag-selection-key c)
14796 (cond
14797 ((= c ?\r) (throw 'exit t))
14798 ((= c ?!)
14799 (setq groups (not groups))
14800 (goto-char (point-min))
14801 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14802 ((= c ?\C-c)
14803 (if (not expert)
14804 (org-fast-tag-show-exit
14805 (setq exit-after-next (not exit-after-next)))
14806 (setq expert nil)
14807 (delete-other-windows)
14808 (set-window-buffer (split-window-vertically) " *Org tags*")
14809 (org-switch-to-buffer-other-window " *Org tags*")
14810 (org-fit-window-to-buffer)))
14811 ((or (= c ?\C-g)
14812 (and (= c ?q) (not (rassoc c ntable))))
14813 (org-detach-overlay org-tags-overlay)
14814 (setq quit-flag t))
14815 ((= c ?\ )
14816 (setq current nil)
14817 (if exit-after-next (setq exit-after-next 'now)))
14818 ((= c ?\t)
14819 (condition-case nil
14820 (setq tg (org-icompleting-read
14821 "Tag: "
14822 (or buffer-tags
14823 (with-current-buffer buf
14824 (org-get-buffer-tags)))))
14825 (quit (setq tg "")))
14826 (when (string-match "\\S-" tg)
14827 (add-to-list 'buffer-tags (list tg))
14828 (if (member tg current)
14829 (setq current (delete tg current))
14830 (push tg current)))
14831 (if exit-after-next (setq exit-after-next 'now)))
14832 ((setq e (rassoc c todo-table) tg (car e))
14833 (with-current-buffer buf
14834 (save-excursion (org-todo tg)))
14835 (if exit-after-next (setq exit-after-next 'now)))
14836 ((setq e (rassoc c ntable) tg (car e))
14837 (if (member tg current)
14838 (setq current (delete tg current))
14839 (loop for g in groups do
14840 (if (member tg g)
14841 (mapc (lambda (x)
14842 (setq current (delete x current)))
14843 g)))
14844 (push tg current))
14845 (if exit-after-next (setq exit-after-next 'now))))
14847 ;; Create a sorted list
14848 (setq current
14849 (sort current
14850 (lambda (a b)
14851 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14852 (if (eq exit-after-next 'now) (throw 'exit t))
14853 (goto-char (point-min))
14854 (beginning-of-line 2)
14855 (delete-region (point) (point-at-eol))
14856 (org-fast-tag-insert "Current" current c-face)
14857 (org-set-current-tags-overlay current ov-prefix)
14858 (while (re-search-forward
14859 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14860 (setq tg (match-string 1))
14861 (add-text-properties
14862 (match-beginning 1) (match-end 1)
14863 (list 'face
14864 (cond
14865 ((member tg current) c-face)
14866 ((member tg inherited) i-face)
14867 (t (get-text-property (match-beginning 1) 'face))))))
14868 (goto-char (point-min)))))
14869 (org-detach-overlay org-tags-overlay)
14870 (if rtn
14871 (mapconcat 'identity current ":")
14872 nil))))
14874 (defun org-get-tags-string ()
14875 "Get the TAGS string in the current headline."
14876 (unless (org-at-heading-p t)
14877 (user-error "Not on a heading"))
14878 (save-excursion
14879 (beginning-of-line 1)
14880 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14881 (org-match-string-no-properties 1)
14882 "")))
14884 (defun org-get-tags ()
14885 "Get the list of tags specified in the current headline."
14886 (org-split-string (org-get-tags-string) ":"))
14888 (defun org-get-buffer-tags ()
14889 "Get a table of all tags used in the buffer, for completion."
14890 (let (tags)
14891 (save-excursion
14892 (goto-char (point-min))
14893 (while (re-search-forward
14894 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14895 (when (equal (char-after (point-at-bol 0)) ?*)
14896 (mapc (lambda (x) (add-to-list 'tags x))
14897 (org-split-string (org-match-string-no-properties 1) ":")))))
14898 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14899 (mapcar 'list tags)))
14901 ;;;; The mapping API
14903 (defun org-map-entries (func &optional match scope &rest skip)
14904 "Call FUNC at each headline selected by MATCH in SCOPE.
14906 FUNC is a function or a lisp form. The function will be called without
14907 arguments, with the cursor positioned at the beginning of the headline.
14908 The return values of all calls to the function will be collected and
14909 returned as a list.
14911 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14912 does not need to preserve point. After evaluation, the cursor will be
14913 moved to the end of the line (presumably of the headline of the
14914 processed entry) and search continues from there. Under some
14915 circumstances, this may not produce the wanted results. For example,
14916 if you have removed (e.g. archived) the current (sub)tree it could
14917 mean that the next entry will be skipped entirely. In such cases, you
14918 can specify the position from where search should continue by making
14919 FUNC set the variable `org-map-continue-from' to the desired buffer
14920 position.
14922 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14923 Only headlines that are matched by this query will be considered during
14924 the iteration. When MATCH is nil or t, all headlines will be
14925 visited by the iteration.
14927 SCOPE determines the scope of this command. It can be any of:
14929 nil The current buffer, respecting the restriction if any
14930 tree The subtree started with the entry at point
14931 region The entries within the active region, if any
14932 region-start-level
14933 The entries within the active region, but only those at
14934 the same level than the first one.
14935 file The current buffer, without restriction
14936 file-with-archives
14937 The current buffer, and any archives associated with it
14938 agenda All agenda files
14939 agenda-with-archives
14940 All agenda files with any archive files associated with them
14941 \(file1 file2 ...)
14942 If this is a list, all files in the list will be scanned
14944 The remaining args are treated as settings for the skipping facilities of
14945 the scanner. The following items can be given here:
14947 archive skip trees with the archive tag
14948 comment skip trees with the COMMENT keyword
14949 function or Emacs Lisp form:
14950 will be used as value for `org-agenda-skip-function', so
14951 whenever the function returns a position, FUNC will not be
14952 called for that entry and search will continue from the
14953 position returned
14955 If your function needs to retrieve the tags including inherited tags
14956 at the *current* entry, you can use the value of the variable
14957 `org-scanner-tags' which will be much faster than getting the value
14958 with `org-get-tags-at'. If your function gets properties with
14959 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14960 to t around the call to `org-entry-properties' to get the same speedup.
14961 Note that if your function moves around to retrieve tags and properties at
14962 a *different* entry, you cannot use these techniques."
14963 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14964 (not (org-region-active-p)))
14965 (let* ((org-agenda-archives-mode nil) ; just to make sure
14966 (org-agenda-skip-archived-trees (memq 'archive skip))
14967 (org-agenda-skip-comment-trees (memq 'comment skip))
14968 (org-agenda-skip-function
14969 (car (org-delete-all '(comment archive) skip)))
14970 (org-tags-match-list-sublevels t)
14971 (start-level (eq scope 'region-start-level))
14972 matcher file res
14973 org-todo-keywords-for-agenda
14974 org-done-keywords-for-agenda
14975 org-todo-keyword-alist-for-agenda
14976 org-drawers-for-agenda
14977 org-tag-alist-for-agenda
14978 todo-only)
14980 (cond
14981 ((eq match t) (setq matcher t))
14982 ((eq match nil) (setq matcher t))
14983 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14985 (save-excursion
14986 (save-restriction
14987 (cond ((eq scope 'tree)
14988 (org-back-to-heading t)
14989 (org-narrow-to-subtree)
14990 (setq scope nil))
14991 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14992 (org-region-active-p))
14993 ;; If needed, set start-level to a string like "2"
14994 (when start-level
14995 (save-excursion
14996 (goto-char (region-beginning))
14997 (unless (org-at-heading-p) (outline-next-heading))
14998 (setq start-level (org-current-level))))
14999 (narrow-to-region (region-beginning)
15000 (save-excursion
15001 (goto-char (region-end))
15002 (unless (and (bolp) (org-at-heading-p))
15003 (outline-next-heading))
15004 (point)))
15005 (setq scope nil)))
15007 (if (not scope)
15008 (progn
15009 (org-agenda-prepare-buffers
15010 (list (buffer-file-name (current-buffer))))
15011 (setq res (org-scan-tags func matcher todo-only start-level)))
15012 ;; Get the right scope
15013 (cond
15014 ((and scope (listp scope) (symbolp (car scope)))
15015 (setq scope (eval scope)))
15016 ((eq scope 'agenda)
15017 (setq scope (org-agenda-files t)))
15018 ((eq scope 'agenda-with-archives)
15019 (setq scope (org-agenda-files t))
15020 (setq scope (org-add-archive-files scope)))
15021 ((eq scope 'file)
15022 (setq scope (list (buffer-file-name))))
15023 ((eq scope 'file-with-archives)
15024 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15025 (org-agenda-prepare-buffers scope)
15026 (while (setq file (pop scope))
15027 (with-current-buffer (org-find-base-buffer-visiting file)
15028 (save-excursion
15029 (save-restriction
15030 (widen)
15031 (goto-char (point-min))
15032 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
15033 res)))
15035 ;;;; Properties
15037 ;;; Setting and retrieving properties
15039 (defconst org-special-properties
15040 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
15041 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
15042 "The special properties valid in Org-mode.
15044 These are properties that are not defined in the property drawer,
15045 but in some other way.")
15047 (defconst org-default-properties
15048 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15049 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15050 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15051 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15052 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
15053 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15054 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15055 "Some properties that are used by Org-mode for various purposes.
15056 Being in this list makes sure that they are offered for completion.")
15058 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15059 "Regular expression matching the first line of a property drawer.")
15061 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15062 "Regular expression matching the last line of a property drawer.")
15064 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
15065 "Regular expression matching the first line of a property drawer.")
15067 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15068 "Regular expression matching the first line of a property drawer.")
15070 (defconst org-property-drawer-re
15071 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15072 org-property-end-re "\\)\n?")
15073 "Matches an entire property drawer.")
15075 (defconst org-clock-drawer-re
15076 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15077 org-property-end-re "\\)\n?")
15078 "Matches an entire clock drawer.")
15080 (defun org-property-action ()
15081 "Do an action on properties."
15082 (interactive)
15083 (let (c)
15084 (org-at-property-p)
15085 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15086 (setq c (read-char-exclusive))
15087 (cond
15088 ((equal c ?s)
15089 (call-interactively 'org-set-property))
15090 ((equal c ?d)
15091 (call-interactively 'org-delete-property))
15092 ((equal c ?D)
15093 (call-interactively 'org-delete-property-globally))
15094 ((equal c ?c)
15095 (call-interactively 'org-compute-property-at-point))
15096 (t (user-error "No such property action %c" c)))))
15098 (defun org-inc-effort ()
15099 "Increment the value of the effort property in the current entry."
15100 (interactive)
15101 (org-set-effort nil t))
15103 (defvar org-clock-effort) ;; Defined in org-clock.el
15104 (defvar org-clock-current-task) ;; Defined in org-clock.el
15105 (defun org-set-effort (&optional value increment)
15106 "Set the effort property of the current entry.
15107 With numerical prefix arg, use the nth allowed value, 0 stands for the
15108 10th allowed value.
15110 When INCREMENT is non-nil, set the property to the next allowed value."
15111 (interactive "P")
15112 (if (equal value 0) (setq value 10))
15113 (let* ((completion-ignore-case t)
15114 (prop org-effort-property)
15115 (cur (org-entry-get nil prop))
15116 (allowed (org-property-get-allowed-values nil prop 'table))
15117 (existing (mapcar 'list (org-property-values prop)))
15118 (heading (nth 4 (org-heading-components)))
15120 (val (cond
15121 ((stringp value) value)
15122 ((and allowed (integerp value))
15123 (or (car (nth (1- value) allowed))
15124 (car (org-last allowed))))
15125 ((and allowed increment)
15126 (or (caadr (member (list cur) allowed))
15127 (user-error "Allowed effort values are not set")))
15128 (allowed
15129 (message "Select 1-9,0, [RET%s]: %s"
15130 (if cur (concat "=" cur) "")
15131 (mapconcat 'car allowed " "))
15132 (setq rpl (read-char-exclusive))
15133 (if (equal rpl ?\r)
15135 (setq rpl (- rpl ?0))
15136 (if (equal rpl 0) (setq rpl 10))
15137 (if (and (> rpl 0) (<= rpl (length allowed)))
15138 (car (nth (1- rpl) allowed))
15139 (org-completing-read "Effort: " allowed nil))))
15141 (let (org-completion-use-ido org-completion-use-iswitchb)
15142 (org-completing-read
15143 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15144 (concat "[" cur "]") "")
15145 ": ")
15146 existing nil nil "" nil cur))))))
15147 (unless (equal (org-entry-get nil prop) val)
15148 (org-entry-put nil prop val))
15149 (save-excursion
15150 (org-back-to-heading t)
15151 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15152 (when (string= heading org-clock-current-task)
15153 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15154 (org-clock-update-mode-line))
15155 (message "%s is now %s" prop val)))
15157 (defun org-at-property-p ()
15158 "Is cursor inside a property drawer?"
15159 (save-excursion
15160 (when (equal 'node-property (car (org-element-at-point)))
15161 (beginning-of-line 1)
15162 (looking-at org-property-re))))
15164 (defun org-get-property-block (&optional beg end force)
15165 "Return the (beg . end) range of the body of the property drawer.
15166 BEG and END are the beginning and end of the current subtree, or of
15167 the part before the first headline. If they are not given, they will
15168 be found. If the drawer does not exist and FORCE is non-nil, create
15169 the drawer."
15170 (catch 'exit
15171 (save-excursion
15172 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15173 (progn (org-back-to-heading t) (point))))
15174 (end (or end (and (not (outline-next-heading)) (point-max))
15175 (point))))
15176 (goto-char beg)
15177 (if (re-search-forward org-property-start-re end t)
15178 (setq beg (1+ (match-end 0)))
15179 (if force
15180 (save-excursion
15181 (org-insert-property-drawer)
15182 (setq end (progn (outline-next-heading) (point))))
15183 (throw 'exit nil))
15184 (goto-char beg)
15185 (if (re-search-forward org-property-start-re end t)
15186 (setq beg (1+ (match-end 0)))))
15187 (if (re-search-forward org-property-end-re end t)
15188 (setq end (match-beginning 0))
15189 (or force (throw 'exit nil))
15190 (goto-char beg)
15191 (setq end beg)
15192 (org-indent-line)
15193 (insert ":END:\n"))
15194 (cons beg end)))))
15196 (defun org-entry-properties (&optional pom which specific)
15197 "Get all properties of the entry at point-or-marker POM.
15198 This includes the TODO keyword, the tags, time strings for deadline,
15199 scheduled, and clocking, and any additional properties defined in the
15200 entry. The return value is an alist, keys may occur multiple times
15201 if the property key was used several times.
15202 POM may also be nil, in which case the current entry is used.
15203 If WHICH is nil or `all', get all properties. If WHICH is
15204 `special' or `standard', only get that subclass. If WHICH
15205 is a string only get exactly this property. SPECIFIC can be a string, the
15206 specific property we are interested in. Specifying it can speed
15207 things up because then unnecessary parsing is avoided."
15208 (setq which (or which 'all))
15209 (org-with-wide-buffer
15210 (org-with-point-at pom
15211 (let ((clockstr (substring org-clock-string 0 -1))
15212 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15213 (case-fold-search nil)
15214 beg end range props sum-props key key1 value string clocksum clocksumt)
15215 (when (and (derived-mode-p 'org-mode)
15216 (ignore-errors (org-back-to-heading t)))
15217 (setq beg (point))
15218 (setq sum-props (get-text-property (point) 'org-summaries))
15219 (setq clocksum (get-text-property (point) :org-clock-minutes)
15220 clocksumt (get-text-property (point) :org-clock-minutes-today))
15221 (outline-next-heading)
15222 (setq end (point))
15223 (when (memq which '(all special))
15224 ;; Get the special properties, like TODO and tags
15225 (goto-char beg)
15226 (when (and (or (not specific) (string= specific "TODO"))
15227 (looking-at org-todo-line-regexp) (match-end 2))
15228 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15229 (when (and (or (not specific) (string= specific "PRIORITY"))
15230 (looking-at org-priority-regexp))
15231 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15232 (when (or (not specific) (string= specific "FILE"))
15233 (push (cons "FILE" buffer-file-name) props))
15234 (when (and (or (not specific) (string= specific "TAGS"))
15235 (setq value (org-get-tags-string))
15236 (string-match "\\S-" value))
15237 (push (cons "TAGS" value) props))
15238 (when (and (or (not specific) (string= specific "ALLTAGS"))
15239 (setq value (org-get-tags-at)))
15240 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15241 ":"))
15242 props))
15243 (when (or (not specific) (string= specific "BLOCKED"))
15244 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15245 (when (or (not specific)
15246 (member specific
15247 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15248 "TIMESTAMP" "TIMESTAMP_IA")))
15249 (catch 'match
15250 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15251 (setq key (if (match-end 1)
15252 (substring (org-match-string-no-properties 1)
15253 0 -1))
15254 string (if (equal key clockstr)
15255 (org-trim
15256 (buffer-substring-no-properties
15257 (match-beginning 3) (goto-char
15258 (point-at-eol))))
15259 (substring (org-match-string-no-properties 3)
15260 1 -1)))
15261 ;; Get the correct property name from the key. This is
15262 ;; necessary if the user has configured time keywords.
15263 (setq key1 (concat key ":"))
15264 (cond
15265 ((not key)
15266 (setq key
15267 (if (= (char-after (match-beginning 3)) ?\[)
15268 "TIMESTAMP_IA" "TIMESTAMP")))
15269 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15270 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15271 ((equal key1 org-closed-string) (setq key "CLOSED"))
15272 ((equal key1 org-clock-string) (setq key "CLOCK")))
15273 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15274 (progn
15275 (push (cons key string) props)
15276 ;; no need to search further if match is found
15277 (throw 'match t))
15278 (when (or (equal key "CLOCK") (not (assoc key props)))
15279 (push (cons key string) props)))))))
15281 (when (memq which '(all standard))
15282 ;; Get the standard properties, like :PROP: ...
15283 (setq range (org-get-property-block beg end))
15284 (when range
15285 (goto-char (car range))
15286 (while (re-search-forward org-property-re
15287 (cdr range) t)
15288 (setq key (org-match-string-no-properties 2)
15289 value (org-trim (or (org-match-string-no-properties 3) "")))
15290 (unless (member key excluded)
15291 (push (cons key (or value "")) props)))))
15292 (if clocksum
15293 (push (cons "CLOCKSUM"
15294 (org-columns-number-to-string (/ (float clocksum) 60.)
15295 'add_times))
15296 props))
15297 (if clocksumt
15298 (push (cons "CLOCKSUM_T"
15299 (org-columns-number-to-string (/ (float clocksumt) 60.)
15300 'add_times))
15301 props))
15302 (unless (assoc "CATEGORY" props)
15303 (push (cons "CATEGORY" (org-get-category)) props))
15304 (append sum-props (nreverse props)))))))
15306 (defun org-entry-get (pom property &optional inherit literal-nil)
15307 "Get value of PROPERTY for entry or content at point-or-marker POM.
15308 If INHERIT is non-nil and the entry does not have the property,
15309 then also check higher levels of the hierarchy.
15310 If INHERIT is the symbol `selective', use inheritance only if the setting
15311 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15312 If the property is present but empty, the return value is the empty string.
15313 If the property is not present at all, nil is returned.
15315 Return the value as a string.
15317 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15318 do not interpret it as the list atom nil. This is used for inheritance
15319 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15320 (org-with-point-at pom
15321 (if (and inherit (if (eq inherit 'selective)
15322 (org-property-inherit-p property)
15324 (org-entry-get-with-inheritance property literal-nil)
15325 (if (member property org-special-properties)
15326 ;; We need a special property. Use `org-entry-properties'
15327 ;; to retrieve it, but specify the wanted property
15328 (cdr (assoc property (org-entry-properties nil 'special property)))
15329 (org-with-wide-buffer
15330 (let ((range (org-get-property-block)))
15331 (when (and range (not (eq (car range) (cdr range)))
15332 (save-excursion
15333 (goto-char (car range))
15334 (re-search-forward
15335 (concat (org-re-property property) "\\|"
15336 (org-re-property (concat property "+")))
15337 (cdr range) t)))
15338 (let* ((props
15339 (list (or (assoc property org-file-properties)
15340 (assoc property org-global-properties)
15341 (assoc property org-global-properties-fixed))))
15342 (ap (lambda (key)
15343 (when (re-search-forward
15344 (org-re-property key) (cdr range) t)
15345 (setq props
15346 (org-update-property-plist
15348 (if (match-end 3)
15349 (org-match-string-no-properties 3) "")
15350 props)))))
15351 val)
15352 (goto-char (car range))
15353 (funcall ap property)
15354 (goto-char (car range))
15355 (while (funcall ap (concat property "+")))
15356 (setq val (cdr (assoc property props)))
15357 (when val (if literal-nil val (org-not-nil val)))))))))))
15359 (defun org-property-or-variable-value (var &optional inherit)
15360 "Check if there is a property fixing the value of VAR.
15361 If yes, return this value. If not, return the current value of the variable."
15362 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15363 (if (and prop (stringp prop) (string-match "\\S-" prop))
15364 (read prop)
15365 (symbol-value var))))
15367 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15368 "Delete the property PROPERTY from entry at point-or-marker POM.
15369 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15370 an empty drawer to delete."
15371 (org-with-point-at pom
15372 (if (member property org-special-properties)
15373 nil ; cannot delete these properties.
15374 (let ((range (org-get-property-block)))
15375 (if (and range
15376 (goto-char (car range))
15377 (re-search-forward
15378 (org-re-property property)
15379 (cdr range) t))
15380 (progn
15381 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15382 (and delete-empty-drawer
15383 (org-remove-empty-drawer-at
15384 delete-empty-drawer (car range)))
15386 nil)))))
15388 ;; Multi-values properties are properties that contain multiple values
15389 ;; These values are assumed to be single words, separated by whitespace.
15390 (defun org-entry-add-to-multivalued-property (pom property value)
15391 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15392 (let* ((old (org-entry-get pom property))
15393 (values (and old (org-split-string old "[ \t]"))))
15394 (setq value (org-entry-protect-space value))
15395 (unless (member value values)
15396 (setq values (append values (list value)))
15397 (org-entry-put pom property
15398 (mapconcat 'identity values " ")))))
15400 (defun org-entry-remove-from-multivalued-property (pom property value)
15401 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15402 (let* ((old (org-entry-get pom property))
15403 (values (and old (org-split-string old "[ \t]"))))
15404 (setq value (org-entry-protect-space value))
15405 (when (member value values)
15406 (setq values (delete value values))
15407 (org-entry-put pom property
15408 (mapconcat 'identity values " ")))))
15410 (defun org-entry-member-in-multivalued-property (pom property value)
15411 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15412 (let* ((old (org-entry-get pom property))
15413 (values (and old (org-split-string old "[ \t]"))))
15414 (setq value (org-entry-protect-space value))
15415 (member value values)))
15417 (defun org-entry-get-multivalued-property (pom property)
15418 "Return a list of values in a multivalued property."
15419 (let* ((value (org-entry-get pom property))
15420 (values (and value (org-split-string value "[ \t]"))))
15421 (mapcar 'org-entry-restore-space values)))
15423 (defun org-entry-put-multivalued-property (pom property &rest values)
15424 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15425 VALUES should be a list of strings. Spaces will be protected."
15426 (org-entry-put pom property
15427 (mapconcat 'org-entry-protect-space values " "))
15428 (let* ((value (org-entry-get pom property))
15429 (values (and value (org-split-string value "[ \t]"))))
15430 (mapcar 'org-entry-restore-space values)))
15432 (defun org-entry-protect-space (s)
15433 "Protect spaces and newline in string S."
15434 (while (string-match " " s)
15435 (setq s (replace-match "%20" t t s)))
15436 (while (string-match "\n" s)
15437 (setq s (replace-match "%0A" t t s)))
15440 (defun org-entry-restore-space (s)
15441 "Restore spaces and newline in string S."
15442 (while (string-match "%20" s)
15443 (setq s (replace-match " " t t s)))
15444 (while (string-match "%0A" s)
15445 (setq s (replace-match "\n" t t s)))
15448 (defvar org-entry-property-inherited-from (make-marker)
15449 "Marker pointing to the entry from where a property was inherited.
15450 Each call to `org-entry-get-with-inheritance' will set this marker to the
15451 location of the entry where the inheritance search matched. If there was
15452 no match, the marker will point nowhere.
15453 Note that also `org-entry-get' calls this function, if the INHERIT flag
15454 is set.")
15456 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15457 "Get PROPERTY of entry or content at point, search higher levels if needed.
15458 The search will stop at the first ancestor which has the property defined.
15459 If the value found is \"nil\", return nil to show that the property
15460 should be considered as undefined (this is the meaning of nil here).
15461 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15462 (move-marker org-entry-property-inherited-from nil)
15463 (let (tmp)
15464 (save-excursion
15465 (save-restriction
15466 (widen)
15467 (catch 'ex
15468 (while t
15469 (when (setq tmp (org-entry-get nil property nil literal-nil))
15470 (or (ignore-errors (org-back-to-heading t))
15471 (goto-char (point-min)))
15472 (move-marker org-entry-property-inherited-from (point))
15473 (throw 'ex tmp))
15474 (or (ignore-errors (org-up-heading-safe))
15475 (throw 'ex nil))))))
15476 (setq tmp (or tmp
15477 (cdr (assoc property org-file-properties))
15478 (cdr (assoc property org-global-properties))
15479 (cdr (assoc property org-global-properties-fixed))))
15480 (if literal-nil tmp (org-not-nil tmp))))
15482 (defvar org-property-changed-functions nil
15483 "Hook called when the value of a property has changed.
15484 Each hook function should accept two arguments, the name of the property
15485 and the new value.")
15487 (defun org-entry-put (pom property value)
15488 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15489 If the value is `nil', it is converted to the empty string.
15490 If it is not a string, an error is raised."
15491 (cond ((null value) (setq value ""))
15492 ((not (stringp value))
15493 (error "Properties values should be strings.")))
15494 (org-with-point-at pom
15495 (org-back-to-heading t)
15496 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15497 range)
15498 (cond
15499 ((equal property "TODO")
15500 (when (and (string-match "\\S-" value)
15501 (not (member value org-todo-keywords-1)))
15502 (user-error "\"%s\" is not a valid TODO state" value))
15503 (if (or (not value)
15504 (not (string-match "\\S-" value)))
15505 (setq value 'none))
15506 (org-todo value)
15507 (org-set-tags nil 'align))
15508 ((equal property "PRIORITY")
15509 (org-priority (if (and value (string-match "\\S-" value))
15510 (string-to-char value) ?\ ))
15511 (org-set-tags nil 'align))
15512 ((equal property "CLOCKSUM")
15513 (if (not (re-search-forward
15514 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15515 (error "Cannot find a clock log")
15516 (goto-char (- (match-end 1) 2))
15517 (cond
15518 ((eq value 'earlier) (org-timestamp-down))
15519 ((eq value 'later) (org-timestamp-up)))
15520 (org-clock-sum-current-item)))
15521 ((equal property "SCHEDULED")
15522 (if (re-search-forward org-scheduled-time-regexp end t)
15523 (cond
15524 ((eq value 'earlier) (org-timestamp-change -1 'day))
15525 ((eq value 'later) (org-timestamp-change 1 'day))
15526 (t (call-interactively 'org-schedule)))
15527 (call-interactively 'org-schedule)))
15528 ((equal property "DEADLINE")
15529 (if (re-search-forward org-deadline-time-regexp end t)
15530 (cond
15531 ((eq value 'earlier) (org-timestamp-change -1 'day))
15532 ((eq value 'later) (org-timestamp-change 1 'day))
15533 (t (call-interactively 'org-deadline)))
15534 (call-interactively 'org-deadline)))
15535 ((member property org-special-properties)
15536 (error "The %s property can not yet be set with `org-entry-put'"
15537 property))
15538 (t ; a non-special property
15539 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15540 (setq range (org-get-property-block beg end 'force))
15541 (goto-char (car range))
15542 (if (re-search-forward
15543 (org-re-property property) (cdr range) t)
15544 (progn
15545 (delete-region (match-beginning 0) (match-end 0))
15546 (goto-char (match-beginning 0)))
15547 (goto-char (cdr range))
15548 (insert "\n")
15549 (backward-char 1)
15550 (org-indent-line))
15551 (insert ":" property ":")
15552 (and value (insert " " value))
15553 (org-indent-line)))))
15554 (run-hook-with-args 'org-property-changed-functions property value)))
15556 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15557 "Get all property keys in the current buffer.
15558 With INCLUDE-SPECIALS, also list the special properties that reflect things
15559 like tags and TODO state.
15560 With INCLUDE-DEFAULTS, also include properties that has special meaning
15561 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15562 and others.
15563 With INCLUDE-COLUMNS, also include property names given in COLUMN
15564 formats in the current buffer."
15565 (let (rtn range cfmt s p)
15566 (save-excursion
15567 (save-restriction
15568 (widen)
15569 (goto-char (point-min))
15570 (while (re-search-forward org-property-start-re nil t)
15571 (setq range (org-get-property-block))
15572 (goto-char (car range))
15573 (while (re-search-forward org-property-re
15574 (cdr range) t)
15575 (add-to-list 'rtn (org-match-string-no-properties 2)))
15576 (outline-next-heading))))
15578 (when include-specials
15579 (setq rtn (append org-special-properties rtn)))
15581 (when include-defaults
15582 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15583 (add-to-list 'rtn org-effort-property))
15585 (when include-columns
15586 (save-excursion
15587 (save-restriction
15588 (widen)
15589 (goto-char (point-min))
15590 (while (re-search-forward
15591 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15592 nil t)
15593 (setq cfmt (match-string 2) s 0)
15594 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15595 cfmt s)
15596 (setq s (match-end 0)
15597 p (match-string 1 cfmt))
15598 (unless (or (equal p "ITEM")
15599 (member p org-special-properties))
15600 (add-to-list 'rtn (match-string 1 cfmt))))))))
15602 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15604 (defun org-property-values (key)
15605 "Return a list of all values of property KEY in the current buffer."
15606 (save-excursion
15607 (save-restriction
15608 (widen)
15609 (goto-char (point-min))
15610 (let ((re (org-re-property key))
15611 values)
15612 (while (re-search-forward re nil t)
15613 (add-to-list 'values (org-trim (match-string 3))))
15614 (delete "" values)))))
15616 (defun org-insert-property-drawer ()
15617 "Insert a property drawer into the current entry."
15618 (org-back-to-heading t)
15619 (looking-at org-outline-regexp)
15620 (let ((indent (if org-adapt-indentation
15621 (- (match-end 0) (match-beginning 0))
15623 (beg (point))
15624 (re (concat "^[ \t]*" org-keyword-time-regexp))
15625 end hiddenp)
15626 (outline-next-heading)
15627 (setq end (point))
15628 (goto-char beg)
15629 (while (re-search-forward re end t))
15630 (setq hiddenp (outline-invisible-p))
15631 (end-of-line 1)
15632 (and (equal (char-after) ?\n) (forward-char 1))
15633 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15634 (if (member (match-string 1) '("CLOCK:" ":END:"))
15635 ;; just skip this line
15636 (beginning-of-line 2)
15637 ;; Drawer start, find the end
15638 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15639 (beginning-of-line 1)))
15640 (org-skip-over-state-notes)
15641 (skip-chars-backward " \t\n\r")
15642 (if (and (eq (char-before) ?*) (not (eq (char-after) ?\n)))
15643 (forward-char 1))
15644 (goto-char (point-at-eol))
15645 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15646 (beginning-of-line 0)
15647 (org-indent-to-column indent)
15648 (beginning-of-line 2)
15649 (org-indent-to-column indent)
15650 (beginning-of-line 0)
15651 (if hiddenp
15652 (save-excursion
15653 (org-back-to-heading t)
15654 (hide-entry))
15655 (org-flag-drawer t))))
15657 (defun org-insert-drawer (&optional arg drawer)
15658 "Insert a drawer at point.
15660 Optional argument DRAWER, when non-nil, is a string representing
15661 drawer's name. Otherwise, the user is prompted for a name.
15663 If a region is active, insert the drawer around that region
15664 instead.
15666 Point is left between drawer's boundaries."
15667 (interactive "P")
15668 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15669 "LOGBOOK"))
15670 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15671 ;; internally by Org. They are meant to be inserted
15672 ;; automatically.
15673 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15674 ;; Remove system drawers from list. Note: For some reason,
15675 ;; `org-completing-read' ignores the predicate while
15676 ;; `completing-read' handles it fine.
15677 (drawer (if arg "PROPERTIES"
15678 (or drawer
15679 (completing-read
15680 "Drawer: " org-drawers
15681 (lambda (d) (not (member d system-drawers))))))))
15682 (cond
15683 ;; With C-u, fall back on `org-insert-property-drawer'
15684 (arg (org-insert-property-drawer))
15685 ;; With an active region, insert a drawer at point.
15686 ((not (org-region-active-p))
15687 (progn
15688 (unless (bolp) (insert "\n"))
15689 (insert (format ":%s:\n\n:END:\n" drawer))
15690 (forward-line -2)))
15691 ;; Otherwise, insert the drawer at point
15693 (let ((rbeg (region-beginning))
15694 (rend (copy-marker (region-end))))
15695 (unwind-protect
15696 (progn
15697 (goto-char rbeg)
15698 (beginning-of-line)
15699 (when (save-excursion
15700 (re-search-forward org-outline-regexp-bol rend t))
15701 (user-error "Drawers cannot contain headlines"))
15702 ;; Position point at the beginning of the first
15703 ;; non-blank line in region. Insert drawer's opening
15704 ;; there, then indent it.
15705 (org-skip-whitespace)
15706 (beginning-of-line)
15707 (insert ":" drawer ":\n")
15708 (forward-line -1)
15709 (indent-for-tab-command)
15710 ;; Move point to the beginning of the first blank line
15711 ;; after the last non-blank line in region. Insert
15712 ;; drawer's closing, then indent it.
15713 (goto-char rend)
15714 (skip-chars-backward " \r\t\n")
15715 (insert "\n:END:")
15716 (deactivate-mark t)
15717 (indent-for-tab-command)
15718 (unless (eolp) (insert "\n")))
15719 ;; Clear marker, whatever the outcome of insertion is.
15720 (set-marker rend nil)))))))
15722 (defvar org-property-set-functions-alist nil
15723 "Property set function alist.
15724 Each entry should have the following format:
15726 (PROPERTY . READ-FUNCTION)
15728 The read function will be called with the same argument as
15729 `org-completing-read'.")
15731 (defun org-set-property-function (property)
15732 "Get the function that should be used to set PROPERTY.
15733 This is computed according to `org-property-set-functions-alist'."
15734 (or (cdr (assoc property org-property-set-functions-alist))
15735 'org-completing-read))
15737 (defun org-read-property-value (property)
15738 "Read PROPERTY value from user."
15739 (let* ((completion-ignore-case t)
15740 (allowed (org-property-get-allowed-values nil property 'table))
15741 (cur (org-entry-get nil property))
15742 (prompt (concat property " value"
15743 (if (and cur (string-match "\\S-" cur))
15744 (concat " [" cur "]") "") ": "))
15745 (set-function (org-set-property-function property))
15746 (val (if allowed
15747 (funcall set-function prompt allowed nil
15748 (not (get-text-property 0 'org-unrestricted
15749 (caar allowed))))
15750 (let (org-completion-use-ido org-completion-use-iswitchb)
15751 (funcall set-function prompt
15752 (mapcar 'list (org-property-values property))
15753 nil nil "" nil cur)))))
15754 (if (equal val "")
15756 val)))
15758 (defvar org-last-set-property nil)
15759 (defvar org-last-set-property-value nil)
15760 (defun org-read-property-name ()
15761 "Read a property name."
15762 (let* ((completion-ignore-case t)
15763 (keys (org-buffer-property-keys nil t t))
15764 (default-prop (or (save-excursion
15765 (save-match-data
15766 (beginning-of-line)
15767 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15768 (null (string= (match-string 1) "END"))
15769 (match-string 1))))
15770 org-last-set-property))
15771 (property (org-icompleting-read
15772 (concat "Property"
15773 (if default-prop (concat " [" default-prop "]") "")
15774 ": ")
15775 (mapcar 'list keys)
15776 nil nil nil nil
15777 default-prop)))
15778 (if (member property keys)
15779 property
15780 (or (cdr (assoc (downcase property)
15781 (mapcar (lambda (x) (cons (downcase x) x))
15782 keys)))
15783 property))))
15785 (defun org-set-property-and-value (use-last)
15786 "Allow to set [PROPERTY]: [value] direction from prompt.
15787 When use-default, don't even ask, just use the last
15788 \"[PROPERTY]: [value]\" string from the history."
15789 (interactive "P")
15790 (let* ((completion-ignore-case t)
15791 (pv (or (and use-last org-last-set-property-value)
15792 (org-completing-read
15793 "Enter a \"[Property]: [value]\" pair: "
15794 nil nil nil nil nil
15795 org-last-set-property-value)))
15796 prop val)
15797 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15798 (setq prop (match-string 1 pv)
15799 val (match-string 2 pv))
15800 (org-set-property prop val))))
15802 (defun org-set-property (property value)
15803 "In the current entry, set PROPERTY to VALUE.
15804 When called interactively, this will prompt for a property name, offering
15805 completion on existing and default properties. And then it will prompt
15806 for a value, offering completion either on allowed values (via an inherited
15807 xxx_ALL property) or on existing values in other instances of this property
15808 in the current file."
15809 (interactive (list nil nil))
15810 (let* ((property (or property (org-read-property-name)))
15811 (value (or value (org-read-property-value property)))
15812 (fn (cdr (assoc property org-properties-postprocess-alist))))
15813 (setq org-last-set-property property)
15814 (setq org-last-set-property-value (concat property ": " value))
15815 ;; Possibly postprocess the inserted value:
15816 (when fn (setq value (funcall fn value)))
15817 (unless (equal (org-entry-get nil property) value)
15818 (org-entry-put nil property value))))
15820 (defun org-delete-property (property &optional delete-empty-drawer)
15821 "In the current entry, delete PROPERTY.
15822 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15823 an empty drawer to delete."
15824 (interactive
15825 (let* ((completion-ignore-case t)
15826 (cat (org-entry-get (point) "CATEGORY"))
15827 (props0 (org-entry-properties nil 'standard))
15828 (props (if cat props0
15829 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15830 (prop (if (< 1 (length props))
15831 (org-icompleting-read "Property: " props nil t)
15832 (caar props))))
15833 (list prop)))
15834 (if (org-entry-delete nil property delete-empty-drawer)
15835 (message "Property %s deleted" property)))
15837 (defun org-delete-property-globally (property)
15838 "Remove PROPERTY globally, from all entries."
15839 (interactive
15840 (let* ((completion-ignore-case t)
15841 (prop (org-icompleting-read
15842 "Globally remove property: "
15843 (mapcar 'list (org-buffer-property-keys)))))
15844 (list prop)))
15845 (save-excursion
15846 (save-restriction
15847 (widen)
15848 (goto-char (point-min))
15849 (let ((cnt 0))
15850 (while (re-search-forward
15851 (org-re-property property)
15852 nil t)
15853 (setq cnt (1+ cnt))
15854 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15855 (message "Property \"%s\" removed from %d entries" property cnt)))))
15857 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15859 (defun org-compute-property-at-point ()
15860 "Compute the property at point.
15861 This looks for an enclosing column format, extracts the operator and
15862 then applies it to the property in the column format's scope."
15863 (interactive)
15864 (unless (org-at-property-p)
15865 (user-error "Not at a property"))
15866 (let ((prop (org-match-string-no-properties 2)))
15867 (org-columns-get-format-and-top-level)
15868 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15869 (user-error "No operator defined for property %s" prop))
15870 (org-columns-compute prop)))
15872 (defvar org-property-allowed-value-functions nil
15873 "Hook for functions supplying allowed values for a specific property.
15874 The functions must take a single argument, the name of the property, and
15875 return a flat list of allowed values. If \":ETC\" is one of
15876 the values, this means that these values are intended as defaults for
15877 completion, but that other values should be allowed too.
15878 The functions must return nil if they are not responsible for this
15879 property.")
15881 (defun org-property-get-allowed-values (pom property &optional table)
15882 "Get allowed values for the property PROPERTY.
15883 When TABLE is non-nil, return an alist that can directly be used for
15884 completion."
15885 (let (vals)
15886 (cond
15887 ((equal property "TODO")
15888 (setq vals (org-with-point-at pom
15889 (append org-todo-keywords-1 '("")))))
15890 ((equal property "PRIORITY")
15891 (let ((n org-lowest-priority))
15892 (while (>= n org-highest-priority)
15893 (push (char-to-string n) vals)
15894 (setq n (1- n)))))
15895 ((member property org-special-properties))
15896 ((setq vals (run-hook-with-args-until-success
15897 'org-property-allowed-value-functions property)))
15899 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15900 (when (and vals (string-match "\\S-" vals))
15901 (setq vals (car (read-from-string (concat "(" vals ")"))))
15902 (setq vals (mapcar (lambda (x)
15903 (cond ((stringp x) x)
15904 ((numberp x) (number-to-string x))
15905 ((symbolp x) (symbol-name x))
15906 (t "???")))
15907 vals)))))
15908 (when (member ":ETC" vals)
15909 (setq vals (remove ":ETC" vals))
15910 (org-add-props (car vals) '(org-unrestricted t)))
15911 (if table (mapcar 'list vals) vals)))
15913 (defun org-property-previous-allowed-value (&optional previous)
15914 "Switch to the next allowed value for this property."
15915 (interactive)
15916 (org-property-next-allowed-value t))
15918 (defun org-property-next-allowed-value (&optional previous)
15919 "Switch to the next allowed value for this property."
15920 (interactive)
15921 (unless (org-at-property-p)
15922 (user-error "Not at a property"))
15923 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15924 (key (match-string 2))
15925 (value (match-string 3))
15926 (allowed (or (org-property-get-allowed-values (point) key)
15927 (and (member value '("[ ]" "[-]" "[X]"))
15928 '("[ ]" "[X]"))))
15929 (heading (save-match-data (nth 4 (org-heading-components))))
15930 nval)
15931 (unless allowed
15932 (user-error "Allowed values for this property have not been defined"))
15933 (if previous (setq allowed (reverse allowed)))
15934 (if (member value allowed)
15935 (setq nval (car (cdr (member value allowed)))))
15936 (setq nval (or nval (car allowed)))
15937 (if (equal nval value)
15938 (user-error "Only one allowed value for this property"))
15939 (org-at-property-p)
15940 (replace-match (concat " :" key ": " nval) t t)
15941 (org-indent-line)
15942 (beginning-of-line 1)
15943 (skip-chars-forward " \t")
15944 (when (equal prop org-effort-property)
15945 (save-excursion
15946 (org-back-to-heading t)
15947 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15948 (when (string= org-clock-current-task heading)
15949 (setq org-clock-effort nval)
15950 (org-clock-update-mode-line)))
15951 (run-hook-with-args 'org-property-changed-functions key nval)))
15953 (defun org-find-olp (path &optional this-buffer)
15954 "Return a marker pointing to the entry at outline path OLP.
15955 If anything goes wrong, throw an error.
15956 You can wrap this call to catch the error like this:
15958 (condition-case msg
15959 (org-mobile-locate-entry (match-string 4))
15960 (error (nth 1 msg)))
15962 The return value will then be either a string with the error message,
15963 or a marker if everything is OK.
15965 If THIS-BUFFER is set, the outline path does not contain a file,
15966 only headings."
15967 (let* ((file (if this-buffer buffer-file-name (pop path)))
15968 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15969 (level 1)
15970 (lmin 1)
15971 (lmax 1)
15972 limit re end found pos heading cnt flevel)
15973 (unless buffer (error "File not found :%s" file))
15974 (with-current-buffer buffer
15975 (save-excursion
15976 (save-restriction
15977 (widen)
15978 (setq limit (point-max))
15979 (goto-char (point-min))
15980 (while (setq heading (pop path))
15981 (setq re (format org-complex-heading-regexp-format
15982 (regexp-quote heading)))
15983 (setq cnt 0 pos (point))
15984 (while (re-search-forward re end t)
15985 (setq level (- (match-end 1) (match-beginning 1)))
15986 (if (and (>= level lmin) (<= level lmax))
15987 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15988 (when (= cnt 0) (error "Heading not found on level %d: %s"
15989 lmax heading))
15990 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15991 lmax heading))
15992 (goto-char found)
15993 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15994 (setq end (save-excursion (org-end-of-subtree t t))))
15995 (when (org-at-heading-p)
15996 (point-marker)))))))
15998 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15999 "Find node HEADING in BUFFER.
16000 Return a marker to the heading if it was found, or nil if not.
16001 If POS-ONLY is set, return just the position instead of a marker.
16003 The heading text must match exact, but it may have a TODO keyword,
16004 a priority cookie and tags in the standard locations."
16005 (with-current-buffer (or buffer (current-buffer))
16006 (save-excursion
16007 (save-restriction
16008 (widen)
16009 (goto-char (point-min))
16010 (let (case-fold-search)
16011 (if (re-search-forward
16012 (format org-complex-heading-regexp-format
16013 (regexp-quote heading)) nil t)
16014 (if pos-only
16015 (match-beginning 0)
16016 (move-marker (make-marker) (match-beginning 0)))))))))
16018 (defun org-find-exact-heading-in-directory (heading &optional dir)
16019 "Find Org node headline HEADING in all .org files in directory DIR.
16020 When the target headline is found, return a marker to this location."
16021 (let ((files (directory-files (or dir default-directory)
16022 nil "\\`[^.#].*\\.org\\'"))
16023 file visiting m buffer)
16024 (catch 'found
16025 (while (setq file (pop files))
16026 (message "trying %s" file)
16027 (setq visiting (org-find-base-buffer-visiting file))
16028 (setq buffer (or visiting (find-file-noselect file)))
16029 (setq m (org-find-exact-headline-in-buffer
16030 heading buffer))
16031 (when (and (not m) (not visiting)) (kill-buffer buffer))
16032 (and m (throw 'found m))))))
16034 (defun org-find-entry-with-id (ident)
16035 "Locate the entry that contains the ID property with exact value IDENT.
16036 IDENT can be a string, a symbol or a number, this function will search for
16037 the string representation of it.
16038 Return the position where this entry starts, or nil if there is no such entry."
16039 (interactive "sID: ")
16040 (let ((id (cond
16041 ((stringp ident) ident)
16042 ((symbol-name ident) (symbol-name ident))
16043 ((numberp ident) (number-to-string ident))
16044 (t (error "IDENT %s must be a string, symbol or number" ident))))
16045 (case-fold-search nil))
16046 (save-excursion
16047 (save-restriction
16048 (widen)
16049 (goto-char (point-min))
16050 (when (re-search-forward
16051 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16052 nil t)
16053 (org-back-to-heading t)
16054 (point))))))
16056 ;;;; Timestamps
16058 (defvar org-last-changed-timestamp nil)
16059 (defvar org-last-inserted-timestamp nil
16060 "The last time stamp inserted with `org-insert-time-stamp'.")
16061 (defvar org-ts-what) ; dynamically scoped parameter
16063 (defun org-time-stamp (arg &optional inactive)
16064 "Prompt for a date/time and insert a time stamp.
16065 If the user specifies a time like HH:MM or if this command is
16066 called with at least one prefix argument, the time stamp contains
16067 the date and the time. Otherwise, only the date is be included.
16069 All parts of a date not specified by the user is filled in from
16070 the current date/time. So if you just press return without
16071 typing anything, the time stamp will represent the current
16072 date/time.
16074 If there is already a timestamp at the cursor, it will be
16075 modified.
16077 With two universal prefix arguments, insert an active timestamp
16078 with the current time without prompting the user.
16080 When called from lisp, the timestamp is inactive if INACTIVE is
16081 non-nil."
16082 (interactive "P")
16083 (let* ((ts nil)
16084 (default-time
16085 ;; Default time is either today, or, when entering a range,
16086 ;; the range start.
16087 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16088 (save-excursion
16089 (re-search-backward
16090 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16091 (- (point) 20) t)))
16092 (apply 'encode-time (org-parse-time-string (match-string 1)))
16093 (current-time)))
16094 (default-input (and ts (org-get-compact-tod ts)))
16095 (repeater (save-excursion
16096 (save-match-data
16097 (beginning-of-line)
16098 (when (re-search-forward
16099 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16100 (save-excursion (progn (end-of-line) (point))) t)
16101 (match-string 0)))))
16102 org-time-was-given org-end-time-was-given time)
16103 (cond
16104 ((and (org-at-timestamp-p t)
16105 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16106 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16107 (insert "--")
16108 (setq time (let ((this-command this-command))
16109 (org-read-date arg 'totime nil nil
16110 default-time default-input inactive)))
16111 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16112 ((org-at-timestamp-p t)
16113 (setq time (let ((this-command this-command))
16114 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16115 (when (org-at-timestamp-p t) ; just to get the match data
16116 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16117 (replace-match "")
16118 (setq org-last-changed-timestamp
16119 (org-insert-time-stamp
16120 time (or org-time-was-given arg)
16121 inactive nil nil (list org-end-time-was-given)))
16122 (when repeater (goto-char (1- (point))) (insert " " repeater)
16123 (setq org-last-changed-timestamp
16124 (concat (substring org-last-inserted-timestamp 0 -1)
16125 " " repeater ">"))))
16126 (message "Timestamp updated"))
16127 ((equal arg '(16))
16128 (org-insert-time-stamp (current-time) t inactive))
16130 (setq time (let ((this-command this-command))
16131 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16132 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16133 nil nil (list org-end-time-was-given))))))
16135 ;; FIXME: can we use this for something else, like computing time differences?
16136 (defun org-get-compact-tod (s)
16137 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16138 (let* ((t1 (match-string 1 s))
16139 (h1 (string-to-number (match-string 2 s)))
16140 (m1 (string-to-number (match-string 3 s)))
16141 (t2 (and (match-end 4) (match-string 5 s)))
16142 (h2 (and t2 (string-to-number (match-string 6 s))))
16143 (m2 (and t2 (string-to-number (match-string 7 s))))
16144 dh dm)
16145 (if (not t2)
16147 (setq dh (- h2 h1) dm (- m2 m1))
16148 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16149 (concat t1 "+" (number-to-string dh)
16150 (and (/= 0 dm) (format ":%02d" dm)))))))
16152 (defun org-time-stamp-inactive (&optional arg)
16153 "Insert an inactive time stamp.
16154 An inactive time stamp is enclosed in square brackets instead of angle
16155 brackets. It is inactive in the sense that it does not trigger agenda entries,
16156 does not link to the calendar and cannot be changed with the S-cursor keys.
16157 So these are more for recording a certain time/date."
16158 (interactive "P")
16159 (org-time-stamp arg 'inactive))
16161 (defvar org-date-ovl (make-overlay 1 1))
16162 (overlay-put org-date-ovl 'face 'org-date-selected)
16163 (org-detach-overlay org-date-ovl)
16165 (defvar org-ans1) ; dynamically scoped parameter
16166 (defvar org-ans2) ; dynamically scoped parameter
16168 (defvar org-plain-time-of-day-regexp) ; defined below
16170 (defvar org-overriding-default-time nil) ; dynamically scoped
16171 (defvar org-read-date-overlay nil)
16172 (defvar org-dcst nil) ; dynamically scoped
16173 (defvar org-read-date-history nil)
16174 (defvar org-read-date-final-answer nil)
16175 (defvar org-read-date-analyze-futurep nil)
16176 (defvar org-read-date-analyze-forced-year nil)
16177 (defvar org-read-date-inactive)
16179 (defvar org-read-date-minibuffer-local-map
16180 (let* ((org-replace-disputed-keys nil)
16181 (map (make-sparse-keymap)))
16182 (set-keymap-parent map minibuffer-local-map)
16183 (org-defkey map (kbd ".")
16184 (lambda () (interactive)
16185 ;; Are we at the beginning of the prompt?
16186 (if (looking-back "^[^:]+: ")
16187 (org-eval-in-calendar '(calendar-goto-today))
16188 (insert "."))))
16189 (org-defkey map (kbd "C-.")
16190 (lambda () (interactive)
16191 (org-eval-in-calendar '(calendar-goto-today))))
16192 (org-defkey map [(meta shift left)]
16193 (lambda () (interactive)
16194 (org-eval-in-calendar '(calendar-backward-month 1))))
16195 (org-defkey map [(meta shift right)]
16196 (lambda () (interactive)
16197 (org-eval-in-calendar '(calendar-forward-month 1))))
16198 (org-defkey map [(meta shift up)]
16199 (lambda () (interactive)
16200 (org-eval-in-calendar '(calendar-backward-year 1))))
16201 (org-defkey map [(meta shift down)]
16202 (lambda () (interactive)
16203 (org-eval-in-calendar '(calendar-forward-year 1))))
16204 (org-defkey map [?\e (shift left)]
16205 (lambda () (interactive)
16206 (org-eval-in-calendar '(calendar-backward-month 1))))
16207 (org-defkey map [?\e (shift right)]
16208 (lambda () (interactive)
16209 (org-eval-in-calendar '(calendar-forward-month 1))))
16210 (org-defkey map [?\e (shift up)]
16211 (lambda () (interactive)
16212 (org-eval-in-calendar '(calendar-backward-year 1))))
16213 (org-defkey map [?\e (shift down)]
16214 (lambda () (interactive)
16215 (org-eval-in-calendar '(calendar-forward-year 1))))
16216 (org-defkey map [(shift up)]
16217 (lambda () (interactive)
16218 (org-eval-in-calendar '(calendar-backward-week 1))))
16219 (org-defkey map [(shift down)]
16220 (lambda () (interactive)
16221 (org-eval-in-calendar '(calendar-forward-week 1))))
16222 (org-defkey map [(shift left)]
16223 (lambda () (interactive)
16224 (org-eval-in-calendar '(calendar-backward-day 1))))
16225 (org-defkey map [(shift right)]
16226 (lambda () (interactive)
16227 (org-eval-in-calendar '(calendar-forward-day 1))))
16228 (org-defkey map "!"
16229 (lambda () (interactive)
16230 (org-eval-in-calendar '(diary-view-entries))
16231 (message "")))
16232 (org-defkey map ">"
16233 (lambda () (interactive)
16234 (org-eval-in-calendar '(scroll-calendar-left 1))))
16235 (org-defkey map "<"
16236 (lambda () (interactive)
16237 (org-eval-in-calendar '(scroll-calendar-right 1))))
16238 (org-defkey map "\C-v"
16239 (lambda () (interactive)
16240 (org-eval-in-calendar
16241 '(calendar-scroll-left-three-months 1))))
16242 (org-defkey map "\M-v"
16243 (lambda () (interactive)
16244 (org-eval-in-calendar
16245 '(calendar-scroll-right-three-months 1))))
16246 map)
16247 "Keymap for minibuffer commands when using `org-read-date'.")
16249 (defvar org-def)
16250 (defvar org-defdecode)
16251 (defvar org-with-time)
16253 (defun org-read-date (&optional org-with-time to-time from-string prompt
16254 default-time default-input inactive)
16255 "Read a date, possibly a time, and make things smooth for the user.
16256 The prompt will suggest to enter an ISO date, but you can also enter anything
16257 which will at least partially be understood by `parse-time-string'.
16258 Unrecognized parts of the date will default to the current day, month, year,
16259 hour and minute. If this command is called to replace a timestamp at point,
16260 or to enter the second timestamp of a range, the default time is taken
16261 from the existing stamp. Furthermore, the command prefers the future,
16262 so if you are giving a date where the year is not given, and the day-month
16263 combination is already past in the current year, it will assume you
16264 mean next year. For details, see the manual. A few examples:
16266 3-2-5 --> 2003-02-05
16267 feb 15 --> currentyear-02-15
16268 2/15 --> currentyear-02-15
16269 sep 12 9 --> 2009-09-12
16270 12:45 --> today 12:45
16271 22 sept 0:34 --> currentyear-09-22 0:34
16272 12 --> currentyear-currentmonth-12
16273 Fri --> nearest Friday after today
16274 -Tue --> last Tuesday
16275 etc.
16277 Furthermore you can specify a relative date by giving, as the *first* thing
16278 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16279 change in days weeks, months, years.
16280 With a single plus or minus, the date is relative to today. With a double
16281 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16282 +4d --> four days from today
16283 +4 --> same as above
16284 +2w --> two weeks from today
16285 ++5 --> five days from default date
16287 The function understands only English month and weekday abbreviations.
16289 While prompting, a calendar is popped up - you can also select the
16290 date with the mouse (button 1). The calendar shows a period of three
16291 months. To scroll it to other months, use the keys `>' and `<'.
16292 If you don't like the calendar, turn it off with
16293 \(setq org-read-date-popup-calendar nil)
16295 With optional argument TO-TIME, the date will immediately be converted
16296 to an internal time.
16297 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16298 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16299 still enter a time, and this function will inform the calling routine
16300 about this change. The calling routine may then choose to change the
16301 format used to insert the time stamp into the buffer to include the time.
16302 With optional argument FROM-STRING, read from this string instead from
16303 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16304 the time/date that is used for everything that is not specified by the
16305 user."
16306 (require 'parse-time)
16307 (let* ((org-time-stamp-rounding-minutes
16308 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16309 (org-dcst org-display-custom-times)
16310 (ct (org-current-time))
16311 (org-def (or org-overriding-default-time default-time ct))
16312 (org-defdecode (decode-time org-def))
16313 (dummy (progn
16314 (when (< (nth 2 org-defdecode) org-extend-today-until)
16315 (setcar (nthcdr 2 org-defdecode) -1)
16316 (setcar (nthcdr 1 org-defdecode) 59)
16317 (setq org-def (apply 'encode-time org-defdecode)
16318 org-defdecode (decode-time org-def)))))
16319 (mouse-autoselect-window nil) ; Don't let the mouse jump
16320 (calendar-frame-setup nil)
16321 (calendar-setup nil)
16322 (calendar-move-hook nil)
16323 (calendar-view-diary-initially-flag nil)
16324 (calendar-view-holidays-initially-flag nil)
16325 (timestr (format-time-string
16326 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16327 (prompt (concat (if prompt (concat prompt " ") "")
16328 (format "Date+time [%s]: " timestr)))
16329 ans (org-ans0 "") org-ans1 org-ans2 final)
16331 (cond
16332 (from-string (setq ans from-string))
16333 (org-read-date-popup-calendar
16334 (save-excursion
16335 (save-window-excursion
16336 (calendar)
16337 (org-eval-in-calendar '(setq cursor-type nil) t)
16338 (unwind-protect
16339 (progn
16340 (calendar-forward-day (- (time-to-days org-def)
16341 (calendar-absolute-from-gregorian
16342 (calendar-current-date))))
16343 (org-eval-in-calendar nil t)
16344 (let* ((old-map (current-local-map))
16345 (map (copy-keymap calendar-mode-map))
16346 (minibuffer-local-map
16347 (copy-keymap org-read-date-minibuffer-local-map)))
16348 (org-defkey map (kbd "RET") 'org-calendar-select)
16349 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16350 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16351 (unwind-protect
16352 (progn
16353 (use-local-map map)
16354 (setq org-read-date-inactive inactive)
16355 (add-hook 'post-command-hook 'org-read-date-display)
16356 (setq org-ans0 (read-string prompt default-input
16357 'org-read-date-history nil))
16358 ;; org-ans0: from prompt
16359 ;; org-ans1: from mouse click
16360 ;; org-ans2: from calendar motion
16361 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16362 (remove-hook 'post-command-hook 'org-read-date-display)
16363 (use-local-map old-map)
16364 (when org-read-date-overlay
16365 (delete-overlay org-read-date-overlay)
16366 (setq org-read-date-overlay nil)))))
16367 (bury-buffer "*Calendar*")))))
16369 (t ; Naked prompt only
16370 (unwind-protect
16371 (setq ans (read-string prompt default-input
16372 'org-read-date-history timestr))
16373 (when org-read-date-overlay
16374 (delete-overlay org-read-date-overlay)
16375 (setq org-read-date-overlay nil)))))
16377 (setq final (org-read-date-analyze ans org-def org-defdecode))
16379 (when org-read-date-analyze-forced-year
16380 (message "Year was forced into %s"
16381 (if org-read-date-force-compatible-dates
16382 "compatible range (1970-2037)"
16383 "range representable on this machine"))
16384 (ding))
16386 ;; One round trip to get rid of 34th of August and stuff like that....
16387 (setq final (decode-time (apply 'encode-time final)))
16389 (setq org-read-date-final-answer ans)
16391 (if to-time
16392 (apply 'encode-time final)
16393 (if (and (boundp 'org-time-was-given) org-time-was-given)
16394 (format "%04d-%02d-%02d %02d:%02d"
16395 (nth 5 final) (nth 4 final) (nth 3 final)
16396 (nth 2 final) (nth 1 final))
16397 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16399 (defun org-read-date-display ()
16400 "Display the current date prompt interpretation in the minibuffer."
16401 (when org-read-date-display-live
16402 (when org-read-date-overlay
16403 (delete-overlay org-read-date-overlay))
16404 (when (minibufferp (current-buffer))
16405 (save-excursion
16406 (end-of-line 1)
16407 (while (not (equal (buffer-substring
16408 (max (point-min) (- (point) 4)) (point))
16409 " "))
16410 (insert " ")))
16411 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16412 " " (or org-ans1 org-ans2)))
16413 (org-end-time-was-given nil)
16414 (f (org-read-date-analyze ans org-def org-defdecode))
16415 (fmts (if org-dcst
16416 org-time-stamp-custom-formats
16417 org-time-stamp-formats))
16418 (fmt (if (or org-with-time
16419 (and (boundp 'org-time-was-given) org-time-was-given))
16420 (cdr fmts)
16421 (car fmts)))
16422 (txt (format-time-string fmt (apply 'encode-time f)))
16423 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16424 (txt (concat "=> " txt)))
16425 (when (and org-end-time-was-given
16426 (string-match org-plain-time-of-day-regexp txt))
16427 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16428 org-end-time-was-given
16429 (substring txt (match-end 0)))))
16430 (when org-read-date-analyze-futurep
16431 (setq txt (concat txt " (=>F)")))
16432 (setq org-read-date-overlay
16433 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16434 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16436 (defun org-read-date-analyze (ans org-def org-defdecode)
16437 "Analyze the combined answer of the date prompt."
16438 ;; FIXME: cleanup and comment
16439 (let ((nowdecode (decode-time (current-time)))
16440 delta deltan deltaw deltadef year month day
16441 hour minute second wday pm h2 m2 tl wday1
16442 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16443 (setq org-read-date-analyze-futurep nil
16444 org-read-date-analyze-forced-year nil)
16445 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16446 (setq ans "+0"))
16448 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16449 (setq ans (replace-match "" t t ans)
16450 deltan (car delta)
16451 deltaw (nth 1 delta)
16452 deltadef (nth 2 delta)))
16454 ;; Check if there is an iso week date in there. If yes, store the
16455 ;; info and postpone interpreting it until the rest of the parsing
16456 ;; is done.
16457 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16458 (setq iso-year (if (match-end 1)
16459 (org-small-year-to-year
16460 (string-to-number (match-string 1 ans))))
16461 iso-weekday (if (match-end 3)
16462 (string-to-number (match-string 3 ans)))
16463 iso-week (string-to-number (match-string 2 ans)))
16464 (setq ans (replace-match "" t t ans)))
16466 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16467 (when (string-match
16468 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16469 (setq year (if (match-end 2)
16470 (string-to-number (match-string 2 ans))
16471 (progn (setq kill-year t)
16472 (string-to-number (format-time-string "%Y"))))
16473 month (string-to-number (match-string 3 ans))
16474 day (string-to-number (match-string 4 ans)))
16475 (if (< year 100) (setq year (+ 2000 year)))
16476 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16477 t nil ans)))
16479 ;; Help matching dotted european dates
16480 (when (string-match
16481 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16482 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16483 (setq kill-year t)
16484 (string-to-number (format-time-string "%Y")))
16485 day (string-to-number (match-string 1 ans))
16486 month (string-to-number (match-string 2 ans))
16487 ans (replace-match (format "%04d-%02d-%02d" year month day)
16488 t nil ans)))
16490 ;; Help matching american dates, like 5/30 or 5/30/7
16491 (when (string-match
16492 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16493 (setq year (if (match-end 4)
16494 (string-to-number (match-string 4 ans))
16495 (progn (setq kill-year t)
16496 (string-to-number (format-time-string "%Y"))))
16497 month (string-to-number (match-string 1 ans))
16498 day (string-to-number (match-string 2 ans)))
16499 (if (< year 100) (setq year (+ 2000 year)))
16500 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16501 t nil ans)))
16502 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16503 ;; If there is a time with am/pm, and *no* time without it, we convert
16504 ;; so that matching will be successful.
16505 (loop for i from 1 to 2 do ; twice, for end time as well
16506 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16507 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16508 (setq hour (string-to-number (match-string 1 ans))
16509 minute (if (match-end 3)
16510 (string-to-number (match-string 3 ans))
16512 pm (equal ?p
16513 (string-to-char (downcase (match-string 4 ans)))))
16514 (if (and (= hour 12) (not pm))
16515 (setq hour 0)
16516 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16517 (setq ans (replace-match (format "%02d:%02d" hour minute)
16518 t t ans))))
16520 ;; Check if a time range is given as a duration
16521 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16522 (setq hour (string-to-number (match-string 1 ans))
16523 h2 (+ hour (string-to-number (match-string 3 ans)))
16524 minute (string-to-number (match-string 2 ans))
16525 m2 (+ minute (if (match-end 5) (string-to-number
16526 (match-string 5 ans))0)))
16527 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16528 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16529 t t ans)))
16531 ;; Check if there is a time range
16532 (when (boundp 'org-end-time-was-given)
16533 (setq org-time-was-given nil)
16534 (when (and (string-match org-plain-time-of-day-regexp ans)
16535 (match-end 8))
16536 (setq org-end-time-was-given (match-string 8 ans))
16537 (setq ans (concat (substring ans 0 (match-beginning 7))
16538 (substring ans (match-end 7))))))
16540 (setq tl (parse-time-string ans)
16541 day (or (nth 3 tl) (nth 3 org-defdecode))
16542 month (or (nth 4 tl)
16543 (if (and org-read-date-prefer-future
16544 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16545 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16546 (nth 4 org-defdecode)))
16547 year (or (and (not kill-year) (nth 5 tl))
16548 (if (and org-read-date-prefer-future
16549 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16550 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16551 (nth 5 org-defdecode)))
16552 hour (or (nth 2 tl) (nth 2 org-defdecode))
16553 minute (or (nth 1 tl) (nth 1 org-defdecode))
16554 second (or (nth 0 tl) 0)
16555 wday (nth 6 tl))
16557 (when (and (eq org-read-date-prefer-future 'time)
16558 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16559 (equal day (nth 3 nowdecode))
16560 (equal month (nth 4 nowdecode))
16561 (equal year (nth 5 nowdecode))
16562 (nth 2 tl)
16563 (or (< (nth 2 tl) (nth 2 nowdecode))
16564 (and (= (nth 2 tl) (nth 2 nowdecode))
16565 (nth 1 tl)
16566 (< (nth 1 tl) (nth 1 nowdecode)))))
16567 (setq day (1+ day)
16568 futurep t))
16570 ;; Special date definitions below
16571 (cond
16572 (iso-week
16573 ;; There was an iso week
16574 (require 'cal-iso)
16575 (setq futurep nil)
16576 (setq year (or iso-year year)
16577 day (or iso-weekday wday 1)
16578 wday nil ; to make sure that the trigger below does not match
16579 iso-date (calendar-gregorian-from-absolute
16580 (calendar-absolute-from-iso
16581 (list iso-week day year))))
16582 ; FIXME: Should we also push ISO weeks into the future?
16583 ; (when (and org-read-date-prefer-future
16584 ; (not iso-year)
16585 ; (< (calendar-absolute-from-gregorian iso-date)
16586 ; (time-to-days (current-time))))
16587 ; (setq year (1+ year)
16588 ; iso-date (calendar-gregorian-from-absolute
16589 ; (calendar-absolute-from-iso
16590 ; (list iso-week day year)))))
16591 (setq month (car iso-date)
16592 year (nth 2 iso-date)
16593 day (nth 1 iso-date)))
16594 (deltan
16595 (setq futurep nil)
16596 (unless deltadef
16597 (let ((now (decode-time (current-time))))
16598 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16599 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16600 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16601 ((equal deltaw "m") (setq month (+ month deltan)))
16602 ((equal deltaw "y") (setq year (+ year deltan)))))
16603 ((and wday (not (nth 3 tl)))
16604 ;; Weekday was given, but no day, so pick that day in the week
16605 ;; on or after the derived date.
16606 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16607 (unless (equal wday wday1)
16608 (setq day (+ day (% (- wday wday1 -7) 7))))))
16609 (if (and (boundp 'org-time-was-given)
16610 (nth 2 tl))
16611 (setq org-time-was-given t))
16612 (if (< year 100) (setq year (+ 2000 year)))
16613 ;; Check of the date is representable
16614 (if org-read-date-force-compatible-dates
16615 (progn
16616 (if (< year 1970)
16617 (setq year 1970 org-read-date-analyze-forced-year t))
16618 (if (> year 2037)
16619 (setq year 2037 org-read-date-analyze-forced-year t)))
16620 (condition-case nil
16621 (ignore (encode-time second minute hour day month year))
16622 (error
16623 (setq year (nth 5 org-defdecode))
16624 (setq org-read-date-analyze-forced-year t))))
16625 (setq org-read-date-analyze-futurep futurep)
16626 (list second minute hour day month year)))
16628 (defvar parse-time-weekdays)
16629 (defun org-read-date-get-relative (s today default)
16630 "Check string S for special relative date string.
16631 TODAY and DEFAULT are internal times, for today and for a default.
16632 Return shift list (N what def-flag)
16633 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16634 N is the number of WHATs to shift.
16635 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16636 the DEFAULT date rather than TODAY."
16637 (require 'parse-time)
16638 (when (and
16639 (string-match
16640 (concat
16641 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16642 "\\([0-9]+\\)?"
16643 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16644 "\\([ \t]\\|$\\)") s)
16645 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16646 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16647 (string-to-char (substring (match-string 1 s) -1))
16648 ?+))
16649 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16650 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16651 (what (if (match-end 3) (match-string 3 s) "d"))
16652 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16653 (date (if rel default today))
16654 (wday (nth 6 (decode-time date)))
16655 delta)
16656 (if wday1
16657 (progn
16658 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16659 (if (= delta 0) (setq delta 7))
16660 (if (= dir ?-)
16661 (progn
16662 (setq delta (- delta 7))
16663 (if (= delta 0) (setq delta -7))))
16664 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16665 (list delta "d" rel))
16666 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16668 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16669 "Turn a user-specified date into the internal representation.
16670 The internal representation needed by the calendar is (month day year).
16671 This is a wrapper to handle the brain-dead convention in calendar that
16672 user function argument order change dependent on argument order."
16673 (if (boundp 'calendar-date-style)
16674 (cond
16675 ((eq calendar-date-style 'american)
16676 (list arg1 arg2 arg3))
16677 ((eq calendar-date-style 'european)
16678 (list arg2 arg1 arg3))
16679 ((eq calendar-date-style 'iso)
16680 (list arg2 arg3 arg1)))
16681 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16682 (if (org-bound-and-true-p european-calendar-style)
16683 (list arg2 arg1 arg3)
16684 (list arg1 arg2 arg3)))))
16686 (defun org-eval-in-calendar (form &optional keepdate)
16687 "Eval FORM in the calendar window and return to current window.
16688 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16689 otherwise stick to the current value of `org-ans2'."
16690 (let ((sf (selected-frame))
16691 (sw (selected-window)))
16692 (select-window (get-buffer-window "*Calendar*" t))
16693 (eval form)
16694 (when (and (not keepdate) (calendar-cursor-to-date))
16695 (let* ((date (calendar-cursor-to-date))
16696 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16697 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16698 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16699 (select-window sw)
16700 (org-select-frame-set-input-focus sf)))
16702 (defun org-calendar-select ()
16703 "Return to `org-read-date' with the date currently selected.
16704 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16705 (interactive)
16706 (when (calendar-cursor-to-date)
16707 (let* ((date (calendar-cursor-to-date))
16708 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16709 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16710 (if (active-minibuffer-window) (exit-minibuffer))))
16712 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16713 "Insert a date stamp for the date given by the internal TIME.
16714 WITH-HM means use the stamp format that includes the time of the day.
16715 INACTIVE means use square brackets instead of angular ones, so that the
16716 stamp will not contribute to the agenda.
16717 PRE and POST are optional strings to be inserted before and after the
16718 stamp.
16719 The command returns the inserted time stamp."
16720 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16721 stamp)
16722 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16723 (insert-before-markers (or pre ""))
16724 (when (listp extra)
16725 (setq extra (car extra))
16726 (if (and (stringp extra)
16727 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16728 (setq extra (format "-%02d:%02d"
16729 (string-to-number (match-string 1 extra))
16730 (string-to-number (match-string 2 extra))))
16731 (setq extra nil)))
16732 (when extra
16733 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16734 (insert-before-markers (setq stamp (format-time-string fmt time)))
16735 (insert-before-markers (or post ""))
16736 (setq org-last-inserted-timestamp stamp)))
16738 (defun org-toggle-time-stamp-overlays ()
16739 "Toggle the use of custom time stamp formats."
16740 (interactive)
16741 (setq org-display-custom-times (not org-display-custom-times))
16742 (unless org-display-custom-times
16743 (let ((p (point-min)) (bmp (buffer-modified-p)))
16744 (while (setq p (next-single-property-change p 'display))
16745 (if (and (get-text-property p 'display)
16746 (eq (get-text-property p 'face) 'org-date))
16747 (remove-text-properties
16748 p (setq p (next-single-property-change p 'display))
16749 '(display t))))
16750 (set-buffer-modified-p bmp)))
16751 (if (featurep 'xemacs)
16752 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16753 (org-restart-font-lock)
16754 (setq org-table-may-need-update t)
16755 (if org-display-custom-times
16756 (message "Time stamps are overlaid with custom format")
16757 (message "Time stamp overlays removed")))
16759 (defun org-display-custom-time (beg end)
16760 "Overlay modified time stamp format over timestamp between BEG and END."
16761 (let* ((ts (buffer-substring beg end))
16762 t1 w1 with-hm tf time str w2 (off 0))
16763 (save-match-data
16764 (setq t1 (org-parse-time-string ts t))
16765 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16766 (setq off (- (match-end 0) (match-beginning 0)))))
16767 (setq end (- end off))
16768 (setq w1 (- end beg)
16769 with-hm (and (nth 1 t1) (nth 2 t1))
16770 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16771 time (org-fix-decoded-time t1)
16772 str (org-add-props
16773 (format-time-string
16774 (substring tf 1 -1) (apply 'encode-time time))
16775 nil 'mouse-face 'highlight)
16776 w2 (length str))
16777 (if (not (= w2 w1))
16778 (add-text-properties (1+ beg) (+ 2 beg)
16779 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16780 (if (featurep 'xemacs)
16781 (progn
16782 (put-text-property beg end 'invisible t)
16783 (put-text-property beg end 'end-glyph (make-glyph str)))
16784 (put-text-property beg end 'display str))))
16786 (defun org-translate-time (string)
16787 "Translate all timestamps in STRING to custom format.
16788 But do this only if the variable `org-display-custom-times' is set."
16789 (when org-display-custom-times
16790 (save-match-data
16791 (let* ((start 0)
16792 (re org-ts-regexp-both)
16793 t1 with-hm inactive tf time str beg end)
16794 (while (setq start (string-match re string start))
16795 (setq beg (match-beginning 0)
16796 end (match-end 0)
16797 t1 (save-match-data
16798 (org-parse-time-string (substring string beg end) t))
16799 with-hm (and (nth 1 t1) (nth 2 t1))
16800 inactive (equal (substring string beg (1+ beg)) "[")
16801 tf (funcall (if with-hm 'cdr 'car)
16802 org-time-stamp-custom-formats)
16803 time (org-fix-decoded-time t1)
16804 str (format-time-string
16805 (concat
16806 (if inactive "[" "<") (substring tf 1 -1)
16807 (if inactive "]" ">"))
16808 (apply 'encode-time time))
16809 string (replace-match str t t string)
16810 start (+ start (length str)))))))
16811 string)
16813 (defun org-fix-decoded-time (time)
16814 "Set 0 instead of nil for the first 6 elements of time.
16815 Don't touch the rest."
16816 (let ((n 0))
16817 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16819 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16821 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16822 "Difference between TIMESTAMP-STRING and now in days.
16823 If SECONDS is non-nil, return the difference in seconds."
16824 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16825 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16826 (funcall fdiff (current-time)))))
16828 (defun org-deadline-close (timestamp-string &optional ndays)
16829 "Is the time in TIMESTAMP-STRING close to the current date?"
16830 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16831 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16832 (not (org-entry-is-done-p))))
16834 (defun org-get-wdays (ts &optional delay zero-delay)
16835 "Get the deadline lead time appropriate for timestring TS.
16836 When DELAY is non-nil, get the delay time for scheduled items
16837 instead of the deadline lead time. When ZERO-DELAY is non-nil
16838 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16839 don't try to find the delay cookie in the scheduled timestamp."
16840 (let ((tv (if delay org-scheduled-delay-days
16841 org-deadline-warning-days)))
16842 (cond
16843 ((or (and delay (< tv 0))
16844 (and delay zero-delay (<= tv 0))
16845 (and (not delay) (<= tv 0)))
16846 ;; Enforce this value no matter what
16847 (- tv))
16848 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16849 ;; lead time is specified.
16850 (floor (* (string-to-number (match-string 1 ts))
16851 (cdr (assoc (match-string 2 ts)
16852 '(("d" . 1) ("w" . 7)
16853 ("m" . 30.4) ("y" . 365.25)
16854 ("h" . 0.041667)))))))
16855 ;; go for the default.
16856 (t tv))))
16858 (defun org-calendar-select-mouse (ev)
16859 "Return to `org-read-date' with the date currently selected.
16860 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16861 (interactive "e")
16862 (mouse-set-point ev)
16863 (when (calendar-cursor-to-date)
16864 (let* ((date (calendar-cursor-to-date))
16865 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16866 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16867 (if (active-minibuffer-window) (exit-minibuffer))))
16869 (defun org-check-deadlines (ndays)
16870 "Check if there are any deadlines due or past due.
16871 A deadline is considered due if it happens within `org-deadline-warning-days'
16872 days from today's date. If the deadline appears in an entry marked DONE,
16873 it is not shown. The prefix arg NDAYS can be used to test that many
16874 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16875 (interactive "P")
16876 (let* ((org-warn-days
16877 (cond
16878 ((equal ndays '(4)) 100000)
16879 (ndays (prefix-numeric-value ndays))
16880 (t (abs org-deadline-warning-days))))
16881 (case-fold-search nil)
16882 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16883 (callback
16884 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16886 (message "%d deadlines past-due or due within %d days"
16887 (org-occur regexp nil callback)
16888 org-warn-days)))
16890 (defsubst org-re-timestamp (type)
16891 "Return a regexp for timestamp TYPE.
16892 Allowed values for TYPE are:
16894 all: all timestamps
16895 active: only active timestamps (<...>)
16896 inactive: only inactive timestamps ([...])
16897 scheduled: only scheduled timestamps
16898 deadline: only deadline timestamps
16899 closed: only closed time-stamps
16901 When TYPE is nil, fall back on returning a regexp that matches
16902 both scheduled and deadline timestamps."
16903 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16904 ((eq type 'active) org-ts-regexp)
16905 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16906 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16907 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16908 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16909 ((eq type 'scheduled-or-deadline)
16910 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16912 (defun org-check-before-date (date)
16913 "Check if there are deadlines or scheduled entries before DATE."
16914 (interactive (list (org-read-date)))
16915 (let ((case-fold-search nil)
16916 (regexp (org-re-timestamp org-ts-type))
16917 (callback
16918 (lambda () (time-less-p
16919 (org-time-string-to-time (match-string 1))
16920 (org-time-string-to-time date)))))
16921 (message "%d entries before %s"
16922 (org-occur regexp nil callback) date)))
16924 (defun org-check-after-date (date)
16925 "Check if there are deadlines or scheduled entries after DATE."
16926 (interactive (list (org-read-date)))
16927 (let ((case-fold-search nil)
16928 (regexp (org-re-timestamp org-ts-type))
16929 (callback
16930 (lambda () (not
16931 (time-less-p
16932 (org-time-string-to-time (match-string 1))
16933 (org-time-string-to-time date))))))
16934 (message "%d entries after %s"
16935 (org-occur regexp nil callback) date)))
16937 (defun org-check-dates-range (start-date end-date)
16938 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16939 (interactive (list (org-read-date nil nil nil "Range starts")
16940 (org-read-date nil nil nil "Range end")))
16941 (let ((case-fold-search nil)
16942 (regexp (org-re-timestamp org-ts-type))
16943 (callback
16944 (lambda ()
16945 (let ((match (match-string 1)))
16946 (and
16947 (not (time-less-p
16948 (org-time-string-to-time match)
16949 (org-time-string-to-time start-date)))
16950 (time-less-p
16951 (org-time-string-to-time match)
16952 (org-time-string-to-time end-date)))))))
16953 (message "%d entries between %s and %s"
16954 (org-occur regexp nil callback) start-date end-date)))
16956 (defun org-evaluate-time-range (&optional to-buffer)
16957 "Evaluate a time range by computing the difference between start and end.
16958 Normally the result is just printed in the echo area, but with prefix arg
16959 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16960 If the time range is actually in a table, the result is inserted into the
16961 next column.
16962 For time difference computation, a year is assumed to be exactly 365
16963 days in order to avoid rounding problems."
16964 (interactive "P")
16966 (org-clock-update-time-maybe)
16967 (save-excursion
16968 (unless (org-at-date-range-p t)
16969 (goto-char (point-at-bol))
16970 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16971 (if (not (org-at-date-range-p t))
16972 (user-error "Not at a time-stamp range, and none found in current line")))
16973 (let* ((ts1 (match-string 1))
16974 (ts2 (match-string 2))
16975 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16976 (match-end (match-end 0))
16977 (time1 (org-time-string-to-time ts1))
16978 (time2 (org-time-string-to-time ts2))
16979 (t1 (org-float-time time1))
16980 (t2 (org-float-time time2))
16981 (diff (abs (- t2 t1)))
16982 (negative (< (- t2 t1) 0))
16983 ;; (ys (floor (* 365 24 60 60)))
16984 (ds (* 24 60 60))
16985 (hs (* 60 60))
16986 (fy "%dy %dd %02d:%02d")
16987 (fy1 "%dy %dd")
16988 (fd "%dd %02d:%02d")
16989 (fd1 "%dd")
16990 (fh "%02d:%02d")
16991 y d h m align)
16992 (if havetime
16993 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16995 d (floor (/ diff ds)) diff (mod diff ds)
16996 h (floor (/ diff hs)) diff (mod diff hs)
16997 m (floor (/ diff 60)))
16998 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17000 d (floor (+ (/ diff ds) 0.5))
17001 h 0 m 0))
17002 (if (not to-buffer)
17003 (message "%s" (org-make-tdiff-string y d h m))
17004 (if (org-at-table-p)
17005 (progn
17006 (goto-char match-end)
17007 (setq align t)
17008 (and (looking-at " *|") (goto-char (match-end 0))))
17009 (goto-char match-end))
17010 (if (looking-at
17011 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17012 (replace-match ""))
17013 (if negative (insert " -"))
17014 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17015 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17016 (insert " " (format fh h m))))
17017 (if align (org-table-align))
17018 (message "Time difference inserted")))))
17020 (defun org-make-tdiff-string (y d h m)
17021 (let ((fmt "")
17022 (l nil))
17023 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17024 l (push y l)))
17025 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17026 l (push d l)))
17027 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17028 l (push h l)))
17029 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17030 l (push m l)))
17031 (apply 'format fmt (nreverse l))))
17033 (defun org-time-string-to-time (s &optional buffer pos)
17034 "Convert a timestamp string into internal time."
17035 (condition-case errdata
17036 (apply 'encode-time (org-parse-time-string s))
17037 (error (error "Bad timestamp `%s'%s\nError was: %s"
17038 s (if (not (and buffer pos))
17040 (format " at %d in buffer `%s'" pos buffer))
17041 (cdr errdata)))))
17043 (defun org-time-string-to-seconds (s)
17044 "Convert a timestamp string to a number of seconds."
17045 (org-float-time (org-time-string-to-time s)))
17047 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17048 "Convert a time stamp to an absolute day number.
17049 If there is a specifier for a cyclic time stamp, get the closest
17050 date to DAYNR.
17051 PREFER and SHOW-ALL are passed through to `org-closest-date'.
17052 The variable `date' is bound by the calendar when this is called."
17053 (cond
17054 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17055 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17056 daynr
17057 (+ daynr 1000)))
17058 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
17059 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17060 (time-to-days (current-time))) (match-string 0 s)
17061 prefer show-all))
17062 (t (time-to-days
17063 (condition-case errdata
17064 (apply 'encode-time (org-parse-time-string s))
17065 (error (error "Bad timestamp `%s'%s\nError was: %s"
17066 s (if (not (and buffer pos))
17068 (format " at %d in buffer `%s'" pos buffer))
17069 (cdr errdata))))))))
17071 (defun org-days-to-iso-week (days)
17072 "Return the iso week number."
17073 (require 'cal-iso)
17074 (car (calendar-iso-from-absolute days)))
17076 (defun org-small-year-to-year (year)
17077 "Convert 2-digit years into 4-digit years.
17078 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17079 The year 2000 cannot be abbreviated. Any year larger than 99
17080 is returned unchanged."
17081 (if (< year 38)
17082 (setq year (+ 2000 year))
17083 (if (< year 100)
17084 (setq year (+ 1900 year))))
17085 year)
17087 (defun org-time-from-absolute (d)
17088 "Return the time corresponding to date D.
17089 D may be an absolute day number, or a calendar-type list (month day year)."
17090 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17091 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17093 (defun org-calendar-holiday ()
17094 "List of holidays, for Diary display in Org-mode."
17095 (require 'holidays)
17096 (let ((hl (funcall
17097 (if (fboundp 'calendar-check-holidays)
17098 'calendar-check-holidays 'check-calendar-holidays) date)))
17099 (if hl (mapconcat 'identity hl "; "))))
17101 (defun org-diary-sexp-entry (sexp entry date)
17102 "Process a SEXP diary ENTRY for DATE."
17103 (require 'diary-lib)
17104 (let ((result (if calendar-debug-sexp
17105 (let ((stack-trace-on-error t))
17106 (eval (car (read-from-string sexp))))
17107 (condition-case nil
17108 (eval (car (read-from-string sexp)))
17109 (error
17110 (beep)
17111 (message "Bad sexp at line %d in %s: %s"
17112 (org-current-line)
17113 (buffer-file-name) sexp)
17114 (sleep-for 2))))))
17115 (cond ((stringp result) (split-string result "; "))
17116 ((and (consp result)
17117 (not (consp (cdr result)))
17118 (stringp (cdr result))) (cdr result))
17119 ((and (consp result)
17120 (stringp (car result))) result)
17121 (result entry))))
17123 (defun org-diary-to-ical-string (frombuf)
17124 "Get iCalendar entries from diary entries in buffer FROMBUF.
17125 This uses the icalendar.el library."
17126 (let* ((tmpdir (if (featurep 'xemacs)
17127 (temp-directory)
17128 temporary-file-directory))
17129 (tmpfile (make-temp-name
17130 (expand-file-name "orgics" tmpdir)))
17131 buf rtn b e)
17132 (with-current-buffer frombuf
17133 (icalendar-export-region (point-min) (point-max) tmpfile)
17134 (setq buf (find-buffer-visiting tmpfile))
17135 (set-buffer buf)
17136 (goto-char (point-min))
17137 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17138 (setq b (match-beginning 0)))
17139 (goto-char (point-max))
17140 (if (re-search-backward "^END:VEVENT" nil t)
17141 (setq e (match-end 0)))
17142 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17143 (kill-buffer buf)
17144 (delete-file tmpfile)
17145 rtn))
17147 (defun org-closest-date (start current change prefer show-all)
17148 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17149 When PREFER is `past', return a date that is either CURRENT or past.
17150 When PREFER is `future', return a date that is either CURRENT or future.
17151 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17152 ;; Make the proper lists from the dates
17153 (catch 'exit
17154 (let ((a1 '(("h" . hour)
17155 ("d" . day)
17156 ("w" . week)
17157 ("m" . month)
17158 ("y" . year)))
17159 (shour (nth 2 (org-parse-time-string start)))
17160 dn dw sday cday n1 n2 n0
17161 d m y y1 y2 date1 date2 nmonths nm ny m2)
17163 (setq start (org-date-to-gregorian start)
17164 current (org-date-to-gregorian
17165 (if show-all
17166 current
17167 (time-to-days (current-time))))
17168 sday (calendar-absolute-from-gregorian start)
17169 cday (calendar-absolute-from-gregorian current))
17171 (if (<= cday sday) (throw 'exit sday))
17173 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17174 (setq dn (string-to-number (match-string 1 change))
17175 dw (cdr (assoc (match-string 2 change) a1)))
17176 (user-error "Invalid change specifier: %s" change))
17177 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17178 (cond
17179 ((eq dw 'hour)
17180 (let ((missing-hours
17181 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17182 dn)))
17183 (setq n1 (if (zerop missing-hours) cday
17184 (- cday (1+ (floor (/ missing-hours 24)))))
17185 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17186 ((eq dw 'day)
17187 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17188 n2 (+ n1 dn)))
17189 ((eq dw 'year)
17190 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17191 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17192 (setq date1 (list m d y1)
17193 n1 (calendar-absolute-from-gregorian date1)
17194 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17195 n2 (calendar-absolute-from-gregorian date2)))
17196 ((eq dw 'month)
17197 ;; approx number of month between the two dates
17198 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17199 ;; How often does dn fit in there?
17200 (setq d (nth 1 start) m (car start) y (nth 2 start)
17201 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17202 m (+ m nm)
17203 ny (floor (/ m 12))
17204 y (+ y ny)
17205 m (- m (* ny 12)))
17206 (while (> m 12) (setq m (- m 12) y (1+ y)))
17207 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17208 (setq m2 (+ m dn) y2 y)
17209 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17210 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17211 (while (<= n2 cday)
17212 (setq n1 n2 m m2 y y2)
17213 (setq m2 (+ m dn) y2 y)
17214 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17215 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17216 ;; Make sure n1 is the earlier date
17217 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17218 (if show-all
17219 (cond
17220 ((eq prefer 'past) (if (= cday n2) n2 n1))
17221 ((eq prefer 'future) (if (= cday n1) n1 n2))
17222 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17223 (cond
17224 ((eq prefer 'past) (if (= cday n2) n2 n1))
17225 ((eq prefer 'future) (if (= cday n1) n1 n2))
17226 (t (if (= cday n1) n1 n2)))))))
17228 (defun org-date-to-gregorian (date)
17229 "Turn any specification of DATE into a Gregorian date for the calendar."
17230 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17231 ((and (listp date) (= (length date) 3)) date)
17232 ((stringp date)
17233 (setq date (org-parse-time-string date))
17234 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17235 ((listp date)
17236 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17238 (defun org-parse-time-string (s &optional nodefault)
17239 "Parse the standard Org-mode time string.
17240 This should be a lot faster than the normal `parse-time-string'.
17241 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17242 hour and minute fields will be nil if not given."
17243 (cond ((string-match org-ts-regexp0 s)
17244 (list 0
17245 (if (or (match-beginning 8) (not nodefault))
17246 (string-to-number (or (match-string 8 s) "0")))
17247 (if (or (match-beginning 7) (not nodefault))
17248 (string-to-number (or (match-string 7 s) "0")))
17249 (string-to-number (match-string 4 s))
17250 (string-to-number (match-string 3 s))
17251 (string-to-number (match-string 2 s))
17252 nil nil nil))
17253 ((string-match "^<[^>]+>$" s)
17254 (decode-time (seconds-to-time (org-matcher-time s))))
17255 (t (error "Not a standard Org-mode time string: %s" s))))
17257 (defun org-timestamp-up (&optional arg)
17258 "Increase the date item at the cursor by one.
17259 If the cursor is on the year, change the year. If it is on the month,
17260 the day or the time, change that.
17261 With prefix ARG, change by that many units."
17262 (interactive "p")
17263 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17265 (defun org-timestamp-down (&optional arg)
17266 "Decrease the date item at the cursor by one.
17267 If the cursor is on the year, change the year. If it is on the month,
17268 the day or the time, change that.
17269 With prefix ARG, change by that many units."
17270 (interactive "p")
17271 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17273 (defun org-timestamp-up-day (&optional arg)
17274 "Increase the date in the time stamp by one day.
17275 With prefix ARG, change that many days."
17276 (interactive "p")
17277 (if (and (not (org-at-timestamp-p t))
17278 (org-at-heading-p))
17279 (org-todo 'up)
17280 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17282 (defun org-timestamp-down-day (&optional arg)
17283 "Decrease the date in the time stamp by one day.
17284 With prefix ARG, change that many days."
17285 (interactive "p")
17286 (if (and (not (org-at-timestamp-p t))
17287 (org-at-heading-p))
17288 (org-todo 'down)
17289 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17291 (defun org-at-timestamp-p (&optional inactive-ok)
17292 "Determine if the cursor is in or at a timestamp."
17293 (interactive)
17294 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17295 (pos (point))
17296 (ans (or (looking-at tsr)
17297 (save-excursion
17298 (skip-chars-backward "^[<\n\r\t")
17299 (if (> (point) (point-min)) (backward-char 1))
17300 (and (looking-at tsr)
17301 (> (- (match-end 0) pos) -1))))))
17302 (and ans
17303 (boundp 'org-ts-what)
17304 (setq org-ts-what
17305 (cond
17306 ((= pos (match-beginning 0)) 'bracket)
17307 ;; Point is considered to be "on the bracket" whether
17308 ;; it's really on it or right after it.
17309 ((= pos (1- (match-end 0))) 'bracket)
17310 ((= pos (match-end 0)) 'after)
17311 ((org-pos-in-match-range pos 2) 'year)
17312 ((org-pos-in-match-range pos 3) 'month)
17313 ((org-pos-in-match-range pos 7) 'hour)
17314 ((org-pos-in-match-range pos 8) 'minute)
17315 ((or (org-pos-in-match-range pos 4)
17316 (org-pos-in-match-range pos 5)) 'day)
17317 ((and (> pos (or (match-end 8) (match-end 5)))
17318 (< pos (match-end 0)))
17319 (- pos (or (match-end 8) (match-end 5))))
17320 (t 'day))))
17321 ans))
17323 (defun org-toggle-timestamp-type ()
17324 "Toggle the type (<active> or [inactive]) of a time stamp."
17325 (interactive)
17326 (when (org-at-timestamp-p t)
17327 (let ((beg (match-beginning 0)) (end (match-end 0))
17328 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17329 (save-excursion
17330 (goto-char beg)
17331 (while (re-search-forward "[][<>]" end t)
17332 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17333 t t)))
17334 (message "Timestamp is now %sactive"
17335 (if (equal (char-after beg) ?<) "" "in")))))
17337 (defun org-at-clock-log-p nil
17338 "Is the cursor on the clock log line?"
17339 (save-excursion
17340 (move-beginning-of-line 1)
17341 (looking-at "^[ \t]*CLOCK:")))
17343 (defvar org-clock-history) ; defined in org-clock.el
17344 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17345 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17346 "Change the date in the time stamp at point.
17347 The date will be changed by N times WHAT. WHAT can be `day', `month',
17348 `year', `minute', `second'. If WHAT is not given, the cursor position
17349 in the timestamp determines what will be changed.
17350 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17351 (let ((origin (point)) origin-cat
17352 with-hm inactive
17353 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17354 org-ts-what
17355 extra rem
17356 ts time time0 fixnext clrgx)
17357 (if (not (org-at-timestamp-p t))
17358 (user-error "Not at a timestamp"))
17359 (if (and (not what) (eq org-ts-what 'bracket))
17360 (org-toggle-timestamp-type)
17361 ;; Point isn't on brackets. Remember the part of the time-stamp
17362 ;; the point was in. Indeed, size of time-stamps may change,
17363 ;; but point must be kept in the same category nonetheless.
17364 (setq origin-cat org-ts-what)
17365 (if (and (not what) (not (eq org-ts-what 'day))
17366 org-display-custom-times
17367 (get-text-property (point) 'display)
17368 (not (get-text-property (1- (point)) 'display)))
17369 (setq org-ts-what 'day))
17370 (setq org-ts-what (or what org-ts-what)
17371 inactive (= (char-after (match-beginning 0)) ?\[)
17372 ts (match-string 0))
17373 (replace-match "")
17374 (when (string-match
17375 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17377 (setq extra (match-string 1 ts))
17378 (if suppress-tmp-delay
17379 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17380 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17381 (setq with-hm t))
17382 (setq time0 (org-parse-time-string ts))
17383 (when (and updown
17384 (eq org-ts-what 'minute)
17385 (not current-prefix-arg))
17386 ;; This looks like s-up and s-down. Change by one rounding step.
17387 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17388 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17389 (setcar (cdr time0) (+ (nth 1 time0)
17390 (if (> n 0) (- rem) (- dm rem))))))
17391 (setq time
17392 (encode-time (or (car time0) 0)
17393 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17394 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17395 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17396 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17397 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17398 (nthcdr 6 time0)))
17399 (when (and (member org-ts-what '(hour minute))
17400 extra
17401 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17402 (setq extra (org-modify-ts-extra
17403 extra
17404 (if (eq org-ts-what 'hour) 2 5)
17405 n dm)))
17406 (when (integerp org-ts-what)
17407 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17408 (if (eq what 'calendar)
17409 (let ((cal-date (org-get-date-from-calendar)))
17410 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17411 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17412 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17413 (setcar time0 (or (car time0) 0))
17414 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17415 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17416 (setq time (apply 'encode-time time0))))
17417 ;; Insert the new time-stamp, and ensure point stays in the same
17418 ;; category as before (i.e. not after the last position in that
17419 ;; category).
17420 (let ((pos (point)))
17421 ;; Stay before inserted string. `save-excursion' is of no use.
17422 (setq org-last-changed-timestamp
17423 (org-insert-time-stamp time with-hm inactive nil nil extra))
17424 (goto-char pos))
17425 (save-match-data
17426 (looking-at org-ts-regexp3)
17427 (goto-char (cond
17428 ;; `day' category ends before `hour' if any, or at
17429 ;; the end of the day name.
17430 ((eq origin-cat 'day)
17431 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17432 ((eq origin-cat 'hour) (min (match-end 7) origin))
17433 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17434 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17435 ;; `year' and `month' have both fixed size: point
17436 ;; couldn't have moved into another part.
17437 (t origin))))
17438 ;; Update clock if on a CLOCK line.
17439 (org-clock-update-time-maybe)
17440 ;; Maybe adjust the closest clock in `org-clock-history'
17441 (when org-clock-adjust-closest
17442 (if (not (and (org-at-clock-log-p)
17443 (< 1 (length (delq nil (mapcar 'marker-position
17444 org-clock-history))))))
17445 (message "No clock to adjust")
17446 (cond ((save-excursion ; fix previous clock?
17447 (re-search-backward org-ts-regexp0 nil t)
17448 (org-looking-back (concat org-clock-string " \\[")))
17449 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17450 ((save-excursion ; fix next clock?
17451 (re-search-backward org-ts-regexp0 nil t)
17452 (looking-at (concat org-ts-regexp0 "\\] =>")))
17453 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17454 (save-window-excursion
17455 ;; Find closest clock to point, adjust the previous/next one in history
17456 (let* ((p (save-excursion (org-back-to-heading t)))
17457 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17458 (clfixnth
17459 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17460 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17461 (if (not clfixpos)
17462 (message "No clock to adjust")
17463 (save-excursion
17464 (org-goto-marker-or-bmk clfixpos)
17465 (org-show-subtree)
17466 (when (re-search-forward clrgx nil t)
17467 (goto-char (match-beginning 1))
17468 (let (org-clock-adjust-closest)
17469 (org-timestamp-change n org-ts-what updown))
17470 (message "Clock adjusted in %s for heading: %s"
17471 (file-name-nondirectory (buffer-file-name))
17472 (org-get-heading t t)))))))))
17473 ;; Try to recenter the calendar window, if any.
17474 (if (and org-calendar-follow-timestamp-change
17475 (get-buffer-window "*Calendar*" t)
17476 (memq org-ts-what '(day month year)))
17477 (org-recenter-calendar (time-to-days time))))))
17479 (defun org-modify-ts-extra (s pos n dm)
17480 "Change the different parts of the lead-time and repeat fields in timestamp."
17481 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17482 ng h m new rem)
17483 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17484 (cond
17485 ((or (org-pos-in-match-range pos 2)
17486 (org-pos-in-match-range pos 3))
17487 (setq m (string-to-number (match-string 3 s))
17488 h (string-to-number (match-string 2 s)))
17489 (if (org-pos-in-match-range pos 2)
17490 (setq h (+ h n))
17491 (setq n (* dm (org-no-warnings (signum n))))
17492 (when (not (= 0 (setq rem (% m dm))))
17493 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17494 (setq m (+ m n)))
17495 (if (< m 0) (setq m (+ m 60) h (1- h)))
17496 (if (> m 59) (setq m (- m 60) h (1+ h)))
17497 (setq h (min 24 (max 0 h)))
17498 (setq ng 1 new (format "-%02d:%02d" h m)))
17499 ((org-pos-in-match-range pos 6)
17500 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17501 ((org-pos-in-match-range pos 5)
17502 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17504 ((org-pos-in-match-range pos 9)
17505 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17506 ((org-pos-in-match-range pos 8)
17507 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17509 (when ng
17510 (setq s (concat
17511 (substring s 0 (match-beginning ng))
17513 (substring s (match-end ng))))))
17516 (defun org-recenter-calendar (date)
17517 "If the calendar is visible, recenter it to DATE."
17518 (let ((cwin (get-buffer-window "*Calendar*" t)))
17519 (when cwin
17520 (let ((calendar-move-hook nil))
17521 (with-selected-window cwin
17522 (calendar-goto-date (if (listp date) date
17523 (calendar-gregorian-from-absolute date))))))))
17525 (defun org-goto-calendar (&optional arg)
17526 "Go to the Emacs calendar at the current date.
17527 If there is a time stamp in the current line, go to that date.
17528 A prefix ARG can be used to force the current date."
17529 (interactive "P")
17530 (let ((tsr org-ts-regexp) diff
17531 (calendar-move-hook nil)
17532 (calendar-view-holidays-initially-flag nil)
17533 (calendar-view-diary-initially-flag nil))
17534 (if (or (org-at-timestamp-p)
17535 (save-excursion
17536 (beginning-of-line 1)
17537 (looking-at (concat ".*" tsr))))
17538 (let ((d1 (time-to-days (current-time)))
17539 (d2 (time-to-days
17540 (org-time-string-to-time (match-string 1)))))
17541 (setq diff (- d2 d1))))
17542 (calendar)
17543 (calendar-goto-today)
17544 (if (and diff (not arg)) (calendar-forward-day diff))))
17546 (defun org-get-date-from-calendar ()
17547 "Return a list (month day year) of date at point in calendar."
17548 (with-current-buffer "*Calendar*"
17549 (save-match-data
17550 (calendar-cursor-to-date))))
17552 (defun org-date-from-calendar ()
17553 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17554 If there is already a time stamp at the cursor position, update it."
17555 (interactive)
17556 (if (org-at-timestamp-p t)
17557 (org-timestamp-change 0 'calendar)
17558 (let ((cal-date (org-get-date-from-calendar)))
17559 (org-insert-time-stamp
17560 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17562 (defcustom org-effort-durations
17563 `(("h" . 60)
17564 ("d" . ,(* 60 8))
17565 ("w" . ,(* 60 8 5))
17566 ("m" . ,(* 60 8 5 4))
17567 ("y" . ,(* 60 8 5 40)))
17568 "Conversion factor to minutes for an effort modifier.
17570 Each entry has the form (MODIFIER . MINUTES).
17572 In an effort string, a number followed by MODIFIER is multiplied
17573 by the specified number of MINUTES to obtain an effort in
17574 minutes.
17576 For example, if the value of this variable is ((\"hours\" . 60)), then an
17577 effort string \"2hours\" is equivalent to 120 minutes."
17578 :group 'org-agenda
17579 :version "24.1"
17580 :type '(alist :key-type (string :tag "Modifier")
17581 :value-type (number :tag "Minutes")))
17583 (defun org-minutes-to-clocksum-string (m)
17584 "Format number of minutes as a clocksum string.
17585 The format is determined by `org-time-clocksum-format',
17586 `org-time-clocksum-use-fractional' and
17587 `org-time-clocksum-fractional-format' and
17588 `org-time-clocksum-use-effort-durations'."
17589 (let ((clocksum "")
17590 (m (round m)) ; Don't allow fractions of minutes
17591 h d w mo y fmt n)
17592 (setq h (if org-time-clocksum-use-effort-durations
17593 (cdr (assoc "h" org-effort-durations)) 60)
17594 d (if org-time-clocksum-use-effort-durations
17595 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17596 w (if org-time-clocksum-use-effort-durations
17597 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17598 mo (if org-time-clocksum-use-effort-durations
17599 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17600 y (if org-time-clocksum-use-effort-durations
17601 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17602 ;; fractional format
17603 (if org-time-clocksum-use-fractional
17604 (cond
17605 ;; single format string
17606 ((stringp org-time-clocksum-fractional-format)
17607 (format org-time-clocksum-fractional-format (/ m (float h))))
17608 ;; choice of fractional formats for different time units
17609 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17610 (> (/ (truncate m) (* y d h)) 0))
17611 (format fmt (/ m (* y d (float h)))))
17612 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17613 (> (/ (truncate m) (* mo d h)) 0))
17614 (format fmt (/ m (* mo d (float h)))))
17615 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17616 (> (/ (truncate m) (* w d h)) 0))
17617 (format fmt (/ m (* w d (float h)))))
17618 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17619 (> (/ (truncate m) (* d h)) 0))
17620 (format fmt (/ m (* d (float h)))))
17621 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17622 (> (/ (truncate m) h) 0))
17623 (format fmt (/ m (float h))))
17624 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17625 (format fmt m))
17626 ;; fall back to smallest time unit with a format
17627 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17628 (format fmt (/ m (float h))))
17629 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17630 (format fmt (/ m (* d (float h)))))
17631 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17632 (format fmt (/ m (* w d (float h)))))
17633 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17634 (format fmt (/ m (* mo d (float h)))))
17635 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17636 (format fmt (/ m (* y d (float h))))))
17637 ;; standard (non-fractional) format, with single format string
17638 (if (stringp org-time-clocksum-format)
17639 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17640 ;; separate formats components
17641 (and (setq fmt (plist-get org-time-clocksum-format :years))
17642 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17643 (plist-get org-time-clocksum-format :require-years))
17644 (setq clocksum (concat clocksum (format fmt n))
17645 m (- m (* n y d h))))
17646 (and (setq fmt (plist-get org-time-clocksum-format :months))
17647 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17648 (plist-get org-time-clocksum-format :require-months))
17649 (setq clocksum (concat clocksum (format fmt n))
17650 m (- m (* n mo d h))))
17651 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17652 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17653 (plist-get org-time-clocksum-format :require-weeks))
17654 (setq clocksum (concat clocksum (format fmt n))
17655 m (- m (* n w d h))))
17656 (and (setq fmt (plist-get org-time-clocksum-format :days))
17657 (or (> (setq n (/ (truncate m) (* d h))) 0)
17658 (plist-get org-time-clocksum-format :require-days))
17659 (setq clocksum (concat clocksum (format fmt n))
17660 m (- m (* n d h))))
17661 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17662 (or (> (setq n (/ (truncate m) h)) 0)
17663 (plist-get org-time-clocksum-format :require-hours))
17664 (setq clocksum (concat clocksum (format fmt n))
17665 m (- m (* n h))))
17666 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17667 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17668 (setq clocksum (concat clocksum (format fmt m))))
17669 ;; return formatted time duration
17670 clocksum))))
17672 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17673 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17674 "Org mode version 8.0")
17676 (defun org-hours-to-clocksum-string (n)
17677 (org-minutes-to-clocksum-string (* n 60)))
17679 (defun org-hh:mm-string-to-minutes (s)
17680 "Convert a string H:MM to a number of minutes.
17681 If the string is just a number, interpret it as minutes.
17682 In fact, the first hh:mm or number in the string will be taken,
17683 there can be extra stuff in the string.
17684 If no number is found, the return value is 0."
17685 (cond
17686 ((integerp s) s)
17687 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17688 (+ (* (string-to-number (match-string 1 s)) 60)
17689 (string-to-number (match-string 2 s))))
17690 ((string-match "\\([0-9]+\\)" s)
17691 (string-to-number (match-string 1 s)))
17692 (t 0)))
17694 (defcustom org-image-actual-width t
17695 "Should we use the actual width of images when inlining them?
17697 When set to `t', always use the image width.
17699 When set to a number, use imagemagick (when available) to set
17700 the image's width to this value.
17702 When set to a number in a list, try to get the width from any
17703 #+ATTR.* keyword if it matches a width specification like
17705 #+ATTR_HTML: :width 300px
17707 and fall back on that number if none is found.
17709 When set to nil, try to get the width from an #+ATTR.* keyword
17710 and fall back on the original width if none is found.
17712 This requires Emacs >= 24.1, build with imagemagick support."
17713 :group 'org-appearance
17714 :version "24.4"
17715 :package-version '(Org . "8.0")
17716 :type '(choice
17717 (const :tag "Use the image width" t)
17718 (integer :tag "Use a number of pixels")
17719 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17720 (const :tag "Use #+ATTR* or don't resize" nil)))
17722 (defcustom org-agenda-inhibit-startup nil
17723 "Inhibit startup when preparing agenda buffers.
17724 When this variable is `t' (the default), the initialization of
17725 the Org agenda buffers is inhibited: e.g. the visibility state
17726 is not set, the tables are not re-aligned, etc."
17727 :type 'boolean
17728 :version "24.3"
17729 :group 'org-agenda)
17731 (defcustom org-agenda-ignore-drawer-properties nil
17732 "Avoid updating text properties when building the agenda.
17733 Properties are used to prepare buffers for effort estimates, appointments,
17734 and subtree-local categories.
17735 If you don't use these in the agenda, you can add them to this list and
17736 agenda building will be a bit faster.
17737 The value is a list, with zero or more of the symbols `effort', `appt',
17738 or `category'."
17739 :type '(set :greedy t
17740 (const effort)
17741 (const appt)
17742 (const category))
17743 :version "24.3"
17744 :group 'org-agenda)
17746 (defun org-duration-string-to-minutes (s &optional output-to-string)
17747 "Convert a duration string S to minutes.
17749 A bare number is interpreted as minutes, modifiers can be set by
17750 customizing `org-effort-durations' (which see).
17752 Entries containing a colon are interpreted as H:MM by
17753 `org-hh:mm-string-to-minutes'."
17754 (let ((result 0)
17755 (re (concat "\\([0-9.]+\\) *\\("
17756 (regexp-opt (mapcar 'car org-effort-durations))
17757 "\\)")))
17758 (while (string-match re s)
17759 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17760 (string-to-number (match-string 1 s))))
17761 (setq s (replace-match "" nil t s)))
17762 (setq result (floor result))
17763 (incf result (org-hh:mm-string-to-minutes s))
17764 (if output-to-string (number-to-string result) result)))
17766 ;;;; Files
17768 (defun org-save-all-org-buffers ()
17769 "Save all Org-mode buffers without user confirmation."
17770 (interactive)
17771 (message "Saving all Org-mode buffers...")
17772 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17773 (when (featurep 'org-id) (org-id-locations-save))
17774 (message "Saving all Org-mode buffers... done"))
17776 (defun org-revert-all-org-buffers ()
17777 "Revert all Org-mode buffers.
17778 Prompt for confirmation when there are unsaved changes.
17779 Be sure you know what you are doing before letting this function
17780 overwrite your changes.
17782 This function is useful in a setup where one tracks org files
17783 with a version control system, to revert on one machine after pulling
17784 changes from another. I believe the procedure must be like this:
17786 1. M-x org-save-all-org-buffers
17787 2. Pull changes from the other machine, resolve conflicts
17788 3. M-x org-revert-all-org-buffers"
17789 (interactive)
17790 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17791 (user-error "Abort"))
17792 (save-excursion
17793 (save-window-excursion
17794 (mapc
17795 (lambda (b)
17796 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17797 (with-current-buffer b buffer-file-name))
17798 (org-pop-to-buffer-same-window b)
17799 (revert-buffer t 'no-confirm)))
17800 (buffer-list))
17801 (when (and (featurep 'org-id) org-id-track-globally)
17802 (org-id-locations-load)))))
17804 ;;;; Agenda files
17806 ;;;###autoload
17807 (defun org-switchb (&optional arg)
17808 "Switch between Org buffers.
17809 With one prefix argument, restrict available buffers to files.
17810 With two prefix arguments, restrict available buffers to agenda files.
17812 Defaults to `iswitchb' for buffer name completion.
17813 Set `org-completion-use-ido' to make it use ido instead."
17814 (interactive "P")
17815 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17816 ((equal arg '(16)) (org-buffer-list 'agenda))
17817 (t (org-buffer-list))))
17818 (org-completion-use-iswitchb org-completion-use-iswitchb)
17819 (org-completion-use-ido org-completion-use-ido))
17820 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17821 (setq org-completion-use-iswitchb t))
17822 (org-pop-to-buffer-same-window
17823 (org-icompleting-read "Org buffer: "
17824 (mapcar 'list (mapcar 'buffer-name blist))
17825 nil t))))
17827 ;;; Define some older names previously used for this functionality
17828 ;;;###autoload
17829 (defalias 'org-ido-switchb 'org-switchb)
17830 ;;;###autoload
17831 (defalias 'org-iswitchb 'org-switchb)
17833 (defun org-buffer-list (&optional predicate exclude-tmp)
17834 "Return a list of Org buffers.
17835 PREDICATE can be `export', `files' or `agenda'.
17837 export restrict the list to Export buffers.
17838 files restrict the list to buffers visiting Org files.
17839 agenda restrict the list to buffers visiting agenda files.
17841 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17842 (let* ((bfn nil)
17843 (agenda-files (and (eq predicate 'agenda)
17844 (mapcar 'file-truename (org-agenda-files t))))
17845 (filter
17846 (cond
17847 ((eq predicate 'files)
17848 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17849 ((eq predicate 'export)
17850 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17851 ((eq predicate 'agenda)
17852 (lambda (b)
17853 (with-current-buffer b
17854 (and (derived-mode-p 'org-mode)
17855 (setq bfn (buffer-file-name b))
17856 (member (file-truename bfn) agenda-files)))))
17857 (t (lambda (b) (with-current-buffer b
17858 (or (derived-mode-p 'org-mode)
17859 (string-match "\*Org .*Export"
17860 (buffer-name b)))))))))
17861 (delq nil
17862 (mapcar
17863 (lambda(b)
17864 (if (and (funcall filter b)
17865 (or (not exclude-tmp)
17866 (not (string-match "tmp" (buffer-name b)))))
17868 nil))
17869 (buffer-list)))))
17871 (defun org-agenda-files (&optional unrestricted archives)
17872 "Get the list of agenda files.
17873 Optional UNRESTRICTED means return the full list even if a restriction
17874 is currently in place.
17875 When ARCHIVES is t, include all archive files that are really being
17876 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17877 `org-agenda-archives-mode' is t."
17878 (let ((files
17879 (cond
17880 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17881 ((stringp org-agenda-files) (org-read-agenda-file-list))
17882 ((listp org-agenda-files) org-agenda-files)
17883 (t (error "Invalid value of `org-agenda-files'")))))
17884 (setq files (apply 'append
17885 (mapcar (lambda (f)
17886 (if (file-directory-p f)
17887 (directory-files
17888 f t org-agenda-file-regexp)
17889 (list f)))
17890 files)))
17891 (when org-agenda-skip-unavailable-files
17892 (setq files (delq nil
17893 (mapcar (function
17894 (lambda (file)
17895 (and (file-readable-p file) file)))
17896 files))))
17897 (when (or (eq archives t)
17898 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17899 (setq files (org-add-archive-files files)))
17900 files))
17902 (defun org-agenda-file-p (&optional file)
17903 "Return non-nil, if FILE is an agenda file.
17904 If FILE is omitted, use the file associated with the current
17905 buffer."
17906 (member (or file (buffer-file-name))
17907 (org-agenda-files t)))
17909 (defun org-edit-agenda-file-list ()
17910 "Edit the list of agenda files.
17911 Depending on setup, this either uses customize to edit the variable
17912 `org-agenda-files', or it visits the file that is holding the list. In the
17913 latter case, the buffer is set up in a way that saving it automatically kills
17914 the buffer and restores the previous window configuration."
17915 (interactive)
17916 (if (stringp org-agenda-files)
17917 (let ((cw (current-window-configuration)))
17918 (find-file org-agenda-files)
17919 (org-set-local 'org-window-configuration cw)
17920 (org-add-hook 'after-save-hook
17921 (lambda ()
17922 (set-window-configuration
17923 (prog1 org-window-configuration
17924 (kill-buffer (current-buffer))))
17925 (org-install-agenda-files-menu)
17926 (message "New agenda file list installed"))
17927 nil 'local)
17928 (message "%s" (substitute-command-keys
17929 "Edit list and finish with \\[save-buffer]")))
17930 (customize-variable 'org-agenda-files)))
17932 (defun org-store-new-agenda-file-list (list)
17933 "Set new value for the agenda file list and save it correctly."
17934 (if (stringp org-agenda-files)
17935 (let ((fe (org-read-agenda-file-list t)) b u)
17936 (while (setq b (find-buffer-visiting org-agenda-files))
17937 (kill-buffer b))
17938 (with-temp-file org-agenda-files
17939 (insert
17940 (mapconcat
17941 (lambda (f) ;; Keep un-expanded entries.
17942 (if (setq u (assoc f fe))
17943 (cdr u)
17945 list "\n")
17946 "\n")))
17947 (let ((org-mode-hook nil) (org-inhibit-startup t)
17948 (org-insert-mode-line-in-empty-file nil))
17949 (setq org-agenda-files list)
17950 (customize-save-variable 'org-agenda-files org-agenda-files))))
17952 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17953 "Read the list of agenda files from a file.
17954 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17955 filenames, used by `org-store-new-agenda-file-list' to write back
17956 un-expanded file names."
17957 (when (file-directory-p org-agenda-files)
17958 (error "`org-agenda-files' cannot be a single directory"))
17959 (when (stringp org-agenda-files)
17960 (with-temp-buffer
17961 (insert-file-contents org-agenda-files)
17962 (mapcar
17963 (lambda (f)
17964 (let ((e (expand-file-name (substitute-in-file-name f)
17965 org-directory)))
17966 (if pair-with-expansion
17967 (cons e f)
17968 e)))
17969 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17971 ;;;###autoload
17972 (defun org-cycle-agenda-files ()
17973 "Cycle through the files in `org-agenda-files'.
17974 If the current buffer visits an agenda file, find the next one in the list.
17975 If the current buffer does not, find the first agenda file."
17976 (interactive)
17977 (let* ((fs (org-agenda-files t))
17978 (files (append fs (list (car fs))))
17979 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17980 file)
17981 (unless files (user-error "No agenda files"))
17982 (catch 'exit
17983 (while (setq file (pop files))
17984 (if (equal (file-truename file) tcf)
17985 (when (car files)
17986 (find-file (car files))
17987 (throw 'exit t))))
17988 (find-file (car fs)))
17989 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17991 (defun org-agenda-file-to-front (&optional to-end)
17992 "Move/add the current file to the top of the agenda file list.
17993 If the file is not present in the list, it is added to the front. If it is
17994 present, it is moved there. With optional argument TO-END, add/move to the
17995 end of the list."
17996 (interactive "P")
17997 (let ((org-agenda-skip-unavailable-files nil)
17998 (file-alist (mapcar (lambda (x)
17999 (cons (file-truename x) x))
18000 (org-agenda-files t)))
18001 (ctf (file-truename
18002 (or buffer-file-name
18003 (user-error "Please save the current buffer to a file"))))
18004 x had)
18005 (setq x (assoc ctf file-alist) had x)
18007 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18008 (if to-end
18009 (setq file-alist (append (delq x file-alist) (list x)))
18010 (setq file-alist (cons x (delq x file-alist))))
18011 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18012 (org-install-agenda-files-menu)
18013 (message "File %s to %s of agenda file list"
18014 (if had "moved" "added") (if to-end "end" "front"))))
18016 (defun org-remove-file (&optional file)
18017 "Remove current file from the list of files in variable `org-agenda-files'.
18018 These are the files which are being checked for agenda entries.
18019 Optional argument FILE means use this file instead of the current."
18020 (interactive)
18021 (let* ((org-agenda-skip-unavailable-files nil)
18022 (file (or file buffer-file-name
18023 (user-error "Current buffer does not visit a file")))
18024 (true-file (file-truename file))
18025 (afile (abbreviate-file-name file))
18026 (files (delq nil (mapcar
18027 (lambda (x)
18028 (if (equal true-file
18029 (file-truename x))
18030 nil x))
18031 (org-agenda-files t)))))
18032 (if (not (= (length files) (length (org-agenda-files t))))
18033 (progn
18034 (org-store-new-agenda-file-list files)
18035 (org-install-agenda-files-menu)
18036 (message "Removed file: %s" afile))
18037 (message "File was not in list: %s (not removed)" afile))))
18039 (defun org-file-menu-entry (file)
18040 (vector file (list 'find-file file) t))
18042 (defun org-check-agenda-file (file)
18043 "Make sure FILE exists. If not, ask user what to do."
18044 (when (not (file-exists-p file))
18045 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18046 (abbreviate-file-name file))
18047 (let ((r (downcase (read-char-exclusive))))
18048 (cond
18049 ((equal r ?r)
18050 (org-remove-file file)
18051 (throw 'nextfile t))
18052 (t (error "Abort"))))))
18054 (defun org-get-agenda-file-buffer (file)
18055 "Get a buffer visiting FILE. If the buffer needs to be created, add
18056 it to the list of buffers which might be released later."
18057 (let ((buf (org-find-base-buffer-visiting file)))
18058 (if buf
18059 buf ; just return it
18060 ;; Make a new buffer and remember it
18061 (setq buf (find-file-noselect file))
18062 (if buf (push buf org-agenda-new-buffers))
18063 buf)))
18065 (defun org-release-buffers (blist)
18066 "Release all buffers in list, asking the user for confirmation when needed.
18067 When a buffer is unmodified, it is just killed. When modified, it is saved
18068 \(if the user agrees) and then killed."
18069 (let (buf file)
18070 (while (setq buf (pop blist))
18071 (setq file (buffer-file-name buf))
18072 (when (and (buffer-modified-p buf)
18073 file
18074 (y-or-n-p (format "Save file %s? " file)))
18075 (with-current-buffer buf (save-buffer)))
18076 (kill-buffer buf))))
18078 (defun org-agenda-prepare-buffers (files)
18079 "Create buffers for all agenda files, protect archived trees and comments."
18080 (interactive)
18081 (let ((pa '(:org-archived t))
18082 (pc '(:org-comment t))
18083 (pall '(:org-archived t :org-comment t))
18084 (inhibit-read-only t)
18085 (org-inhibit-startup org-agenda-inhibit-startup)
18086 (rea (concat ":" org-archive-tag ":"))
18087 file re pos)
18088 (setq org-tag-alist-for-agenda nil
18089 org-tag-groups-alist-for-agenda nil)
18090 (save-excursion
18091 (save-restriction
18092 (while (setq file (pop files))
18093 (catch 'nextfile
18094 (if (bufferp file)
18095 (set-buffer file)
18096 (org-check-agenda-file file)
18097 (set-buffer (org-get-agenda-file-buffer file)))
18098 (widen)
18099 (org-set-regexps-and-options-for-tags)
18100 (setq pos (point))
18101 (goto-char (point-min))
18102 (let ((case-fold-search t))
18103 (when (search-forward "#+setupfile" nil t)
18104 ;; Don't set all regexps and options systematically as
18105 ;; this is only run for setting agenda tags from setup
18106 ;; file
18107 (org-set-regexps-and-options)))
18108 (or (memq 'category org-agenda-ignore-drawer-properties)
18109 (org-refresh-category-properties))
18110 (or (memq 'effort org-agenda-ignore-drawer-properties)
18111 (org-refresh-properties org-effort-property 'org-effort))
18112 (or (memq 'appt org-agenda-ignore-drawer-properties)
18113 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18114 (setq org-todo-keywords-for-agenda
18115 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18116 (setq org-done-keywords-for-agenda
18117 (append org-done-keywords-for-agenda org-done-keywords))
18118 (setq org-todo-keyword-alist-for-agenda
18119 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18120 (setq org-drawers-for-agenda
18121 (append org-drawers-for-agenda org-drawers))
18122 (setq org-tag-alist-for-agenda
18123 (org-uniquify
18124 (append org-tag-alist-for-agenda
18125 org-tag-alist
18126 org-tag-persistent-alist)))
18127 (if org-group-tags
18128 (setq org-tag-groups-alist-for-agenda
18129 (org-uniquify-alist
18130 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18131 (org-with-silent-modifications
18132 (save-excursion
18133 (remove-text-properties (point-min) (point-max) pall)
18134 (when org-agenda-skip-archived-trees
18135 (goto-char (point-min))
18136 (while (re-search-forward rea nil t)
18137 (if (org-at-heading-p t)
18138 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18139 (goto-char (point-min))
18140 (setq re (format org-heading-keyword-regexp-format
18141 org-comment-string))
18142 (while (re-search-forward re nil t)
18143 (add-text-properties
18144 (match-beginning 0) (org-end-of-subtree t) pc))))
18145 (goto-char pos)))))
18146 (setq org-todo-keywords-for-agenda
18147 (org-uniquify org-todo-keywords-for-agenda))
18148 (setq org-todo-keyword-alist-for-agenda
18149 (org-uniquify org-todo-keyword-alist-for-agenda))))
18152 ;;;; CDLaTeX minor mode
18154 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18155 "Keymap for the minor `org-cdlatex-mode'.")
18157 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18158 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18159 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18160 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18161 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18163 (defvar org-cdlatex-texmathp-advice-is-done nil
18164 "Flag remembering if we have applied the advice to texmathp already.")
18166 (define-minor-mode org-cdlatex-mode
18167 "Toggle the minor `org-cdlatex-mode'.
18168 This mode supports entering LaTeX environment and math in LaTeX fragments
18169 in Org-mode.
18170 \\{org-cdlatex-mode-map}"
18171 nil " OCDL" nil
18172 (when org-cdlatex-mode
18173 (require 'cdlatex)
18174 (run-hooks 'cdlatex-mode-hook)
18175 (cdlatex-compute-tables))
18176 (unless org-cdlatex-texmathp-advice-is-done
18177 (setq org-cdlatex-texmathp-advice-is-done t)
18178 (defadvice texmathp (around org-math-always-on activate)
18179 "Always return t in org-mode buffers.
18180 This is because we want to insert math symbols without dollars even outside
18181 the LaTeX math segments. If Orgmode thinks that point is actually inside
18182 an embedded LaTeX fragment, let texmathp do its job.
18183 \\[org-cdlatex-mode-map]"
18184 (interactive)
18185 (let (p)
18186 (cond
18187 ((not (derived-mode-p 'org-mode)) ad-do-it)
18188 ((eq this-command 'cdlatex-math-symbol)
18189 (setq ad-return-value t
18190 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18192 (let ((p (org-inside-LaTeX-fragment-p)))
18193 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18194 (setq ad-return-value t
18195 texmathp-why '("Org-mode embedded math" . 0))
18196 (if p ad-do-it)))))))))
18198 (defun turn-on-org-cdlatex ()
18199 "Unconditionally turn on `org-cdlatex-mode'."
18200 (org-cdlatex-mode 1))
18202 (defun org-try-cdlatex-tab ()
18203 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18204 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18205 - inside a LaTeX fragment, or
18206 - after the first word in a line, where an abbreviation expansion could
18207 insert a LaTeX environment."
18208 (when org-cdlatex-mode
18209 (cond
18210 ;; Before any word on the line: No expansion possible.
18211 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18212 ;; Just after first word on the line: Expand it. Make sure it
18213 ;; cannot happen on headlines, though.
18214 ((save-excursion
18215 (skip-chars-backward "a-zA-Z0-9*")
18216 (skip-chars-backward " \t")
18217 (and (bolp) (not (org-at-heading-p))))
18218 (cdlatex-tab) t)
18219 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18221 (defun org-cdlatex-underscore-caret (&optional arg)
18222 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18223 Revert to the normal definition outside of these fragments."
18224 (interactive "P")
18225 (if (org-inside-LaTeX-fragment-p)
18226 (call-interactively 'cdlatex-sub-superscript)
18227 (let (org-cdlatex-mode)
18228 (call-interactively (key-binding (vector last-input-event))))))
18230 (defun org-cdlatex-math-modify (&optional arg)
18231 "Execute `cdlatex-math-modify' in LaTeX fragments.
18232 Revert to the normal definition outside of these fragments."
18233 (interactive "P")
18234 (if (org-inside-LaTeX-fragment-p)
18235 (call-interactively 'cdlatex-math-modify)
18236 (let (org-cdlatex-mode)
18237 (call-interactively (key-binding (vector last-input-event))))))
18241 ;;;; LaTeX fragments
18243 (defvar org-latex-regexps
18244 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18245 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18246 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18247 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18248 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18249 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18250 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18251 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18252 "Regular expressions for matching embedded LaTeX.")
18254 (defun org-inside-LaTeX-fragment-p ()
18255 "Test if point is inside a LaTeX fragment.
18256 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18257 sequence appearing also before point.
18258 Even though the matchers for math are configurable, this function assumes
18259 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18260 delimiters are skipped when they have been removed by customization.
18261 The return value is nil, or a cons cell with the delimiter and the
18262 position of this delimiter.
18264 This function does a reasonably good job, but can locally be fooled by
18265 for example currency specifications. For example it will assume being in
18266 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18267 fragments that are properly closed, but during editing, we have to live
18268 with the uncertainty caused by missing closing delimiters. This function
18269 looks only before point, not after."
18270 (catch 'exit
18271 (let ((pos (point))
18272 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18273 (lim (progn
18274 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18275 (point)))
18276 dd-on str (start 0) m re)
18277 (goto-char pos)
18278 (when dodollar
18279 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18280 re (nth 1 (assoc "$" org-latex-regexps)))
18281 (while (string-match re str start)
18282 (cond
18283 ((= (match-end 0) (length str))
18284 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18285 ((= (match-end 0) (- (length str) 5))
18286 (throw 'exit nil))
18287 (t (setq start (match-end 0))))))
18288 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18289 (goto-char pos)
18290 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18291 (and (match-beginning 2) (throw 'exit nil))
18292 ;; count $$
18293 (while (re-search-backward "\\$\\$" lim t)
18294 (setq dd-on (not dd-on)))
18295 (goto-char pos)
18296 (if dd-on (cons "$$" m))))))
18298 (defun org-inside-latex-macro-p ()
18299 "Is point inside a LaTeX macro or its arguments?"
18300 (save-match-data
18301 (org-in-regexp
18302 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18304 (defvar org-latex-fragment-image-overlays nil
18305 "List of overlays carrying the images of latex fragments.")
18306 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18308 (defun org-remove-latex-fragment-image-overlays ()
18309 "Remove all overlays with LaTeX fragment images in current buffer."
18310 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18311 (setq org-latex-fragment-image-overlays nil))
18313 (defun org-preview-latex-fragment (&optional subtree)
18314 "Preview the LaTeX fragment at point, or all locally or globally.
18315 If the cursor is in a LaTeX fragment, create the image and overlay
18316 it over the source code. If there is no fragment at point, display
18317 all fragments in the current text, from one headline to the next. With
18318 prefix SUBTREE, display all fragments in the current subtree. With a
18319 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18320 the cursor is before the first headline,
18321 display all fragments in the buffer.
18322 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18323 (interactive "P")
18324 (unless buffer-file-name
18325 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18326 (when (display-graphic-p)
18327 (org-remove-latex-fragment-image-overlays)
18328 (save-excursion
18329 (save-restriction
18330 (let (beg end at msg)
18331 (cond
18332 ((or (equal subtree '(16))
18333 (not (save-excursion
18334 (re-search-backward org-outline-regexp-bol nil t))))
18335 (setq beg (point-min) end (point-max)
18336 msg "Creating images for buffer...%s"))
18337 ((equal subtree '(4))
18338 (org-back-to-heading)
18339 (setq beg (point) end (org-end-of-subtree t)
18340 msg "Creating images for subtree...%s"))
18342 (if (setq at (org-inside-LaTeX-fragment-p))
18343 (goto-char (max (point-min) (- (cdr at) 2)))
18344 (org-back-to-heading))
18345 (setq beg (point) end (progn (outline-next-heading) (point))
18346 msg (if at "Creating image...%s"
18347 "Creating images for entry...%s"))))
18348 (message msg "")
18349 (narrow-to-region beg end)
18350 (goto-char beg)
18351 (org-format-latex
18352 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18353 (file-name-nondirectory
18354 buffer-file-name)))
18355 default-directory 'overlays msg at 'forbuffer
18356 org-latex-create-formula-image-program)
18357 (message msg "done. Use `C-c C-c' to remove images."))))))
18359 (defun org-format-latex (prefix &optional dir overlays msg at
18360 forbuffer processing-type)
18361 "Replace LaTeX fragments with links to an image, and produce images.
18362 Some of the options can be changed using the variable
18363 `org-format-latex-options'."
18364 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18365 (let* ((prefixnodir (file-name-nondirectory prefix))
18366 (absprefix (expand-file-name prefix dir))
18367 (todir (file-name-directory absprefix))
18368 (opt org-format-latex-options)
18369 (optnew org-format-latex-options)
18370 (matchers (plist-get opt :matchers))
18371 (re-list org-latex-regexps)
18372 (cnt 0) txt hash link beg end re e checkdir
18373 string
18374 m n block-type block linkfile movefile ov)
18375 ;; Check the different regular expressions
18376 (while (setq e (pop re-list))
18377 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18378 block (if block-type "\n\n" ""))
18379 (when (member m matchers)
18380 (goto-char (point-min))
18381 (while (re-search-forward re nil t)
18382 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18383 (or (not overlays)
18384 (not (eq (get-char-property (match-beginning n)
18385 'org-overlay-type)
18386 'org-latex-overlay))))
18387 (cond
18388 ((eq processing-type 'verbatim))
18389 ((eq processing-type 'mathjax)
18390 ;; Prepare for MathJax processing.
18391 (setq string (match-string n))
18392 (when (member m '("$" "$1"))
18393 (save-excursion
18394 (delete-region (match-beginning n) (match-end n))
18395 (goto-char (match-beginning n))
18396 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18397 ((or (eq processing-type 'dvipng)
18398 (eq processing-type 'imagemagick))
18399 ;; Process to an image.
18400 (setq txt (match-string n)
18401 beg (match-beginning n) end (match-end n)
18402 cnt (1+ cnt))
18403 (let ((face (face-at-point))
18404 (fg (plist-get opt :foreground))
18405 (bg (plist-get opt :background))
18406 ;; Ensure full list is printed.
18407 print-length print-level)
18408 (when forbuffer
18409 ;; Get the colors from the face at point.
18410 (goto-char beg)
18411 (when (eq fg 'auto)
18412 (setq fg (face-attribute face :foreground nil 'default)))
18413 (when (eq bg 'auto)
18414 (setq bg (face-attribute face :background nil 'default)))
18415 (setq optnew (copy-sequence opt))
18416 (plist-put optnew :foreground fg)
18417 (plist-put optnew :background bg))
18418 (setq hash (sha1 (prin1-to-string
18419 (list org-format-latex-header
18420 org-latex-default-packages-alist
18421 org-latex-packages-alist
18422 org-format-latex-options
18423 forbuffer txt fg bg)))
18424 linkfile (format "%s_%s.png" prefix hash)
18425 movefile (format "%s_%s.png" absprefix hash)))
18426 (setq link (concat block "[[file:" linkfile "]]" block))
18427 (if msg (message msg cnt))
18428 (goto-char beg)
18429 (unless checkdir ; Ensure the directory exists.
18430 (setq checkdir t)
18431 (or (file-directory-p todir) (make-directory todir t)))
18432 (unless (file-exists-p movefile)
18433 (org-create-formula-image
18434 txt movefile optnew forbuffer processing-type))
18435 (if overlays
18436 (progn
18437 (mapc (lambda (o)
18438 (if (eq (overlay-get o 'org-overlay-type)
18439 'org-latex-overlay)
18440 (delete-overlay o)))
18441 (overlays-in beg end))
18442 (setq ov (make-overlay beg end))
18443 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18444 (if (featurep 'xemacs)
18445 (progn
18446 (overlay-put ov 'invisible t)
18447 (overlay-put
18448 ov 'end-glyph
18449 (make-glyph (vector 'png :file movefile))))
18450 (overlay-put
18451 ov 'display
18452 (list 'image :type 'png :file movefile :ascent 'center)))
18453 (push ov org-latex-fragment-image-overlays)
18454 (goto-char end))
18455 (delete-region beg end)
18456 (insert (org-add-props link
18457 (list 'org-latex-src
18458 (replace-regexp-in-string
18459 "\"" "" txt)
18460 'org-latex-src-embed-type
18461 (if block-type 'paragraph 'character))))))
18462 ((eq processing-type 'mathml)
18463 ;; Process to MathML
18464 (unless (save-match-data (org-format-latex-mathml-available-p))
18465 (user-error "LaTeX to MathML converter not configured"))
18466 (setq txt (match-string n)
18467 beg (match-beginning n) end (match-end n)
18468 cnt (1+ cnt))
18469 (if msg (message msg cnt))
18470 (goto-char beg)
18471 (delete-region beg end)
18472 (insert (org-format-latex-as-mathml
18473 txt block-type prefix dir)))
18475 (error "Unknown conversion type %s for LaTeX fragments"
18476 processing-type)))))))))
18478 (defun org-create-math-formula (latex-frag &optional mathml-file)
18479 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18480 Use `org-latex-to-mathml-convert-command'. If the conversion is
18481 sucessful, return the portion between \"<math...> </math>\"
18482 elements otherwise return nil. When MATHML-FILE is specified,
18483 write the results in to that file. When invoked as an
18484 interactive command, prompt for LATEX-FRAG, with initial value
18485 set to the current active region and echo the results for user
18486 inspection."
18487 (interactive (list (let ((frag (when (org-region-active-p)
18488 (buffer-substring-no-properties
18489 (region-beginning) (region-end)))))
18490 (read-string "LaTeX Fragment: " frag nil frag))))
18491 (unless latex-frag (error "Invalid LaTeX fragment"))
18492 (let* ((tmp-in-file (file-relative-name
18493 (make-temp-name (expand-file-name "ltxmathml-in"))))
18494 (ignore (write-region latex-frag nil tmp-in-file))
18495 (tmp-out-file (file-relative-name
18496 (make-temp-name (expand-file-name "ltxmathml-out"))))
18497 (cmd (format-spec
18498 org-latex-to-mathml-convert-command
18499 `((?j . ,(shell-quote-argument
18500 (expand-file-name org-latex-to-mathml-jar-file)))
18501 (?I . ,(shell-quote-argument tmp-in-file))
18502 (?o . ,(shell-quote-argument tmp-out-file)))))
18503 mathml shell-command-output)
18504 (when (org-called-interactively-p 'any)
18505 (unless (org-format-latex-mathml-available-p)
18506 (user-error "LaTeX to MathML converter not configured")))
18507 (message "Running %s" cmd)
18508 (setq shell-command-output (shell-command-to-string cmd))
18509 (setq mathml
18510 (when (file-readable-p tmp-out-file)
18511 (with-current-buffer (find-file-noselect tmp-out-file t)
18512 (goto-char (point-min))
18513 (when (re-search-forward
18514 (concat
18515 (regexp-quote
18516 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18517 "\\(.\\|\n\\)*"
18518 (regexp-quote "</math>")) nil t)
18519 (prog1 (match-string 0) (kill-buffer))))))
18520 (cond
18521 (mathml
18522 (setq mathml
18523 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18524 (when mathml-file
18525 (write-region mathml nil mathml-file))
18526 (when (org-called-interactively-p 'any)
18527 (message mathml)))
18528 ((message "LaTeX to MathML conversion failed")
18529 (message shell-command-output)))
18530 (delete-file tmp-in-file)
18531 (when (file-exists-p tmp-out-file)
18532 (delete-file tmp-out-file))
18533 mathml))
18535 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18536 prefix &optional dir)
18537 "Use `org-create-math-formula' but check local cache first."
18538 (let* ((absprefix (expand-file-name prefix dir))
18539 (print-length nil) (print-level nil)
18540 (formula-id (concat
18541 "formula-"
18542 (sha1
18543 (prin1-to-string
18544 (list latex-frag
18545 org-latex-to-mathml-convert-command)))))
18546 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18547 (formula-cache-dir (file-name-directory formula-cache)))
18549 (unless (file-directory-p formula-cache-dir)
18550 (make-directory formula-cache-dir t))
18552 (unless (file-exists-p formula-cache)
18553 (org-create-math-formula latex-frag formula-cache))
18555 (if (file-exists-p formula-cache)
18556 ;; Successful conversion. Return the link to MathML file.
18557 (org-add-props
18558 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18559 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18560 'org-latex-src-embed-type (if latex-frag-type
18561 'paragraph 'character)))
18562 ;; Failed conversion. Return the LaTeX fragment verbatim
18563 latex-frag)))
18565 (defun org-create-formula-image (string tofile options buffer &optional type)
18566 "Create an image from LaTeX source using dvipng or convert.
18567 This function calls either `org-create-formula-image-with-dvipng'
18568 or `org-create-formula-image-with-imagemagick' depending on the
18569 value of `org-latex-create-formula-image-program' or on the value
18570 of the optional TYPE variable.
18572 Note: ultimately these two function should be combined as they
18573 share a good deal of logic."
18574 (org-check-external-command
18575 "latex" "needed to convert LaTeX fragments to images")
18576 (funcall
18577 (case (or type org-latex-create-formula-image-program)
18578 ('dvipng
18579 (org-check-external-command
18580 "dvipng" "needed to convert LaTeX fragments to images")
18581 #'org-create-formula-image-with-dvipng)
18582 ('imagemagick
18583 (org-check-external-command
18584 "convert" "you need to install imagemagick")
18585 #'org-create-formula-image-with-imagemagick)
18586 (t (error
18587 "Invalid value of `org-latex-create-formula-image-program'")))
18588 string tofile options buffer))
18590 (declare-function org-export-get-backend "ox" (name))
18591 (declare-function org-export--get-global-options "ox" (&optional backend))
18592 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18593 (declare-function org-latex-guess-inputenc "ox-latex" (header))
18594 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
18595 (defun org-create-formula--latex-header ()
18596 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18597 (let ((info (org-combine-plists (org-export--get-global-options
18598 (org-export-get-backend 'latex))
18599 (org-export--get-inbuffer-options
18600 (org-export-get-backend 'latex)))))
18601 (org-latex-guess-babel-language
18602 (org-latex-guess-inputenc
18603 (org-splice-latex-header
18604 org-format-latex-header
18605 org-latex-default-packages-alist
18606 org-latex-packages-alist t
18607 (plist-get info :latex-header)))
18608 info)))
18610 ;; This function borrows from Ganesh Swami's latex2png.el
18611 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18612 "This calls dvipng."
18613 (require 'ox-latex)
18614 (let* ((tmpdir (if (featurep 'xemacs)
18615 (temp-directory)
18616 temporary-file-directory))
18617 (texfilebase (make-temp-name
18618 (expand-file-name "orgtex" tmpdir)))
18619 (texfile (concat texfilebase ".tex"))
18620 (dvifile (concat texfilebase ".dvi"))
18621 (pngfile (concat texfilebase ".png"))
18622 (fnh (if (featurep 'xemacs)
18623 (font-height (face-font 'default))
18624 (face-attribute 'default :height nil)))
18625 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18626 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18627 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18628 "Black"))
18629 (bg (or (plist-get options (if buffer :background :html-background))
18630 "Transparent")))
18631 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18632 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18633 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18634 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18635 (let ((latex-header (org-create-formula--latex-header)))
18636 (with-temp-file texfile
18637 (insert latex-header)
18638 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18639 (let ((dir default-directory))
18640 (condition-case nil
18641 (progn
18642 (cd tmpdir)
18643 (call-process "latex" nil nil nil texfile))
18644 (error nil))
18645 (cd dir))
18646 (if (not (file-exists-p dvifile))
18647 (progn (message "Failed to create dvi file from %s" texfile) nil)
18648 (condition-case nil
18649 (if (featurep 'xemacs)
18650 (call-process "dvipng" nil nil nil
18651 "-fg" fg "-bg" bg
18652 "-T" "tight"
18653 "-o" pngfile
18654 dvifile)
18655 (call-process "dvipng" nil nil nil
18656 "-fg" fg "-bg" bg
18657 "-D" dpi
18658 ;;"-x" scale "-y" scale
18659 "-T" "tight"
18660 "-o" pngfile
18661 dvifile))
18662 (error nil))
18663 (if (not (file-exists-p pngfile))
18664 (if org-format-latex-signal-error
18665 (error "Failed to create png file from %s" texfile)
18666 (message "Failed to create png file from %s" texfile)
18667 nil)
18668 ;; Use the requested file name and clean up
18669 (copy-file pngfile tofile 'replace)
18670 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18671 (if (file-exists-p (concat texfilebase e))
18672 (delete-file (concat texfilebase e))))
18673 pngfile))))
18675 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18676 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18677 "This calls convert, which is included into imagemagick."
18678 (require 'ox-latex)
18679 (let* ((tmpdir (if (featurep 'xemacs)
18680 (temp-directory)
18681 temporary-file-directory))
18682 (texfilebase (make-temp-name
18683 (expand-file-name "orgtex" tmpdir)))
18684 (texfile (concat texfilebase ".tex"))
18685 (pdffile (concat texfilebase ".pdf"))
18686 (pngfile (concat texfilebase ".png"))
18687 (fnh (if (featurep 'xemacs)
18688 (font-height (face-font 'default))
18689 (face-attribute 'default :height nil)))
18690 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18691 (dpi (number-to-string (* scale (floor (if buffer fnh 120.)))))
18692 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18693 "black"))
18694 (bg (or (plist-get options (if buffer :background :html-background))
18695 "white")))
18696 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18697 (setq fg (org-latex-color-format fg)))
18698 (if (eq bg 'default) (setq bg (org-latex-color :background))
18699 (setq bg (org-latex-color-format
18700 (if (string= bg "Transparent") "white" bg))))
18701 (let ((latex-header (org-create-formula--latex-header)))
18702 (with-temp-file texfile
18703 (insert latex-header)
18704 (insert "\n\\begin{document}\n"
18705 "\\definecolor{fg}{rgb}{" fg "}\n"
18706 "\\definecolor{bg}{rgb}{" bg "}\n"
18707 "\n\\pagecolor{bg}\n"
18708 "\n{\\color{fg}\n"
18709 string
18710 "\n}\n"
18711 "\n\\end{document}\n")))
18712 (org-latex-compile texfile t)
18713 (if (not (file-exists-p pdffile))
18714 (progn (message "Failed to create pdf file from %s" texfile) nil)
18715 (condition-case nil
18716 (if (featurep 'xemacs)
18717 (call-process "convert" nil nil nil
18718 "-density" "96"
18719 "-trim"
18720 "-antialias"
18721 pdffile
18722 "-quality" "100"
18723 ;; "-sharpen" "0x1.0"
18724 pngfile)
18725 (call-process "convert" nil nil nil
18726 "-density" dpi
18727 "-trim"
18728 "-antialias"
18729 pdffile
18730 "-quality" "100"
18731 ;; "-sharpen" "0x1.0"
18732 pngfile))
18733 (error nil))
18734 (if (not (file-exists-p pngfile))
18735 (if org-format-latex-signal-error
18736 (error "Failed to create png file from %s" texfile)
18737 (message "Failed to create png file from %s" texfile)
18738 nil)
18739 ;; Use the requested file name and clean up
18740 (copy-file pngfile tofile 'replace)
18741 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18742 (if (file-exists-p (concat texfilebase e))
18743 (delete-file (concat texfilebase e))))
18744 pngfile))))
18746 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18747 "Fill a LaTeX header template TPL.
18748 In the template, the following place holders will be recognized:
18750 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18751 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18752 [PACKAGES] \\usepackage statements for PKG
18753 [NO-PACKAGES] do not include PKG
18754 [EXTRA] the string EXTRA
18755 [NO-EXTRA] do not include EXTRA
18757 For backward compatibility, if both the positive and the negative place
18758 holder is missing, the positive one (without the \"NO-\") will be
18759 assumed to be present at the end of the template.
18760 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18761 EXTRA is a string.
18762 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18763 (let (rpl (end ""))
18764 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18765 (setq rpl (if (or (match-end 1) (not def-pkg))
18766 "" (org-latex-packages-to-string def-pkg snippets-p t))
18767 tpl (replace-match rpl t t tpl))
18768 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18770 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18771 (setq rpl (if (or (match-end 1) (not pkg))
18772 "" (org-latex-packages-to-string pkg snippets-p t))
18773 tpl (replace-match rpl t t tpl))
18774 (if pkg (setq end
18775 (concat end "\n"
18776 (org-latex-packages-to-string pkg snippets-p)))))
18778 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18779 (setq rpl (if (or (match-end 1) (not extra))
18780 "" (concat extra "\n"))
18781 tpl (replace-match rpl t t tpl))
18782 (if (and extra (string-match "\\S-" extra))
18783 (setq end (concat end "\n" extra))))
18785 (if (string-match "\\S-" end)
18786 (concat tpl "\n" end)
18787 tpl)))
18789 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18790 "Turn an alist of packages into a string with the \\usepackage macros."
18791 (setq pkg (mapconcat (lambda(p)
18792 (cond
18793 ((stringp p) p)
18794 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18795 (format "%% Package %s omitted" (cadr p)))
18796 ((equal "" (car p))
18797 (format "\\usepackage{%s}" (cadr p)))
18799 (format "\\usepackage[%s]{%s}"
18800 (car p) (cadr p)))))
18802 "\n"))
18803 (if newline (concat pkg "\n") pkg))
18805 (defun org-dvipng-color (attr)
18806 "Return a RGB color specification for dvipng."
18807 (apply 'format "rgb %s %s %s"
18808 (mapcar 'org-normalize-color
18809 (if (featurep 'xemacs)
18810 (color-rgb-components
18811 (face-property 'default
18812 (cond ((eq attr :foreground) 'foreground)
18813 ((eq attr :background) 'background))))
18814 (color-values (face-attribute 'default attr nil))))))
18816 (defun org-dvipng-color-format (color-name)
18817 "Convert COLOR-NAME to a RGB color value for dvipng."
18818 (apply 'format "rgb %s %s %s"
18819 (mapcar 'org-normalize-color
18820 (color-values color-name))))
18822 (defun org-latex-color (attr)
18823 "Return a RGB color for the LaTeX color package."
18824 (apply 'format "%s,%s,%s"
18825 (mapcar 'org-normalize-color
18826 (if (featurep 'xemacs)
18827 (color-rgb-components
18828 (face-property 'default
18829 (cond ((eq attr :foreground) 'foreground)
18830 ((eq attr :background) 'background))))
18831 (color-values (face-attribute 'default attr nil))))))
18833 (defun org-latex-color-format (color-name)
18834 "Convert COLOR-NAME to a RGB color value."
18835 (apply 'format "%s,%s,%s"
18836 (mapcar 'org-normalize-color
18837 (color-values color-name))))
18839 (defun org-normalize-color (value)
18840 "Return string to be used as color value for an RGB component."
18841 (format "%g" (/ value 65535.0)))
18845 ;; Image display
18847 (defvar org-inline-image-overlays nil)
18848 (make-variable-buffer-local 'org-inline-image-overlays)
18850 (defun org-toggle-inline-images (&optional include-linked)
18851 "Toggle the display of inline images.
18852 INCLUDE-LINKED is passed to `org-display-inline-images'."
18853 (interactive "P")
18854 (if org-inline-image-overlays
18855 (progn
18856 (org-remove-inline-images)
18857 (message "Inline image display turned off"))
18858 (org-display-inline-images include-linked)
18859 (if (and (org-called-interactively-p)
18860 org-inline-image-overlays)
18861 (message "%d images displayed inline"
18862 (length org-inline-image-overlays))
18863 (message "No images to display inline"))))
18865 (defun org-redisplay-inline-images ()
18866 "Refresh the display of inline images."
18867 (interactive)
18868 (if (not org-inline-image-overlays)
18869 (org-toggle-inline-images)
18870 (org-toggle-inline-images)
18871 (org-toggle-inline-images)))
18873 (defun org-display-inline-images (&optional include-linked refresh beg end)
18874 "Display inline images.
18875 Normally only links without a description part are inlined, because this
18876 is how it will work for export. When INCLUDE-LINKED is set, also links
18877 with a description part will be inlined. This can be nice for a quick
18878 look at those images, but it does not reflect what exported files will look
18879 like.
18880 When REFRESH is set, refresh existing images between BEG and END.
18881 This will create new image displays only if necessary.
18882 BEG and END default to the buffer boundaries."
18883 (interactive "P")
18884 (when (display-graphic-p)
18885 (unless refresh
18886 (org-remove-inline-images)
18887 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18888 (save-excursion
18889 (save-restriction
18890 (widen)
18891 (setq beg (or beg (point-min)) end (or end (point-max)))
18892 (goto-char beg)
18893 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18894 (substring (org-image-file-name-regexp) 0 -2)
18895 "\\)\\]" (if include-linked "" "\\]")))
18896 (case-fold-search t)
18897 old file ov img type attrwidth width)
18898 (while (re-search-forward re end t)
18899 (setq old (get-char-property-and-overlay (match-beginning 1)
18900 'org-image-overlay)
18901 file (expand-file-name
18902 (concat (or (match-string 3) "") (match-string 4))))
18903 (when (image-type-available-p 'imagemagick)
18904 (setq attrwidth (if (or (listp org-image-actual-width)
18905 (null org-image-actual-width))
18906 (save-excursion
18907 (save-match-data
18908 (when (re-search-backward
18909 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18910 (save-excursion
18911 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18912 (string-to-number (match-string 1))))))
18913 width (cond ((eq org-image-actual-width t) nil)
18914 ((null org-image-actual-width) attrwidth)
18915 ((numberp org-image-actual-width)
18916 org-image-actual-width)
18917 ((listp org-image-actual-width)
18918 (or attrwidth (car org-image-actual-width))))
18919 type (if width 'imagemagick)))
18920 (when (file-exists-p file)
18921 (if (and (car-safe old) refresh)
18922 (image-refresh (overlay-get (cdr old) 'display))
18923 (setq img (save-match-data (create-image file type nil :width width)))
18924 (when img
18925 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18926 (overlay-put ov 'display img)
18927 (overlay-put ov 'face 'default)
18928 (overlay-put ov 'org-image-overlay t)
18929 (overlay-put ov 'modification-hooks
18930 (list 'org-display-inline-remove-overlay))
18931 (push ov org-inline-image-overlays))))))))))
18933 (define-obsolete-function-alias
18934 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18936 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18937 "Remove inline-display overlay if a corresponding region is modified."
18938 (let ((inhibit-modification-hooks t))
18939 (when (and ov after)
18940 (delete ov org-inline-image-overlays)
18941 (delete-overlay ov))))
18943 (defun org-remove-inline-images ()
18944 "Remove inline display of images."
18945 (interactive)
18946 (mapc 'delete-overlay org-inline-image-overlays)
18947 (setq org-inline-image-overlays nil))
18949 ;;;; Key bindings
18951 ;; Outline functions from `outline-mode-prefix-map'
18952 ;; that can be remapped in Org:
18953 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18954 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18955 (define-key org-mode-map [remap outline-forward-same-level]
18956 'org-forward-heading-same-level)
18957 (define-key org-mode-map [remap outline-backward-same-level]
18958 'org-backward-heading-same-level)
18959 (define-key org-mode-map [remap show-branches]
18960 'org-kill-note-or-show-branches)
18961 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18962 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18963 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18965 ;; Outline functions from `outline-mode-prefix-map' that can not
18966 ;; be remapped in Org:
18968 ;; - the column "key binding" shows whether the Outline function is still
18969 ;; available in Org mode on the same key that it has been bound to in
18970 ;; Outline mode:
18971 ;; - "overridden": key used for a different functionality in Org mode
18972 ;; - else: key still bound to the same Outline function in Org mode
18974 ;; | Outline function | key binding | Org replacement |
18975 ;; |------------------------------------+-------------+-----------------------|
18976 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18977 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18978 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18979 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18980 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18981 ;; | `show-entry' | overridden | no replacement |
18982 ;; | `show-children' | `C-c C-i' | visibility cycling |
18983 ;; | `show-branches' | `C-c C-k' | still same function |
18984 ;; | `show-subtree' | overridden | visibility cycling |
18985 ;; | `show-all' | overridden | no replacement |
18986 ;; | `hide-subtree' | overridden | visibility cycling |
18987 ;; | `hide-body' | overridden | no replacement |
18988 ;; | `hide-entry' | overridden | visibility cycling |
18989 ;; | `hide-leaves' | overridden | no replacement |
18990 ;; | `hide-sublevels' | overridden | no replacement |
18991 ;; | `hide-other' | overridden | no replacement |
18993 ;; Make `C-c C-x' a prefix key
18994 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18996 ;; TAB key with modifiers
18997 (org-defkey org-mode-map "\C-i" 'org-cycle)
18998 (org-defkey org-mode-map [(tab)] 'org-cycle)
18999 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19000 (org-defkey org-mode-map "\M-\t" 'pcomplete)
19001 ;; The following line is necessary under Suse GNU/Linux
19002 (unless (featurep 'xemacs)
19003 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19004 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19005 (define-key org-mode-map [backtab] 'org-shifttab)
19007 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19008 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19009 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19011 ;; Cursor keys with modifiers
19012 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19013 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19014 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19015 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19017 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19018 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19019 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19020 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19022 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19023 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19024 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19025 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19027 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19028 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19029 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19030 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19032 ;; Babel keys
19033 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19034 (mapc (lambda (pair)
19035 (define-key org-babel-map (car pair) (cdr pair)))
19036 org-babel-key-bindings)
19038 ;;; Extra keys for tty access.
19039 ;; We only set them when really needed because otherwise the
19040 ;; menus don't show the simple keys
19042 (when (or org-use-extra-keys
19043 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19044 (not window-system))
19045 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19046 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19047 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19048 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19049 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19050 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19051 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19052 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19053 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19054 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19055 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19056 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19057 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19058 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19059 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19060 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19061 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19062 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19063 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19064 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19065 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19066 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19067 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
19068 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19069 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19070 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19071 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19072 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19074 ;; All the other keys
19076 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
19077 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19078 (if (boundp 'narrow-map)
19079 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19080 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19081 (if (boundp 'narrow-map)
19082 (org-defkey narrow-map "b" 'org-narrow-to-block)
19083 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19084 (if (boundp 'narrow-map)
19085 (org-defkey narrow-map "e" 'org-narrow-to-element)
19086 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19087 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19088 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19089 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19090 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19091 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19092 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19093 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19094 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19095 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19096 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19097 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
19098 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19099 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19100 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19101 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19102 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19103 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19104 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19105 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19106 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19107 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19108 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19109 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19110 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19111 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19112 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19113 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19114 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19115 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19116 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19117 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19118 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19119 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19120 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19121 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19122 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19123 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19124 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19125 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19126 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19127 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19128 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19129 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19130 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19131 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19132 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19133 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19134 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19135 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19136 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19137 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19138 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19139 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19140 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19141 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19142 (org-defkey org-mode-map "\C-c^" 'org-sort)
19143 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19144 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19145 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19146 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19147 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19148 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19149 (org-defkey org-mode-map "\C-m" 'org-return)
19150 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19151 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19152 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19153 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19154 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19155 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19156 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19157 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19158 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19159 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19160 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19161 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19162 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19163 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19164 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19165 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19166 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19167 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19168 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19169 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19170 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19171 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19172 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19174 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19175 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19176 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19178 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19179 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19180 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19181 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19182 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19183 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19184 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19185 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19186 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19187 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19188 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19189 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19190 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19191 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19192 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19193 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19194 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19195 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19196 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19197 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19198 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19199 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19200 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19202 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19203 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19204 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19205 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19206 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19208 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19210 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19212 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19213 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19215 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19218 (when (featurep 'xemacs)
19219 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19222 (defconst org-speed-commands-default
19224 ("Outline Navigation")
19225 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19226 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19227 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19228 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19229 ("F" . org-next-block)
19230 ("B" . org-previous-block)
19231 ("u" . (org-speed-move-safe 'outline-up-heading))
19232 ("j" . org-goto)
19233 ("g" . (org-refile t))
19234 ("Outline Visibility")
19235 ("c" . org-cycle)
19236 ("C" . org-shifttab)
19237 (" " . org-display-outline-path)
19238 ("s" . org-narrow-to-subtree)
19239 ("=" . org-columns)
19240 ("Outline Structure Editing")
19241 ("U" . org-shiftmetaup)
19242 ("D" . org-shiftmetadown)
19243 ("r" . org-metaright)
19244 ("l" . org-metaleft)
19245 ("R" . org-shiftmetaright)
19246 ("L" . org-shiftmetaleft)
19247 ("i" . (progn (forward-char 1) (call-interactively
19248 'org-insert-heading-respect-content)))
19249 ("^" . org-sort)
19250 ("w" . org-refile)
19251 ("a" . org-archive-subtree-default-with-confirmation)
19252 ("@" . org-mark-subtree)
19253 ("#" . org-toggle-comment)
19254 ("Clock Commands")
19255 ("I" . org-clock-in)
19256 ("O" . org-clock-out)
19257 ("Meta Data Editing")
19258 ("t" . org-todo)
19259 ("," . (org-priority))
19260 ("0" . (org-priority ?\ ))
19261 ("1" . (org-priority ?A))
19262 ("2" . (org-priority ?B))
19263 ("3" . (org-priority ?C))
19264 (":" . org-set-tags-command)
19265 ("e" . org-set-effort)
19266 ("E" . org-inc-effort)
19267 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19268 (org-entry-put (point) "APPT_WARNTIME" m)))
19269 ("Agenda Views etc")
19270 ("v" . org-agenda)
19271 ("/" . org-sparse-tree)
19272 ("Misc")
19273 ("o" . org-open-at-point)
19274 ("?" . org-speed-command-help)
19275 ("<" . (org-agenda-set-restriction-lock 'subtree))
19276 (">" . (org-agenda-remove-restriction-lock))
19278 "The default speed commands.")
19280 (defun org-print-speed-command (e)
19281 (if (> (length (car e)) 1)
19282 (progn
19283 (princ "\n")
19284 (princ (car e))
19285 (princ "\n")
19286 (princ (make-string (length (car e)) ?-))
19287 (princ "\n"))
19288 (princ (car e))
19289 (princ " ")
19290 (if (symbolp (cdr e))
19291 (princ (symbol-name (cdr e)))
19292 (prin1 (cdr e)))
19293 (princ "\n")))
19295 (defun org-speed-command-help ()
19296 "Show the available speed commands."
19297 (interactive)
19298 (if (not org-use-speed-commands)
19299 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19300 (with-output-to-temp-buffer "*Help*"
19301 (princ "User-defined Speed commands\n===========================\n")
19302 (mapc 'org-print-speed-command org-speed-commands-user)
19303 (princ "\n")
19304 (princ "Built-in Speed commands\n=======================\n")
19305 (mapc 'org-print-speed-command org-speed-commands-default))
19306 (with-current-buffer "*Help*"
19307 (setq truncate-lines t))))
19309 (defun org-speed-move-safe (cmd)
19310 "Execute CMD, but make sure that the cursor always ends up in a headline.
19311 If not, return to the original position and throw an error."
19312 (interactive)
19313 (let ((pos (point)))
19314 (call-interactively cmd)
19315 (unless (and (bolp) (org-at-heading-p))
19316 (goto-char pos)
19317 (error "Boundary reached while executing %s" cmd))))
19319 (defvar org-self-insert-command-undo-counter 0)
19321 (defvar org-table-auto-blank-field) ; defined in org-table.el
19322 (defvar org-speed-command nil)
19324 (define-obsolete-function-alias
19325 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19327 (defun org-speed-command-activate (keys)
19328 "Hook for activating single-letter speed commands.
19329 `org-speed-commands-default' specifies a minimal command set.
19330 Use `org-speed-commands-user' for further customization."
19331 (when (or (and (bolp) (looking-at org-outline-regexp))
19332 (and (functionp org-use-speed-commands)
19333 (funcall org-use-speed-commands)))
19334 (cdr (assoc keys (append org-speed-commands-user
19335 org-speed-commands-default)))))
19337 (define-obsolete-function-alias
19338 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19340 (defun org-babel-speed-command-activate (keys)
19341 "Hook for activating single-letter code block commands."
19342 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19343 (cdr (assoc keys org-babel-key-bindings))))
19345 (defcustom org-speed-command-hook
19346 '(org-speed-command-default-hook org-babel-speed-command-hook)
19347 "Hook for activating speed commands at strategic locations.
19348 Hook functions are called in sequence until a valid handler is
19349 found.
19351 Each hook takes a single argument, a user-pressed command key
19352 which is also a `self-insert-command' from the global map.
19354 Within the hook, examine the cursor position and the command key
19355 and return nil or a valid handler as appropriate. Handler could
19356 be one of an interactive command, a function, or a form.
19358 Set `org-use-speed-commands' to non-nil value to enable this
19359 hook. The default setting is `org-speed-command-activate'."
19360 :group 'org-structure
19361 :version "24.1"
19362 :type 'hook)
19364 (defun org-self-insert-command (N)
19365 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19366 If the cursor is in a table looking at whitespace, the whitespace is
19367 overwritten, and the table is not marked as requiring realignment."
19368 (interactive "p")
19369 (org-check-before-invisible-edit 'insert)
19370 (cond
19371 ((and org-use-speed-commands
19372 (setq org-speed-command
19373 (run-hook-with-args-until-success
19374 'org-speed-command-hook (this-command-keys))))
19375 (cond
19376 ((commandp org-speed-command)
19377 (setq this-command org-speed-command)
19378 (call-interactively org-speed-command))
19379 ((functionp org-speed-command)
19380 (funcall org-speed-command))
19381 ((and org-speed-command (listp org-speed-command))
19382 (eval org-speed-command))
19383 (t (let (org-use-speed-commands)
19384 (call-interactively 'org-self-insert-command)))))
19385 ((and
19386 (org-table-p)
19387 (progn
19388 ;; check if we blank the field, and if that triggers align
19389 (and (featurep 'org-table) org-table-auto-blank-field
19390 (member last-command
19391 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19392 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19393 ;; got extra space, this field does not determine column width
19394 (let (org-table-may-need-update) (org-table-blank-field))
19395 ;; no extra space, this field may determine column width
19396 (org-table-blank-field)))
19398 (eq N 1)
19399 (looking-at "[^|\n]* |"))
19400 (let (org-table-may-need-update)
19401 (goto-char (1- (match-end 0)))
19402 (backward-delete-char 1)
19403 (goto-char (match-beginning 0))
19404 (self-insert-command N)))
19406 (setq org-table-may-need-update t)
19407 (self-insert-command N)
19408 (org-fix-tags-on-the-fly)
19409 (if org-self-insert-cluster-for-undo
19410 (if (not (eq last-command 'org-self-insert-command))
19411 (setq org-self-insert-command-undo-counter 1)
19412 (if (>= org-self-insert-command-undo-counter 20)
19413 (setq org-self-insert-command-undo-counter 1)
19414 (and (> org-self-insert-command-undo-counter 0)
19415 buffer-undo-list (listp buffer-undo-list)
19416 (not (cadr buffer-undo-list)) ; remove nil entry
19417 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19418 (setq org-self-insert-command-undo-counter
19419 (1+ org-self-insert-command-undo-counter))))))))
19421 (defun org-check-before-invisible-edit (kind)
19422 "Check is editing if kind KIND would be dangerous with invisible text around.
19423 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19424 ;; First, try to get out of here as quickly as possible, to reduce overhead
19425 (if (and org-catch-invisible-edits
19426 (or (not (boundp 'visible-mode)) (not visible-mode))
19427 (or (get-char-property (point) 'invisible)
19428 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19429 ;; OK, we need to take a closer look
19430 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19431 (invisible-before-point (if (bobp) nil (get-char-property
19432 (1- (point)) 'invisible)))
19433 (border-and-ok-direction
19435 ;; Check if we are acting predictably before invisible text
19436 (and invisible-at-point (not invisible-before-point)
19437 (memq kind '(insert delete-backward)))
19438 ;; Check if we are acting predictably after invisible text
19439 ;; This works not well, and I have turned it off. It seems
19440 ;; better to always show and stop after invisible text.
19441 ;; (and (not invisible-at-point) invisible-before-point
19442 ;; (memq kind '(insert delete)))
19444 (when (or (memq invisible-at-point '(outline org-hide-block t))
19445 (memq invisible-before-point '(outline org-hide-block t)))
19446 (if (eq org-catch-invisible-edits 'error)
19447 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19448 (if (and org-custom-properties-overlays
19449 (y-or-n-p "Display invisible properties in this buffer? "))
19450 (org-toggle-custom-properties-visibility)
19451 ;; Make the area visible
19452 (save-excursion
19453 (if invisible-before-point
19454 (goto-char (previous-single-char-property-change
19455 (point) 'invisible)))
19456 (org-cycle))
19457 (cond
19458 ((eq org-catch-invisible-edits 'show)
19459 ;; That's it, we do the edit after showing
19460 (message
19461 "Unfolding invisible region around point before editing")
19462 (sit-for 1))
19463 ((and (eq org-catch-invisible-edits 'smart)
19464 border-and-ok-direction)
19465 (message "Unfolding invisible region around point before editing"))
19467 ;; Don't do the edit, make the user repeat it in full visibility
19468 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19470 (defun org-fix-tags-on-the-fly ()
19471 (when (and (equal (char-after (point-at-bol)) ?*)
19472 (org-at-heading-p))
19473 (org-align-tags-here org-tags-column)))
19475 (defun org-delete-backward-char (N)
19476 "Like `delete-backward-char', insert whitespace at field end in tables.
19477 When deleting backwards, in tables this function will insert whitespace in
19478 front of the next \"|\" separator, to keep the table aligned. The table will
19479 still be marked for re-alignment if the field did fill the entire column,
19480 because, in this case the deletion might narrow the column."
19481 (interactive "p")
19482 (save-match-data
19483 (org-check-before-invisible-edit 'delete-backward)
19484 (if (and (org-table-p)
19485 (eq N 1)
19486 (string-match "|" (buffer-substring (point-at-bol) (point)))
19487 (looking-at ".*?|"))
19488 (let ((pos (point))
19489 (noalign (looking-at "[^|\n\r]* |"))
19490 (c org-table-may-need-update))
19491 (backward-delete-char N)
19492 (if (not overwrite-mode)
19493 (progn
19494 (skip-chars-forward "^|")
19495 (insert " ")
19496 (goto-char (1- pos))))
19497 ;; noalign: if there were two spaces at the end, this field
19498 ;; does not determine the width of the column.
19499 (if noalign (setq org-table-may-need-update c)))
19500 (backward-delete-char N)
19501 (org-fix-tags-on-the-fly))))
19503 (defun org-delete-char (N)
19504 "Like `delete-char', but insert whitespace at field end in tables.
19505 When deleting characters, in tables this function will insert whitespace in
19506 front of the next \"|\" separator, to keep the table aligned. The table will
19507 still be marked for re-alignment if the field did fill the entire column,
19508 because, in this case the deletion might narrow the column."
19509 (interactive "p")
19510 (save-match-data
19511 (org-check-before-invisible-edit 'delete)
19512 (if (and (org-table-p)
19513 (not (bolp))
19514 (not (= (char-after) ?|))
19515 (eq N 1))
19516 (if (looking-at ".*?|")
19517 (let ((pos (point))
19518 (noalign (looking-at "[^|\n\r]* |"))
19519 (c org-table-may-need-update))
19520 (replace-match
19521 (concat (substring (match-string 0) 1 -1) " |") nil t)
19522 (goto-char pos)
19523 ;; noalign: if there were two spaces at the end, this field
19524 ;; does not determine the width of the column.
19525 (if noalign (setq org-table-may-need-update c)))
19526 (delete-char N))
19527 (delete-char N)
19528 (org-fix-tags-on-the-fly))))
19530 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19531 (put 'org-self-insert-command 'delete-selection
19532 (lambda ()
19533 (not (run-hook-with-args-until-success
19534 'self-insert-uses-region-functions))))
19535 (put 'orgtbl-self-insert-command 'delete-selection
19536 (lambda ()
19537 (not (run-hook-with-args-until-success
19538 'self-insert-uses-region-functions))))
19539 (put 'org-delete-char 'delete-selection 'supersede)
19540 (put 'org-delete-backward-char 'delete-selection 'supersede)
19541 (put 'org-yank 'delete-selection 'yank)
19543 ;; Make `flyspell-mode' delay after some commands
19544 (put 'org-self-insert-command 'flyspell-delayed t)
19545 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19546 (put 'org-delete-char 'flyspell-delayed t)
19547 (put 'org-delete-backward-char 'flyspell-delayed t)
19549 ;; Make pabbrev-mode expand after org-mode commands
19550 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19551 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19553 (defun org-remap (map &rest commands)
19554 "In MAP, remap the functions given in COMMANDS.
19555 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19556 (let (new old)
19557 (while commands
19558 (setq old (pop commands) new (pop commands))
19559 (if (fboundp 'command-remapping)
19560 (org-defkey map (vector 'remap old) new)
19561 (substitute-key-definition old new map global-map)))))
19563 (defun org-transpose-words ()
19564 "Transpose words for Org.
19565 This uses the `org-mode-transpose-word-syntax-table' syntax
19566 table, which interprets characters in `org-emphasis-alist' as
19567 word constituents."
19568 (interactive)
19569 (with-syntax-table org-mode-transpose-word-syntax-table
19570 (call-interactively 'transpose-words)))
19571 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19573 (when (eq org-enable-table-editor 'optimized)
19574 ;; If the user wants maximum table support, we need to hijack
19575 ;; some standard editing functions
19576 (org-remap org-mode-map
19577 'self-insert-command 'org-self-insert-command
19578 'delete-char 'org-delete-char
19579 'delete-backward-char 'org-delete-backward-char)
19580 (org-defkey org-mode-map "|" 'org-force-self-insert))
19582 (defvar org-ctrl-c-ctrl-c-hook nil
19583 "Hook for functions attaching themselves to `C-c C-c'.
19585 This can be used to add additional functionality to the C-c C-c
19586 key which executes context-dependent commands. This hook is run
19587 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19588 run after the last test.
19590 Each function will be called with no arguments. The function
19591 must check if the context is appropriate for it to act. If yes,
19592 it should do its thing and then return a non-nil value. If the
19593 context is wrong, just do nothing and return nil.")
19595 (defvar org-ctrl-c-ctrl-c-final-hook nil
19596 "Hook for functions attaching themselves to `C-c C-c'.
19598 This can be used to add additional functionality to the C-c C-c
19599 key which executes context-dependent commands. This hook is run
19600 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19601 before the first test.
19603 Each function will be called with no arguments. The function
19604 must check if the context is appropriate for it to act. If yes,
19605 it should do its thing and then return a non-nil value. If the
19606 context is wrong, just do nothing and return nil.")
19608 (defvar org-tab-first-hook nil
19609 "Hook for functions to attach themselves to TAB.
19610 See `org-ctrl-c-ctrl-c-hook' for more information.
19611 This hook runs as the first action when TAB is pressed, even before
19612 `org-cycle' messes around with the `outline-regexp' to cater for
19613 inline tasks and plain list item folding.
19614 If any function in this hook returns t, any other actions that
19615 would have been caused by TAB (such as table field motion or visibility
19616 cycling) will not occur.")
19618 (defvar org-tab-after-check-for-table-hook nil
19619 "Hook for functions to attach themselves to TAB.
19620 See `org-ctrl-c-ctrl-c-hook' for more information.
19621 This hook runs after it has been established that the cursor is not in a
19622 table, but before checking if the cursor is in a headline or if global cycling
19623 should be done.
19624 If any function in this hook returns t, not other actions like visibility
19625 cycling will be done.")
19627 (defvar org-tab-after-check-for-cycling-hook nil
19628 "Hook for functions to attach themselves to TAB.
19629 See `org-ctrl-c-ctrl-c-hook' for more information.
19630 This hook runs after it has been established that not table field motion and
19631 not visibility should be done because of current context. This is probably
19632 the place where a package like yasnippets can hook in.")
19634 (defvar org-tab-before-tab-emulation-hook nil
19635 "Hook for functions to attach themselves to TAB.
19636 See `org-ctrl-c-ctrl-c-hook' for more information.
19637 This hook runs after every other options for TAB have been exhausted, but
19638 before indentation and \t insertion takes place.")
19640 (defvar org-metaleft-hook nil
19641 "Hook for functions attaching themselves to `M-left'.
19642 See `org-ctrl-c-ctrl-c-hook' for more information.")
19643 (defvar org-metaright-hook nil
19644 "Hook for functions attaching themselves to `M-right'.
19645 See `org-ctrl-c-ctrl-c-hook' for more information.")
19646 (defvar org-metaup-hook nil
19647 "Hook for functions attaching themselves to `M-up'.
19648 See `org-ctrl-c-ctrl-c-hook' for more information.")
19649 (defvar org-metadown-hook nil
19650 "Hook for functions attaching themselves to `M-down'.
19651 See `org-ctrl-c-ctrl-c-hook' for more information.")
19652 (defvar org-shiftmetaleft-hook nil
19653 "Hook for functions attaching themselves to `M-S-left'.
19654 See `org-ctrl-c-ctrl-c-hook' for more information.")
19655 (defvar org-shiftmetaright-hook nil
19656 "Hook for functions attaching themselves to `M-S-right'.
19657 See `org-ctrl-c-ctrl-c-hook' for more information.")
19658 (defvar org-shiftmetaup-hook nil
19659 "Hook for functions attaching themselves to `M-S-up'.
19660 See `org-ctrl-c-ctrl-c-hook' for more information.")
19661 (defvar org-shiftmetadown-hook nil
19662 "Hook for functions attaching themselves to `M-S-down'.
19663 See `org-ctrl-c-ctrl-c-hook' for more information.")
19664 (defvar org-metareturn-hook nil
19665 "Hook for functions attaching themselves to `M-RET'.
19666 See `org-ctrl-c-ctrl-c-hook' for more information.")
19667 (defvar org-shiftup-hook nil
19668 "Hook for functions attaching themselves to `S-up'.
19669 See `org-ctrl-c-ctrl-c-hook' for more information.")
19670 (defvar org-shiftup-final-hook nil
19671 "Hook for functions attaching themselves to `S-up'.
19672 This one runs after all other options except shift-select have been excluded.
19673 See `org-ctrl-c-ctrl-c-hook' for more information.")
19674 (defvar org-shiftdown-hook nil
19675 "Hook for functions attaching themselves to `S-down'.
19676 See `org-ctrl-c-ctrl-c-hook' for more information.")
19677 (defvar org-shiftdown-final-hook nil
19678 "Hook for functions attaching themselves to `S-down'.
19679 This one runs after all other options except shift-select have been excluded.
19680 See `org-ctrl-c-ctrl-c-hook' for more information.")
19681 (defvar org-shiftleft-hook nil
19682 "Hook for functions attaching themselves to `S-left'.
19683 See `org-ctrl-c-ctrl-c-hook' for more information.")
19684 (defvar org-shiftleft-final-hook nil
19685 "Hook for functions attaching themselves to `S-left'.
19686 This one runs after all other options except shift-select have been excluded.
19687 See `org-ctrl-c-ctrl-c-hook' for more information.")
19688 (defvar org-shiftright-hook nil
19689 "Hook for functions attaching themselves to `S-right'.
19690 See `org-ctrl-c-ctrl-c-hook' for more information.")
19691 (defvar org-shiftright-final-hook nil
19692 "Hook for functions attaching themselves to `S-right'.
19693 This one runs after all other options except shift-select have been excluded.
19694 See `org-ctrl-c-ctrl-c-hook' for more information.")
19696 (defun org-modifier-cursor-error ()
19697 "Throw an error, a modified cursor command was applied in wrong context."
19698 (user-error "This command is active in special context like tables, headlines or items"))
19700 (defun org-shiftselect-error ()
19701 "Throw an error because Shift-Cursor command was applied in wrong context."
19702 (if (and (boundp 'shift-select-mode) shift-select-mode)
19703 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19704 (user-error "This command works only in special context like headlines or timestamps")))
19706 (defun org-call-for-shift-select (cmd)
19707 (let ((this-command-keys-shift-translated t))
19708 (call-interactively cmd)))
19710 (defun org-shifttab (&optional arg)
19711 "Global visibility cycling or move to previous table field.
19712 Call `org-table-previous-field' within a table.
19713 When ARG is nil, cycle globally through visibility states.
19714 When ARG is a numeric prefix, show contents of this level."
19715 (interactive "P")
19716 (cond
19717 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19718 ((integerp arg)
19719 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19720 (message "Content view to level: %d" arg)
19721 (org-content (prefix-numeric-value arg2))
19722 (org-cycle-show-empty-lines t)
19723 (setq org-cycle-global-status 'overview)))
19724 (t (call-interactively 'org-global-cycle))))
19726 (defun org-shiftmetaleft ()
19727 "Promote subtree or delete table column.
19728 Calls `org-promote-subtree', `org-outdent-item-tree', or
19729 `org-table-delete-column', depending on context. See the
19730 individual commands for more information."
19731 (interactive)
19732 (cond
19733 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19734 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19735 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19736 ((if (not (org-region-active-p)) (org-at-item-p)
19737 (save-excursion (goto-char (region-beginning))
19738 (org-at-item-p)))
19739 (call-interactively 'org-outdent-item-tree))
19740 (t (org-modifier-cursor-error))))
19742 (defun org-shiftmetaright ()
19743 "Demote subtree or insert table column.
19744 Calls `org-demote-subtree', `org-indent-item-tree', or
19745 `org-table-insert-column', depending on context. See the
19746 individual commands for more information."
19747 (interactive)
19748 (cond
19749 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19750 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19751 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19752 ((if (not (org-region-active-p)) (org-at-item-p)
19753 (save-excursion (goto-char (region-beginning))
19754 (org-at-item-p)))
19755 (call-interactively 'org-indent-item-tree))
19756 (t (org-modifier-cursor-error))))
19758 (defun org-shiftmetaup (&optional arg)
19759 "Move subtree up or kill table row.
19760 Calls `org-move-subtree-up' or `org-table-kill-row' or
19761 `org-move-item-up' or `org-timestamp-up', depending on context.
19762 See the individual commands for more information."
19763 (interactive "P")
19764 (cond
19765 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19766 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19767 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19768 ((org-at-item-p) (call-interactively 'org-move-item-up))
19769 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19770 (call-interactively 'org-timestamp-up)))
19771 (t (call-interactively 'org-drag-line-backward))))
19773 (defun org-shiftmetadown (&optional arg)
19774 "Move subtree down or insert table row.
19775 Calls `org-move-subtree-down' or `org-table-insert-row' or
19776 `org-move-item-down' or `org-timestamp-up', depending on context.
19777 See the individual commands for more information."
19778 (interactive "P")
19779 (cond
19780 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19781 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19782 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19783 ((org-at-item-p) (call-interactively 'org-move-item-down))
19784 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19785 (call-interactively 'org-timestamp-down)))
19786 (t (call-interactively 'org-drag-line-forward))))
19788 (defsubst org-hidden-tree-error ()
19789 (user-error
19790 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19792 (defun org-metaleft (&optional arg)
19793 "Promote heading or move table column to left.
19794 Calls `org-do-promote' or `org-table-move-column', depending on context.
19795 With no specific context, calls the Emacs default `backward-word'.
19796 See the individual commands for more information."
19797 (interactive "P")
19798 (cond
19799 ((run-hook-with-args-until-success 'org-metaleft-hook))
19800 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19801 ((org-with-limited-levels
19802 (or (org-at-heading-p)
19803 (and (org-region-active-p)
19804 (save-excursion
19805 (goto-char (region-beginning))
19806 (org-at-heading-p)))))
19807 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19808 (call-interactively 'org-do-promote))
19809 ;; At an inline task.
19810 ((org-at-heading-p)
19811 (call-interactively 'org-inlinetask-promote))
19812 ((or (org-at-item-p)
19813 (and (org-region-active-p)
19814 (save-excursion
19815 (goto-char (region-beginning))
19816 (org-at-item-p))))
19817 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19818 (call-interactively 'org-outdent-item))
19819 (t (call-interactively 'backward-word))))
19821 (defun org-metaright (&optional arg)
19822 "Demote a subtree, a list item or move table column to right.
19823 In front of a drawer or a block keyword, indent it correctly.
19824 With no specific context, calls the Emacs default `forward-word'.
19825 See the individual commands for more information."
19826 (interactive "P")
19827 (cond
19828 ((run-hook-with-args-until-success 'org-metaright-hook))
19829 ((org-at-table-p) (call-interactively 'org-table-move-column))
19830 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19831 ((org-at-block-p) (call-interactively 'org-indent-block))
19832 ((org-with-limited-levels
19833 (or (org-at-heading-p)
19834 (and (org-region-active-p)
19835 (save-excursion
19836 (goto-char (region-beginning))
19837 (org-at-heading-p)))))
19838 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19839 (call-interactively 'org-do-demote))
19840 ;; At an inline task.
19841 ((org-at-heading-p)
19842 (call-interactively 'org-inlinetask-demote))
19843 ((or (org-at-item-p)
19844 (and (org-region-active-p)
19845 (save-excursion
19846 (goto-char (region-beginning))
19847 (org-at-item-p))))
19848 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19849 (call-interactively 'org-indent-item))
19850 (t (call-interactively 'forward-word))))
19852 (defun org-check-for-hidden (what)
19853 "Check if there are hidden headlines/items in the current visual line.
19854 WHAT can be either `headlines' or `items'. If the current line is
19855 an outline or item heading and it has a folded subtree below it,
19856 this function returns t, nil otherwise."
19857 (let ((re (cond
19858 ((eq what 'headlines) org-outline-regexp-bol)
19859 ((eq what 'items) (org-item-beginning-re))
19860 (t (error "This should not happen"))))
19861 beg end)
19862 (save-excursion
19863 (catch 'exit
19864 (unless (org-region-active-p)
19865 (setq beg (point-at-bol))
19866 (beginning-of-line 2)
19867 (while (and (not (eobp)) ;; this is like `next-line'
19868 (get-char-property (1- (point)) 'invisible))
19869 (beginning-of-line 2))
19870 (setq end (point))
19871 (goto-char beg)
19872 (goto-char (point-at-eol))
19873 (setq end (max end (point)))
19874 (while (re-search-forward re end t)
19875 (if (get-char-property (match-beginning 0) 'invisible)
19876 (throw 'exit t))))
19877 nil))))
19879 (defun org-metaup (&optional arg)
19880 "Move subtree up or move table row up.
19881 Calls `org-move-subtree-up' or `org-table-move-row' or
19882 `org-move-item-up', depending on context. See the individual commands
19883 for more information."
19884 (interactive "P")
19885 (cond
19886 ((run-hook-with-args-until-success 'org-metaup-hook))
19887 ((org-region-active-p)
19888 (let* ((a (min (region-beginning) (region-end)))
19889 (b (1- (max (region-beginning) (region-end))))
19890 (c (save-excursion (goto-char a)
19891 (move-beginning-of-line 0)))
19892 (d (save-excursion (goto-char a)
19893 (move-end-of-line 0) (point))))
19894 (transpose-regions a b c d)
19895 (goto-char c)))
19896 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19897 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19898 ((org-at-item-p) (call-interactively 'org-move-item-up))
19899 (t (org-drag-element-backward))))
19901 (defun org-metadown (&optional arg)
19902 "Move subtree down or move table row down.
19903 Calls `org-move-subtree-down' or `org-table-move-row' or
19904 `org-move-item-down', depending on context. See the individual
19905 commands for more information."
19906 (interactive "P")
19907 (cond
19908 ((run-hook-with-args-until-success 'org-metadown-hook))
19909 ((org-region-active-p)
19910 (let* ((a (min (region-beginning) (region-end)))
19911 (b (max (region-beginning) (region-end)))
19912 (c (save-excursion (goto-char b)
19913 (move-beginning-of-line 1)))
19914 (d (save-excursion (goto-char b)
19915 (move-end-of-line 1) (1+ (point)))))
19916 (transpose-regions a b c d)
19917 (goto-char d)))
19918 ((org-at-table-p) (call-interactively 'org-table-move-row))
19919 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19920 ((org-at-item-p) (call-interactively 'org-move-item-down))
19921 (t (org-drag-element-forward))))
19923 (defun org-shiftup (&optional arg)
19924 "Increase item in timestamp or increase priority of current headline.
19925 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19926 depending on context. See the individual commands for more information."
19927 (interactive "P")
19928 (cond
19929 ((run-hook-with-args-until-success 'org-shiftup-hook))
19930 ((and org-support-shift-select (org-region-active-p))
19931 (org-call-for-shift-select 'previous-line))
19932 ((org-at-timestamp-p t)
19933 (call-interactively (if org-edit-timestamp-down-means-later
19934 'org-timestamp-down 'org-timestamp-up)))
19935 ((and (not (eq org-support-shift-select 'always))
19936 org-enable-priority-commands
19937 (org-at-heading-p))
19938 (call-interactively 'org-priority-up))
19939 ((and (not org-support-shift-select) (org-at-item-p))
19940 (call-interactively 'org-previous-item))
19941 ((org-clocktable-try-shift 'up arg))
19942 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19943 (org-support-shift-select
19944 (org-call-for-shift-select 'previous-line))
19945 (t (org-shiftselect-error))))
19947 (defun org-shiftdown (&optional arg)
19948 "Decrease item in timestamp or decrease priority of current headline.
19949 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19950 depending on context. See the individual commands for more information."
19951 (interactive "P")
19952 (cond
19953 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19954 ((and org-support-shift-select (org-region-active-p))
19955 (org-call-for-shift-select 'next-line))
19956 ((org-at-timestamp-p t)
19957 (call-interactively (if org-edit-timestamp-down-means-later
19958 'org-timestamp-up 'org-timestamp-down)))
19959 ((and (not (eq org-support-shift-select 'always))
19960 org-enable-priority-commands
19961 (org-at-heading-p))
19962 (call-interactively 'org-priority-down))
19963 ((and (not org-support-shift-select) (org-at-item-p))
19964 (call-interactively 'org-next-item))
19965 ((org-clocktable-try-shift 'down arg))
19966 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19967 (org-support-shift-select
19968 (org-call-for-shift-select 'next-line))
19969 (t (org-shiftselect-error))))
19971 (defun org-shiftright (&optional arg)
19972 "Cycle the thing at point or in the current line, depending on context.
19973 Depending on context, this does one of the following:
19975 - switch a timestamp at point one day into the future
19976 - on a headline, switch to the next TODO keyword.
19977 - on an item, switch entire list to the next bullet type
19978 - on a property line, switch to the next allowed value
19979 - on a clocktable definition line, move time block into the future"
19980 (interactive "P")
19981 (cond
19982 ((run-hook-with-args-until-success 'org-shiftright-hook))
19983 ((and org-support-shift-select (org-region-active-p))
19984 (org-call-for-shift-select 'forward-char))
19985 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19986 ((and (not (eq org-support-shift-select 'always))
19987 (org-at-heading-p))
19988 (let ((org-inhibit-logging
19989 (not org-treat-S-cursor-todo-selection-as-state-change))
19990 (org-inhibit-blocking
19991 (not org-treat-S-cursor-todo-selection-as-state-change)))
19992 (org-call-with-arg 'org-todo 'right)))
19993 ((or (and org-support-shift-select
19994 (not (eq org-support-shift-select 'always))
19995 (org-at-item-bullet-p))
19996 (and (not org-support-shift-select) (org-at-item-p)))
19997 (org-call-with-arg 'org-cycle-list-bullet nil))
19998 ((and (not (eq org-support-shift-select 'always))
19999 (org-at-property-p))
20000 (call-interactively 'org-property-next-allowed-value))
20001 ((org-clocktable-try-shift 'right arg))
20002 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20003 (org-support-shift-select
20004 (org-call-for-shift-select 'forward-char))
20005 (t (org-shiftselect-error))))
20007 (defun org-shiftleft (&optional arg)
20008 "Cycle the thing at point or in the current line, depending on context.
20009 Depending on context, this does one of the following:
20011 - switch a timestamp at point one day into the past
20012 - on a headline, switch to the previous TODO keyword.
20013 - on an item, switch entire list to the previous bullet type
20014 - on a property line, switch to the previous allowed value
20015 - on a clocktable definition line, move time block into the past"
20016 (interactive "P")
20017 (cond
20018 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20019 ((and org-support-shift-select (org-region-active-p))
20020 (org-call-for-shift-select 'backward-char))
20021 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20022 ((and (not (eq org-support-shift-select 'always))
20023 (org-at-heading-p))
20024 (let ((org-inhibit-logging
20025 (not org-treat-S-cursor-todo-selection-as-state-change))
20026 (org-inhibit-blocking
20027 (not org-treat-S-cursor-todo-selection-as-state-change)))
20028 (org-call-with-arg 'org-todo 'left)))
20029 ((or (and org-support-shift-select
20030 (not (eq org-support-shift-select 'always))
20031 (org-at-item-bullet-p))
20032 (and (not org-support-shift-select) (org-at-item-p)))
20033 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20034 ((and (not (eq org-support-shift-select 'always))
20035 (org-at-property-p))
20036 (call-interactively 'org-property-previous-allowed-value))
20037 ((org-clocktable-try-shift 'left arg))
20038 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20039 (org-support-shift-select
20040 (org-call-for-shift-select 'backward-char))
20041 (t (org-shiftselect-error))))
20043 (defun org-shiftcontrolright ()
20044 "Switch to next TODO set."
20045 (interactive)
20046 (cond
20047 ((and org-support-shift-select (org-region-active-p))
20048 (org-call-for-shift-select 'forward-word))
20049 ((and (not (eq org-support-shift-select 'always))
20050 (org-at-heading-p))
20051 (org-call-with-arg 'org-todo 'nextset))
20052 (org-support-shift-select
20053 (org-call-for-shift-select 'forward-word))
20054 (t (org-shiftselect-error))))
20056 (defun org-shiftcontrolleft ()
20057 "Switch to previous TODO set."
20058 (interactive)
20059 (cond
20060 ((and org-support-shift-select (org-region-active-p))
20061 (org-call-for-shift-select 'backward-word))
20062 ((and (not (eq org-support-shift-select 'always))
20063 (org-at-heading-p))
20064 (org-call-with-arg 'org-todo 'previousset))
20065 (org-support-shift-select
20066 (org-call-for-shift-select 'backward-word))
20067 (t (org-shiftselect-error))))
20069 (defun org-shiftcontrolup (&optional n)
20070 "Change timestamps synchronously up in CLOCK log lines.
20071 Optional argument N tells to change by that many units."
20072 (interactive "P")
20073 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20074 (let (org-support-shift-select)
20075 (org-clock-timestamps-up n))
20076 (user-error "Not at a clock log")))
20078 (defun org-shiftcontroldown (&optional n)
20079 "Change timestamps synchronously down in CLOCK log lines.
20080 Optional argument N tells to change by that many units."
20081 (interactive "P")
20082 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20083 (let (org-support-shift-select)
20084 (org-clock-timestamps-down n))
20085 (user-error "Not at a clock log")))
20087 (defun org-ctrl-c-ret ()
20088 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20089 (interactive)
20090 (cond
20091 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20092 (t (call-interactively 'org-insert-heading))))
20094 (defun org-find-visible ()
20095 (let ((s (point)))
20096 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20097 (get-char-property s 'invisible)))
20099 (defun org-find-invisible ()
20100 (let ((s (point)))
20101 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20102 (not (get-char-property s 'invisible))))
20105 (defun org-copy-visible (beg end)
20106 "Copy the visible parts of the region."
20107 (interactive "r")
20108 (let (snippets s)
20109 (save-excursion
20110 (save-restriction
20111 (narrow-to-region beg end)
20112 (setq s (goto-char (point-min)))
20113 (while (not (= (point) (point-max)))
20114 (goto-char (org-find-invisible))
20115 (push (buffer-substring s (point)) snippets)
20116 (setq s (goto-char (org-find-visible))))))
20117 (kill-new (apply 'concat (nreverse snippets)))))
20119 (defun org-copy-special ()
20120 "Copy region in table or copy current subtree.
20121 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20122 See the individual commands for more information."
20123 (interactive)
20124 (call-interactively
20125 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20127 (defun org-cut-special ()
20128 "Cut region in table or cut current subtree.
20129 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20130 See the individual commands for more information."
20131 (interactive)
20132 (call-interactively
20133 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20135 (defun org-paste-special (arg)
20136 "Paste rectangular region into table, or past subtree relative to level.
20137 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20138 See the individual commands for more information."
20139 (interactive "P")
20140 (if (org-at-table-p)
20141 (org-table-paste-rectangle)
20142 (org-paste-subtree arg)))
20144 (defsubst org-in-fixed-width-region-p ()
20145 "Is point in a fixed-width region?"
20146 (save-match-data
20147 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20149 (defun org-edit-special (&optional arg)
20150 "Call a special editor for the element at point.
20151 When at a table, call the formula editor with `org-table-edit-formulas'.
20152 When in a source code block, call `org-edit-src-code'.
20153 When in a fixed-width region, call `org-edit-fixed-width-region'.
20154 When at an #+INCLUDE keyword, visit the included file.
20155 On a link, call `ffap' to visit the link at point.
20156 Otherwise, return a user error."
20157 (interactive "P")
20158 (let ((element (org-element-at-point)))
20159 (assert (not buffer-read-only) nil
20160 "Buffer is read-only: %s" (buffer-name))
20161 (case (org-element-type element)
20162 (src-block
20163 (if (not arg) (org-edit-src-code)
20164 (let* ((info (org-babel-get-src-block-info))
20165 (lang (nth 0 info))
20166 (params (nth 2 info))
20167 (session (cdr (assq :session params))))
20168 (if (not session) (org-edit-src-code)
20169 ;; At a src-block with a session and function called with
20170 ;; an ARG: switch to the buffer related to the inferior
20171 ;; process.
20172 (switch-to-buffer
20173 (funcall (intern (concat "org-babel-prep-session:" lang))
20174 session params))))))
20175 (keyword
20176 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20177 (find-file
20178 (org-remove-double-quotes
20179 (car (org-split-string (org-element-property :value element)))))
20180 (user-error "No special environment to edit here")))
20181 (table
20182 (if (eq (org-element-property :type element) 'table.el)
20183 (org-edit-src-code)
20184 (call-interactively 'org-table-edit-formulas)))
20185 ;; Only Org tables contain `table-row' type elements.
20186 (table-row (call-interactively 'org-table-edit-formulas))
20187 ((example-block export-block) (org-edit-src-code))
20188 (fixed-width (org-edit-fixed-width-region))
20189 (otherwise
20190 ;; No notable element at point. Though, we may be at a link,
20191 ;; which is an object. Thus, scan deeper.
20192 (if (eq (org-element-type (org-element-context element)) 'link)
20193 (call-interactively 'ffap)
20194 (user-error "No special environment to edit here"))))))
20196 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20197 (defun org-ctrl-c-ctrl-c (&optional arg)
20198 "Set tags in headline, or update according to changed information at point.
20200 This command does many different things, depending on context:
20202 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20203 this is what we do.
20205 - If the cursor is on a statistics cookie, update it.
20207 - If the cursor is in a headline, prompt for tags and insert them
20208 into the current line, aligned to `org-tags-column'. When called
20209 with prefix arg, realign all tags in the current buffer.
20211 - If the cursor is in one of the special #+KEYWORD lines, this
20212 triggers scanning the buffer for these lines and updating the
20213 information.
20215 - If the cursor is inside a table, realign the table. This command
20216 works even if the automatic table editor has been turned off.
20218 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20219 the entire table.
20221 - If the cursor is at a footnote reference or definition, jump to
20222 the corresponding definition or references, respectively.
20224 - If the cursor is a the beginning of a dynamic block, update it.
20226 - If the current buffer is a capture buffer, close note and file it.
20228 - If the cursor is on a <<<target>>>, update radio targets and
20229 corresponding links in this buffer.
20231 - If the cursor is on a numbered item in a plain list, renumber the
20232 ordered list.
20234 - If the cursor is on a checkbox, toggle it.
20236 - If the cursor is on a code block, evaluate it. The variable
20237 `org-confirm-babel-evaluate' can be used to control prompting
20238 before code block evaluation, by default every code block
20239 evaluation requires confirmation. Code block evaluation can be
20240 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20241 (interactive "P")
20242 (cond
20243 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20244 org-occur-highlights
20245 org-latex-fragment-image-overlays)
20246 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20247 (org-remove-occur-highlights)
20248 (org-remove-latex-fragment-image-overlays)
20249 (message "Temporary highlights/overlays removed from current buffer"))
20250 ((and (local-variable-p 'org-finish-function (current-buffer))
20251 (fboundp org-finish-function))
20252 (funcall org-finish-function))
20253 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20255 (let* ((context (org-element-context)) (type (org-element-type context)))
20256 ;; Test if point is within a blank line.
20257 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20258 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20259 (user-error "C-c C-c can do nothing useful at this location"))
20260 (case type
20261 ;; When at a link, act according to the parent instead.
20262 (link (setq context (org-element-property :parent context))
20263 (setq type (org-element-type context)))
20264 ;; Unsupported object types: check parent element instead.
20265 ((bold code entity export-snippet inline-babel-call inline-src-block
20266 italic latex-fragment line-break macro strike-through subscript
20267 superscript underline verbatim)
20268 (while (and (setq context (org-element-property :parent context))
20269 (not (memq (setq type (org-element-type context))
20270 '(paragraph verse-block table-cell)))))))
20271 ;; For convenience: at the first line of a paragraph on the
20272 ;; same line as an item, apply function on that item instead.
20273 (when (eq type 'paragraph)
20274 (let ((parent (org-element-property :parent context)))
20275 (when (and (eq (org-element-type parent) 'item)
20276 (= (point-at-bol) (org-element-property :begin parent)))
20277 (setq context parent type 'item))))
20278 ;; Act according to type of element or object at point.
20279 (case type
20280 (clock (org-clock-update-time-maybe))
20281 (dynamic-block
20282 (save-excursion
20283 (goto-char (org-element-property :post-affiliated context))
20284 (org-update-dblock)))
20285 (footnote-definition
20286 (goto-char (org-element-property :post-affiliated context))
20287 (call-interactively 'org-footnote-action))
20288 (footnote-reference (call-interactively 'org-footnote-action))
20289 ((headline inlinetask)
20290 (save-excursion (goto-char (org-element-property :begin context))
20291 (call-interactively 'org-set-tags)))
20292 (item
20293 ;; At an item: a double C-u set checkbox to "[-]"
20294 ;; unconditionally, whereas a single one will toggle its
20295 ;; presence. Without an universal argument, if the item
20296 ;; has a checkbox, toggle it. Otherwise repair the list.
20297 (let* ((box (org-element-property :checkbox context))
20298 (struct (org-element-property :structure context))
20299 (old-struct (copy-tree struct))
20300 (parents (org-list-parents-alist struct))
20301 (prevs (org-list-prevs-alist struct))
20302 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20303 (org-list-set-checkbox
20304 (org-element-property :begin context) struct
20305 (cond ((equal arg '(16)) "[-]")
20306 ((and (not box) (equal arg '(4))) "[ ]")
20307 ((or (not box) (equal arg '(4))) nil)
20308 ((eq box 'on) "[ ]")
20309 (t "[X]")))
20310 ;; Mimic `org-list-write-struct' but with grabbing
20311 ;; a return value from `org-list-struct-fix-box'.
20312 (org-list-struct-fix-ind struct parents 2)
20313 (org-list-struct-fix-item-end struct)
20314 (org-list-struct-fix-bul struct prevs)
20315 (org-list-struct-fix-ind struct parents)
20316 (let ((block-item
20317 (org-list-struct-fix-box struct parents prevs orderedp)))
20318 (if (and box (equal struct old-struct))
20319 (if (equal arg '(16))
20320 (message "Checkboxes already reset")
20321 (user-error "Cannot toggle this checkbox: %s"
20322 (if (eq box 'on)
20323 "all subitems checked"
20324 "unchecked subitems")))
20325 (org-list-struct-apply-struct struct old-struct)
20326 (org-update-checkbox-count-maybe))
20327 (when block-item
20328 (message "Checkboxes were removed due to empty box at line %d"
20329 (org-current-line block-item))))))
20330 (keyword
20331 (let ((org-inhibit-startup-visibility-stuff t)
20332 (org-startup-align-all-tables nil))
20333 (when (boundp 'org-table-coordinate-overlays)
20334 (mapc 'delete-overlay org-table-coordinate-overlays)
20335 (setq org-table-coordinate-overlays nil))
20336 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20337 (message "Local setup has been refreshed"))
20338 (plain-list
20339 ;; At a plain list, with a double C-u argument, set
20340 ;; checkboxes of each item to "[-]", whereas a single one
20341 ;; will toggle their presence according to the state of the
20342 ;; first item in the list. Without an argument, repair the
20343 ;; list.
20344 (let* ((begin (org-element-property :contents-begin context))
20345 (beginm (move-marker (make-marker) begin))
20346 (struct (org-element-property :structure context))
20347 (old-struct (copy-tree struct))
20348 (first-box (save-excursion
20349 (goto-char begin)
20350 (looking-at org-list-full-item-re)
20351 (match-string-no-properties 3)))
20352 (new-box (cond ((equal arg '(16)) "[-]")
20353 ((equal arg '(4)) (unless first-box "[ ]"))
20354 ((equal first-box "[X]") "[ ]")
20355 (t "[X]"))))
20356 (cond
20357 (arg
20358 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20359 (org-list-get-all-items
20360 begin struct (org-list-prevs-alist struct))))
20361 ((and first-box (eq (point) begin))
20362 ;; For convenience, when point is at bol on the first
20363 ;; item of the list and no argument is provided, simply
20364 ;; toggle checkbox of that item, if any.
20365 (org-list-set-checkbox begin struct new-box)))
20366 (org-list-write-struct
20367 struct (org-list-parents-alist struct) old-struct)
20368 (org-update-checkbox-count-maybe)
20369 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20370 ((property-drawer node-property)
20371 (call-interactively 'org-property-action))
20372 ((radio-target target)
20373 (call-interactively 'org-update-radio-target-regexp))
20374 (statistics-cookie
20375 (call-interactively 'org-update-statistics-cookies))
20376 ((table table-cell table-row)
20377 ;; At a table, recalculate every field and align it. Also
20378 ;; send the table if necessary. If the table has
20379 ;; a `table.el' type, just give up. At a table row or
20380 ;; cell, maybe recalculate line but always align table.
20381 (if (eq (org-element-property :type context) 'table.el)
20382 (message "Use C-c ' to edit table.el tables")
20383 (let ((org-enable-table-editor t))
20384 (if (or (eq type 'table)
20385 ;; Check if point is at a TBLFM line.
20386 (and (eq type 'table-row)
20387 (= (point) (org-element-property :end context))))
20388 (save-excursion
20389 (if (org-at-TBLFM-p)
20390 (progn (require 'org-table)
20391 (org-table-calc-current-TBLFM))
20392 (goto-char (org-element-property :contents-begin context))
20393 (org-call-with-arg 'org-table-recalculate (or arg t))
20394 (orgtbl-send-table 'maybe)))
20395 (org-table-maybe-eval-formula)
20396 (cond (arg (call-interactively 'org-table-recalculate))
20397 ((org-table-maybe-recalculate-line))
20398 (t (org-table-align)))))))
20399 (timestamp (org-timestamp-change 0 'day))
20400 (otherwise
20401 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20402 (user-error
20403 "C-c C-c can do nothing useful at this location")))))))))
20405 (defun org-mode-restart ()
20406 (interactive)
20407 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
20408 (funcall major-mode)
20409 (hack-local-variables)
20410 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
20411 (org-indent-mode -1)))
20412 (message "%s restarted" major-mode))
20414 (defun org-kill-note-or-show-branches ()
20415 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20416 (interactive)
20417 (if (not org-finish-function)
20418 (progn
20419 (hide-subtree)
20420 (call-interactively 'show-branches))
20421 (let ((org-note-abort t))
20422 (funcall org-finish-function))))
20424 (defun org-open-line (n)
20425 "Insert a new row in tables, call `open-line' elsewhere.
20426 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
20427 (interactive "*p")
20428 (cond
20429 ((not org-special-ctrl-o)
20430 (open-line n))
20431 ((org-at-table-p)
20432 (org-table-insert-row))
20434 (open-line n))))
20436 (defun org-return (&optional indent)
20437 "Goto next table row or insert a newline.
20438 Calls `org-table-next-row' or `newline', depending on context.
20439 See the individual commands for more information."
20440 (interactive)
20441 (let (org-ts-what)
20442 (cond
20443 ((or (bobp) (org-in-src-block-p))
20444 (if indent (newline-and-indent) (newline)))
20445 ((org-at-table-p)
20446 (org-table-justify-field-maybe)
20447 (call-interactively 'org-table-next-row))
20448 ;; when `newline-and-indent' is called within a list, make sure
20449 ;; text moved stays inside the item.
20450 ((and (org-in-item-p) indent)
20451 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20452 (progn
20453 (save-match-data (newline))
20454 (org-indent-line-to (length (match-string 0))))
20455 (let ((ind (org-get-indentation)))
20456 (newline)
20457 (if (org-looking-back org-list-end-re)
20458 (org-indent-line)
20459 (org-indent-line-to ind)))))
20460 ((and org-return-follows-link
20461 (org-at-timestamp-p t)
20462 (not (eq org-ts-what 'after)))
20463 (org-follow-timestamp-link))
20464 ((and org-return-follows-link
20465 (let ((tprop (get-text-property (point) 'face)))
20466 (or (eq tprop 'org-link)
20467 (and (listp tprop) (memq 'org-link tprop)))))
20468 (call-interactively 'org-open-at-point))
20469 ((and (org-at-heading-p)
20470 (looking-at
20471 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20472 (org-show-entry)
20473 (end-of-line 1)
20474 (newline))
20475 (t (if indent (newline-and-indent) (newline))))))
20477 (defun org-return-indent ()
20478 "Goto next table row or insert a newline and indent.
20479 Calls `org-table-next-row' or `newline-and-indent', depending on
20480 context. See the individual commands for more information."
20481 (interactive)
20482 (org-return t))
20484 (defun org-ctrl-c-star ()
20485 "Compute table, or change heading status of lines.
20486 Calls `org-table-recalculate' or `org-toggle-heading',
20487 depending on context."
20488 (interactive)
20489 (cond
20490 ((org-at-table-p)
20491 (call-interactively 'org-table-recalculate))
20493 ;; Convert all lines in region to list items
20494 (call-interactively 'org-toggle-heading))))
20496 (defun org-ctrl-c-minus ()
20497 "Insert separator line in table or modify bullet status of line.
20498 Also turns a plain line or a region of lines into list items.
20499 Calls `org-table-insert-hline', `org-toggle-item', or
20500 `org-cycle-list-bullet', depending on context."
20501 (interactive)
20502 (cond
20503 ((org-at-table-p)
20504 (call-interactively 'org-table-insert-hline))
20505 ((org-region-active-p)
20506 (call-interactively 'org-toggle-item))
20507 ((org-in-item-p)
20508 (call-interactively 'org-cycle-list-bullet))
20510 (call-interactively 'org-toggle-item))))
20512 (defun org-toggle-item (arg)
20513 "Convert headings or normal lines to items, items to normal lines.
20514 If there is no active region, only the current line is considered.
20516 If the first non blank line in the region is a headline, convert
20517 all headlines to items, shifting text accordingly.
20519 If it is an item, convert all items to normal lines.
20521 If it is normal text, change region into a list of items.
20522 With a prefix argument ARG, change the region in a single item."
20523 (interactive "P")
20524 (let ((shift-text
20525 (function
20526 ;; Shift text in current section to IND, from point to END.
20527 ;; The function leaves point to END line.
20528 (lambda (ind end)
20529 (let ((min-i 1000) (end (copy-marker end)))
20530 ;; First determine the minimum indentation (MIN-I) of
20531 ;; the text.
20532 (save-excursion
20533 (catch 'exit
20534 (while (< (point) end)
20535 (let ((i (org-get-indentation)))
20536 (cond
20537 ;; Skip blank lines and inline tasks.
20538 ((looking-at "^[ \t]*$"))
20539 ((looking-at org-outline-regexp-bol))
20540 ;; We can't find less than 0 indentation.
20541 ((zerop i) (throw 'exit (setq min-i 0)))
20542 ((< i min-i) (setq min-i i))))
20543 (forward-line))))
20544 ;; Then indent each line so that a line indented to
20545 ;; MIN-I becomes indented to IND. Ignore blank lines
20546 ;; and inline tasks in the process.
20547 (let ((delta (- ind min-i)))
20548 (while (< (point) end)
20549 (unless (or (looking-at "^[ \t]*$")
20550 (looking-at org-outline-regexp-bol))
20551 (org-indent-line-to (+ (org-get-indentation) delta)))
20552 (forward-line)))))))
20553 (skip-blanks
20554 (function
20555 ;; Return beginning of first non-blank line, starting from
20556 ;; line at POS.
20557 (lambda (pos)
20558 (save-excursion
20559 (goto-char pos)
20560 (skip-chars-forward " \r\t\n")
20561 (point-at-bol)))))
20562 beg end)
20563 ;; Determine boundaries of changes.
20564 (if (org-region-active-p)
20565 (setq beg (funcall skip-blanks (region-beginning))
20566 end (copy-marker (region-end)))
20567 (setq beg (funcall skip-blanks (point-at-bol))
20568 end (copy-marker (point-at-eol))))
20569 ;; Depending on the starting line, choose an action on the text
20570 ;; between BEG and END.
20571 (org-with-limited-levels
20572 (save-excursion
20573 (goto-char beg)
20574 (cond
20575 ;; Case 1. Start at an item: de-itemize. Note that it only
20576 ;; happens when a region is active: `org-ctrl-c-minus'
20577 ;; would call `org-cycle-list-bullet' otherwise.
20578 ((org-at-item-p)
20579 (while (< (point) end)
20580 (when (org-at-item-p)
20581 (skip-chars-forward " \t")
20582 (delete-region (point) (match-end 0)))
20583 (forward-line)))
20584 ;; Case 2. Start at an heading: convert to items.
20585 ((org-at-heading-p)
20586 (let* ((bul (org-list-bullet-string "-"))
20587 (bul-len (length bul))
20588 ;; Indentation of the first heading. It should be
20589 ;; relative to the indentation of its parent, if any.
20590 (start-ind (save-excursion
20591 (cond
20592 ((not org-adapt-indentation) 0)
20593 ((not (outline-previous-heading)) 0)
20594 (t (length (match-string 0))))))
20595 ;; Level of first heading. Further headings will be
20596 ;; compared to it to determine hierarchy in the list.
20597 (ref-level (org-reduced-level (org-outline-level))))
20598 (while (< (point) end)
20599 (let* ((level (org-reduced-level (org-outline-level)))
20600 (delta (max 0 (- level ref-level))))
20601 ;; If current headline is less indented than the first
20602 ;; one, set it as reference, in order to preserve
20603 ;; subtrees.
20604 (when (< level ref-level) (setq ref-level level))
20605 (replace-match bul t t)
20606 (org-indent-line-to (+ start-ind (* delta bul-len)))
20607 ;; Ensure all text down to END (or SECTION-END) belongs
20608 ;; to the newly created item.
20609 (let ((section-end (save-excursion
20610 (or (outline-next-heading) (point)))))
20611 (forward-line)
20612 (funcall shift-text
20613 (+ start-ind (* (1+ delta) bul-len))
20614 (min end section-end)))))))
20615 ;; Case 3. Normal line with ARG: make the first line of region
20616 ;; an item, and shift indentation of others lines to
20617 ;; set them as item's body.
20618 (arg (let* ((bul (org-list-bullet-string "-"))
20619 (bul-len (length bul))
20620 (ref-ind (org-get-indentation)))
20621 (skip-chars-forward " \t")
20622 (insert bul)
20623 (forward-line)
20624 (while (< (point) end)
20625 ;; Ensure that lines less indented than first one
20626 ;; still get included in item body.
20627 (funcall shift-text
20628 (+ ref-ind bul-len)
20629 (min end (save-excursion (or (outline-next-heading)
20630 (point)))))
20631 (forward-line))))
20632 ;; Case 4. Normal line without ARG: turn each non-item line
20633 ;; into an item.
20635 (while (< (point) end)
20636 (unless (or (org-at-heading-p) (org-at-item-p))
20637 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20638 (replace-match
20639 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20640 (forward-line))))))))
20642 (defun org-toggle-heading (&optional nstars)
20643 "Convert headings to normal text, or items or text to headings.
20644 If there is no active region, only convert the current line.
20646 With a \\[universal-argument] prefix, convert the whole list at
20647 point into heading.
20649 In a region:
20651 - If the first non blank line is a headline, remove the stars
20652 from all headlines in the region.
20654 - If it is a normal line, turn each and every normal line (i.e.,
20655 not an heading or an item) in the region into headings. If you
20656 want to convert only the first line of this region, use one
20657 universal prefix argument.
20659 - If it is a plain list item, turn all plain list items into headings.
20661 When converting a line into a heading, the number of stars is chosen
20662 such that the lines become children of the current entry. However,
20663 when a numeric prefix argument is given, its value determines the
20664 number of stars to add."
20665 (interactive "P")
20666 (let ((skip-blanks
20667 (function
20668 ;; Return beginning of first non-blank line, starting from
20669 ;; line at POS.
20670 (lambda (pos)
20671 (save-excursion
20672 (goto-char pos)
20673 (while (org-at-comment-p) (forward-line))
20674 (skip-chars-forward " \r\t\n")
20675 (point-at-bol)))))
20676 beg end toggled)
20677 ;; Determine boundaries of changes. If a universal prefix has
20678 ;; been given, put the list in a region. If region ends at a bol,
20679 ;; do not consider the last line to be in the region.
20681 (when (and current-prefix-arg (org-at-item-p))
20682 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20683 (org-mark-element))
20685 (if (org-region-active-p)
20686 (setq beg (funcall skip-blanks (region-beginning))
20687 end (copy-marker (save-excursion
20688 (goto-char (region-end))
20689 (if (bolp) (point) (point-at-eol)))))
20690 (setq beg (funcall skip-blanks (point-at-bol))
20691 end (copy-marker (point-at-eol))))
20692 ;; Ensure inline tasks don't count as headings.
20693 (org-with-limited-levels
20694 (save-excursion
20695 (goto-char beg)
20696 (cond
20697 ;; Case 1. Started at an heading: de-star headings.
20698 ((org-at-heading-p)
20699 (while (< (point) end)
20700 (when (org-at-heading-p t)
20701 (looking-at org-outline-regexp) (replace-match "")
20702 (setq toggled t))
20703 (forward-line)))
20704 ;; Case 2. Started at an item: change items into headlines.
20705 ;; One star will be added by `org-list-to-subtree'.
20706 ((org-at-item-p)
20707 (let* ((stars (make-string
20708 ;; subtract the star that will be added again by
20709 ;; `org-list-to-subtree'
20710 (if (numberp nstars) (1- nstars)
20711 (or (org-current-level) 0))
20712 ?*))
20713 (add-stars
20714 (cond (nstars "") ; stars from prefix only
20715 ((equal stars "") "") ; before first heading
20716 (org-odd-levels-only "*") ; inside heading, odd
20717 (t "")))) ; inside heading, oddeven
20718 (while (< (point) end)
20719 (when (org-at-item-p)
20720 ;; Pay attention to cases when region ends before list.
20721 (let* ((struct (org-list-struct))
20722 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20723 (save-restriction
20724 (narrow-to-region (point) list-end)
20725 (insert
20726 (org-list-to-subtree
20727 (org-list-parse-list t)
20728 '(:istart (concat stars add-stars (funcall get-stars depth))
20729 :icount (concat stars add-stars (funcall get-stars depth)))))))
20730 (setq toggled t))
20731 (forward-line))))
20732 ;; Case 3. Started at normal text: make every line an heading,
20733 ;; skipping headlines and items.
20734 (t (let* ((stars
20735 (make-string
20736 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20737 (add-stars
20738 (cond (nstars "") ; stars from prefix only
20739 ((equal stars "") "*") ; before first heading
20740 (org-odd-levels-only "**") ; inside heading, odd
20741 (t "*"))) ; inside heading, oddeven
20742 (rpl (concat stars add-stars " "))
20743 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20744 (while (< (point) (if (equal nstars '(4)) lend end))
20745 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20746 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20747 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20748 (forward-line)))))))
20749 (unless toggled (message "Cannot toggle heading from here"))))
20751 (defun org-meta-return (&optional arg)
20752 "Insert a new heading or wrap a region in a table.
20753 Calls `org-insert-heading' or `org-table-wrap-region', depending
20754 on context. See the individual commands for more information."
20755 (interactive "P")
20756 (org-check-before-invisible-edit 'insert)
20757 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20758 (let* ((element (org-element-at-point))
20759 (type (org-element-type element)))
20760 (when (eq type 'table-row)
20761 (setq element (org-element-property :parent element))
20762 (setq type 'table))
20763 (if (and (eq type 'table)
20764 (eq (org-element-property :type element) 'org)
20765 (>= (point) (org-element-property :contents-begin element))
20766 (< (point) (org-element-property :contents-end element)))
20767 (call-interactively 'org-table-wrap-region)
20768 (call-interactively 'org-insert-heading)))))
20770 ;;; Menu entries
20772 (defsubst org-in-subtree-not-table-p ()
20773 "Are we in a subtree and not in a table?"
20774 (and (not (org-before-first-heading-p))
20775 (not (org-at-table-p))))
20777 ;; Define the Org-mode menus
20778 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20779 '("Tbl"
20780 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20781 ["Next Field" org-cycle (org-at-table-p)]
20782 ["Previous Field" org-shifttab (org-at-table-p)]
20783 ["Next Row" org-return (org-at-table-p)]
20784 "--"
20785 ["Blank Field" org-table-blank-field (org-at-table-p)]
20786 ["Edit Field" org-table-edit-field (org-at-table-p)]
20787 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20788 "--"
20789 ("Column"
20790 ["Move Column Left" org-metaleft (org-at-table-p)]
20791 ["Move Column Right" org-metaright (org-at-table-p)]
20792 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20793 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20794 ("Row"
20795 ["Move Row Up" org-metaup (org-at-table-p)]
20796 ["Move Row Down" org-metadown (org-at-table-p)]
20797 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20798 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20799 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20800 "--"
20801 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20802 ("Rectangle"
20803 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20804 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20805 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20806 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20807 "--"
20808 ("Calculate"
20809 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20810 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20811 ["Edit Formulas" org-edit-special (org-at-table-p)]
20812 "--"
20813 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20814 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20815 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20816 "--"
20817 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20818 "--"
20819 ["Sum Column/Rectangle" org-table-sum
20820 (or (org-at-table-p) (org-region-active-p))]
20821 ["Which Column?" org-table-current-column (org-at-table-p)])
20822 ["Debug Formulas"
20823 org-table-toggle-formula-debugger
20824 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20825 ["Show Col/Row Numbers"
20826 org-table-toggle-coordinate-overlays
20827 :style toggle
20828 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20829 "--"
20830 ["Create" org-table-create (and (not (org-at-table-p))
20831 org-enable-table-editor)]
20832 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20833 ["Import from File" org-table-import (not (org-at-table-p))]
20834 ["Export to File" org-table-export (org-at-table-p)]
20835 "--"
20836 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20838 (easy-menu-define org-org-menu org-mode-map "Org menu"
20839 '("Org"
20840 ("Show/Hide"
20841 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20842 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20843 ["Sparse Tree..." org-sparse-tree t]
20844 ["Reveal Context" org-reveal t]
20845 ["Show All" show-all t]
20846 "--"
20847 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20848 "--"
20849 ["New Heading" org-insert-heading t]
20850 ("Navigate Headings"
20851 ["Up" outline-up-heading t]
20852 ["Next" outline-next-visible-heading t]
20853 ["Previous" outline-previous-visible-heading t]
20854 ["Next Same Level" outline-forward-same-level t]
20855 ["Previous Same Level" outline-backward-same-level t]
20856 "--"
20857 ["Jump" org-goto t])
20858 ("Edit Structure"
20859 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20860 "--"
20861 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20862 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20863 "--"
20864 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20865 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20866 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20867 "--"
20868 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20869 "--"
20870 ["Copy visible text" org-copy-visible t]
20871 "--"
20872 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20873 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20874 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20875 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20876 "--"
20877 ["Sort Region/Children" org-sort t]
20878 "--"
20879 ["Convert to odd levels" org-convert-to-odd-levels t]
20880 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20881 ("Editing"
20882 ["Emphasis..." org-emphasize t]
20883 ["Edit Source Example" org-edit-special t]
20884 "--"
20885 ["Footnote new/jump" org-footnote-action t]
20886 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20887 ("Archive"
20888 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20889 "--"
20890 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20891 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20892 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20894 "--"
20895 ("Hyperlinks"
20896 ["Store Link (Global)" org-store-link t]
20897 ["Find existing link to here" org-occur-link-in-agenda-files t]
20898 ["Insert Link" org-insert-link t]
20899 ["Follow Link" org-open-at-point t]
20900 "--"
20901 ["Next link" org-next-link t]
20902 ["Previous link" org-previous-link t]
20903 "--"
20904 ["Descriptive Links"
20905 org-toggle-link-display
20906 :style radio
20907 :selected org-descriptive-links
20909 ["Literal Links"
20910 org-toggle-link-display
20911 :style radio
20912 :selected (not org-descriptive-links)])
20913 "--"
20914 ("TODO Lists"
20915 ["TODO/DONE/-" org-todo t]
20916 ("Select keyword"
20917 ["Next keyword" org-shiftright (org-at-heading-p)]
20918 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20919 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20920 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20921 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20922 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20923 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20924 "--"
20925 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20926 :selected org-enforce-todo-dependencies :style toggle :active t]
20927 "Settings for tree at point"
20928 ["Do Children sequentially" org-toggle-ordered-property :style radio
20929 :selected (org-entry-get nil "ORDERED")
20930 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20931 ["Do Children parallel" org-toggle-ordered-property :style radio
20932 :selected (not (org-entry-get nil "ORDERED"))
20933 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20934 "--"
20935 ["Set Priority" org-priority t]
20936 ["Priority Up" org-shiftup t]
20937 ["Priority Down" org-shiftdown t]
20938 "--"
20939 ["Get news from all feeds" org-feed-update-all t]
20940 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20941 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20942 ("TAGS and Properties"
20943 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20944 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20945 "--"
20946 ["Set property" org-set-property (not (org-before-first-heading-p))]
20947 ["Column view of properties" org-columns t]
20948 ["Insert Column View DBlock" org-insert-columns-dblock t])
20949 ("Dates and Scheduling"
20950 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20951 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20952 ("Change Date"
20953 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20954 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20955 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20956 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20957 ["Compute Time Range" org-evaluate-time-range t]
20958 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20959 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20960 "--"
20961 ["Custom time format" org-toggle-time-stamp-overlays
20962 :style radio :selected org-display-custom-times]
20963 "--"
20964 ["Goto Calendar" org-goto-calendar t]
20965 ["Date from Calendar" org-date-from-calendar t]
20966 "--"
20967 ["Start/Restart Timer" org-timer-start t]
20968 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20969 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20970 ["Insert Timer String" org-timer t]
20971 ["Insert Timer Item" org-timer-item t])
20972 ("Logging work"
20973 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20974 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20975 ["Clock out" org-clock-out t]
20976 ["Clock cancel" org-clock-cancel t]
20977 "--"
20978 ["Mark as default task" org-clock-mark-default-task t]
20979 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20980 ["Goto running clock" org-clock-goto t]
20981 "--"
20982 ["Display times" org-clock-display t]
20983 ["Create clock table" org-clock-report t]
20984 "--"
20985 ["Record DONE time"
20986 (progn (setq org-log-done (not org-log-done))
20987 (message "Switching to %s will %s record a timestamp"
20988 (car org-done-keywords)
20989 (if org-log-done "automatically" "not")))
20990 :style toggle :selected org-log-done])
20991 "--"
20992 ["Agenda Command..." org-agenda t]
20993 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20994 ("File List for Agenda")
20995 ("Special views current file"
20996 ["TODO Tree" org-show-todo-tree t]
20997 ["Check Deadlines" org-check-deadlines t]
20998 ["Timeline" org-timeline t]
20999 ["Tags/Property tree" org-match-sparse-tree t])
21000 "--"
21001 ["Export/Publish..." org-export-dispatch t]
21002 ("LaTeX"
21003 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21004 :selected org-cdlatex-mode]
21005 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21006 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21007 ["Modify math symbol" org-cdlatex-math-modify
21008 (org-inside-LaTeX-fragment-p)]
21009 ["Insert citation" org-reftex-citation t]
21010 "--"
21011 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21012 "--"
21013 ("MobileOrg"
21014 ["Push Files and Views" org-mobile-push t]
21015 ["Get Captured and Flagged" org-mobile-pull t]
21016 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21017 "--"
21018 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21019 "--"
21020 ("Documentation"
21021 ["Show Version" org-version t]
21022 ["Info Documentation" org-info t])
21023 ("Customize"
21024 ["Browse Org Group" org-customize t]
21025 "--"
21026 ["Expand This Menu" org-create-customize-menu
21027 (fboundp 'customize-menu-create)])
21028 ["Send bug report" org-submit-bug-report t]
21029 "--"
21030 ("Refresh/Reload"
21031 ["Refresh setup current buffer" org-mode-restart t]
21032 ["Reload Org (after update)" org-reload t]
21033 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21036 (defun org-info (&optional node)
21037 "Read documentation for Org-mode in the info system.
21038 With optional NODE, go directly to that node."
21039 (interactive)
21040 (info (format "(org)%s" (or node ""))))
21042 ;;;###autoload
21043 (defun org-submit-bug-report ()
21044 "Submit a bug report on Org-mode via mail.
21046 Don't hesitate to report any problems or inaccurate documentation.
21048 If you don't have setup sending mail from (X)Emacs, please copy the
21049 output buffer into your mail program, as it gives us important
21050 information about your Org-mode version and configuration."
21051 (interactive)
21052 (require 'reporter)
21053 (org-load-modules-maybe)
21054 (org-require-autoloaded-modules)
21055 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21056 (reporter-submit-bug-report
21057 "emacs-orgmode@gnu.org"
21058 (org-version nil 'full)
21059 (let (list)
21060 (save-window-excursion
21061 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21062 (delete-other-windows)
21063 (erase-buffer)
21064 (insert "You are about to submit a bug report to the Org-mode mailing list.
21066 We would like to add your full Org-mode and Outline configuration to the
21067 bug report. This greatly simplifies the work of the maintainer and
21068 other experts on the mailing list.
21070 HOWEVER, some variables you have customized may contain private
21071 information. The names of customers, colleagues, or friends, might
21072 appear in the form of file names, tags, todo states, or search strings.
21073 If you answer yes to the prompt, you might want to check and remove
21074 such private information before sending the email.")
21075 (add-text-properties (point-min) (point-max) '(face org-warning))
21076 (when (yes-or-no-p "Include your Org-mode configuration ")
21077 (mapatoms
21078 (lambda (v)
21079 (and (boundp v)
21080 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21081 (or (and (symbol-value v)
21082 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21083 (and
21084 (get v 'custom-type) (get v 'standard-value)
21085 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21086 (push v list)))))
21087 (kill-buffer (get-buffer "*Warn about privacy*"))
21088 list))
21089 nil nil
21090 "Remember to cover the basics, that is, what you expected to happen and
21091 what in fact did happen. You don't know how to make a good report? See
21093 http://orgmode.org/manual/Feedback.html#Feedback
21095 Your bug report will be posted to the Org-mode mailing list.
21096 ------------------------------------------------------------------------")
21097 (save-excursion
21098 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21099 (replace-match "\\1Bug: \\3 [\\2]")))))
21102 (defun org-install-agenda-files-menu ()
21103 (let ((bl (buffer-list)))
21104 (save-excursion
21105 (while bl
21106 (set-buffer (pop bl))
21107 (if (derived-mode-p 'org-mode) (setq bl nil)))
21108 (when (derived-mode-p 'org-mode)
21109 (easy-menu-change
21110 '("Org") "File List for Agenda"
21111 (append
21112 (list
21113 ["Edit File List" (org-edit-agenda-file-list) t]
21114 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21115 ["Remove Current File from List" org-remove-file t]
21116 ["Cycle through agenda files" org-cycle-agenda-files t]
21117 ["Occur in all agenda files" org-occur-in-agenda-files t]
21118 "--")
21119 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21121 ;;;; Documentation
21123 (defun org-require-autoloaded-modules ()
21124 (interactive)
21125 (mapc 'require
21126 '(org-agenda org-archive org-attach org-clock org-colview org-id
21127 org-table org-timer)))
21129 ;;;###autoload
21130 (defun org-reload (&optional uncompiled)
21131 "Reload all org lisp files.
21132 With prefix arg UNCOMPILED, load the uncompiled versions."
21133 (interactive "P")
21134 (require 'loadhist)
21135 (let* ((org-dir (org-find-library-dir "org"))
21136 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21137 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21138 (remove-re (mapconcat 'identity
21139 (mapcar (lambda (f) (concat "^" f "$"))
21140 (list (if (featurep 'xemacs)
21141 "org-colview"
21142 "org-colview-xemacs")
21143 "org" "org-loaddefs" "org-version"))
21144 "\\|"))
21145 (feats (delete-dups
21146 (mapcar 'file-name-sans-extension
21147 (mapcar 'file-name-nondirectory
21148 (delq nil
21149 (mapcar 'feature-file
21150 features))))))
21151 (lfeat (append
21152 (sort
21153 (setq feats
21154 (delq nil (mapcar
21155 (lambda (f)
21156 (if (and (string-match feature-re f)
21157 (not (string-match remove-re f)))
21158 f nil))
21159 feats)))
21160 'string-lessp)
21161 (list "org-version" "org")))
21162 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21163 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21164 load-uncore load-misses)
21165 (setq load-misses
21166 (delq 't
21167 (mapcar (lambda (f)
21168 (or (org-load-noerror-mustsuffix (concat org-dir f))
21169 (and (string= org-dir contrib-dir)
21170 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21171 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21172 (add-to-list 'load-uncore f 'append)
21175 lfeat)))
21176 (if load-uncore
21177 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21178 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21179 (if load-misses
21180 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21181 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21182 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21184 ;;;###autoload
21185 (defun org-customize ()
21186 "Call the customize function with org as argument."
21187 (interactive)
21188 (org-load-modules-maybe)
21189 (org-require-autoloaded-modules)
21190 (customize-browse 'org))
21192 (defun org-create-customize-menu ()
21193 "Create a full customization menu for Org-mode, insert it into the menu."
21194 (interactive)
21195 (org-load-modules-maybe)
21196 (org-require-autoloaded-modules)
21197 (if (fboundp 'customize-menu-create)
21198 (progn
21199 (easy-menu-change
21200 '("Org") "Customize"
21201 `(["Browse Org group" org-customize t]
21202 "--"
21203 ,(customize-menu-create 'org)
21204 ["Set" Custom-set t]
21205 ["Save" Custom-save t]
21206 ["Reset to Current" Custom-reset-current t]
21207 ["Reset to Saved" Custom-reset-saved t]
21208 ["Reset to Standard Settings" Custom-reset-standard t]))
21209 (message "\"Org\"-menu now contains full customization menu"))
21210 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21212 ;;;; Miscellaneous stuff
21214 ;;; Generally useful functions
21216 (defun org-get-at-bol (property)
21217 "Get text property PROPERTY at beginning of line."
21218 (get-text-property (point-at-bol) property))
21220 (defun org-find-text-property-in-string (prop s)
21221 "Return the first non-nil value of property PROP in string S."
21222 (or (get-text-property 0 prop s)
21223 (get-text-property (or (next-single-property-change 0 prop s) 0)
21224 prop s)))
21226 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21227 "Display the given MESSAGE as a warning."
21228 (if (fboundp 'display-warning)
21229 (display-warning 'org message
21230 (if (featurep 'xemacs) 'warning :warning))
21231 (let ((buf (get-buffer-create "*Org warnings*")))
21232 (with-current-buffer buf
21233 (goto-char (point-max))
21234 (insert "Warning (Org): " message)
21235 (unless (bolp)
21236 (newline)))
21237 (display-buffer buf)
21238 (sit-for 0))))
21240 (defun org-eval (form)
21241 "Eval FORM and return result."
21242 (condition-case error
21243 (eval form)
21244 (error (format "%%![Error: %s]" error))))
21246 (defun org-in-clocktable-p ()
21247 "Check if the cursor is in a clocktable."
21248 (let ((pos (point)) start)
21249 (save-excursion
21250 (end-of-line 1)
21251 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21252 (setq start (match-beginning 0))
21253 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21254 (>= (match-end 0) pos)
21255 start))))
21257 (defun org-in-commented-line ()
21258 "Is point in a line starting with `#'?"
21259 (equal (char-after (point-at-bol)) ?#))
21261 (defun org-in-indented-comment-line ()
21262 "Is point in a line starting with `#' after some white space?"
21263 (save-excursion
21264 (save-match-data
21265 (goto-char (point-at-bol))
21266 (looking-at "[ \t]*#"))))
21268 (defun org-in-verbatim-emphasis ()
21269 (save-match-data
21270 (and (org-in-regexp org-emph-re 2)
21271 (>= (point) (match-beginning 3))
21272 (<= (point) (match-end 4))
21273 (member (match-string 3) '("=" "~")))))
21275 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21276 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21277 (if (and marker (marker-buffer marker)
21278 (buffer-live-p (marker-buffer marker)))
21279 (progn
21280 (org-pop-to-buffer-same-window (marker-buffer marker))
21281 (if (or (> marker (point-max)) (< marker (point-min)))
21282 (widen))
21283 (goto-char marker)
21284 (org-show-context 'org-goto))
21285 (if bookmark
21286 (bookmark-jump bookmark)
21287 (error "Cannot find location"))))
21289 (defun org-quote-csv-field (s)
21290 "Quote field for inclusion in CSV material."
21291 (if (string-match "[\",]" s)
21292 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21295 (defun org-force-self-insert (N)
21296 "Needed to enforce self-insert under remapping."
21297 (interactive "p")
21298 (self-insert-command N))
21300 (defun org-string-width (s)
21301 "Compute width of string, ignoring invisible characters.
21302 This ignores character with invisibility property `org-link', and also
21303 characters with property `org-cwidth', because these will become invisible
21304 upon the next fontification round."
21305 (let (b l)
21306 (when (or (eq t buffer-invisibility-spec)
21307 (assq 'org-link buffer-invisibility-spec))
21308 (while (setq b (text-property-any 0 (length s)
21309 'invisible 'org-link s))
21310 (setq s (concat (substring s 0 b)
21311 (substring s (or (next-single-property-change
21312 b 'invisible s) (length s)))))))
21313 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21314 (setq s (concat (substring s 0 b)
21315 (substring s (or (next-single-property-change
21316 b 'org-cwidth s) (length s))))))
21317 (setq l (string-width s) b -1)
21318 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21319 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21322 (defun org-shorten-string (s maxlength)
21323 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21324 If the string is shorter or has length MAXLENGTH, just return the
21325 original string. If it is longer, the functions finds a space in the
21326 string, breaks this string off at that locations and adds three dots
21327 as ellipsis. Including the ellipsis, the string will not be longer
21328 than MAXLENGTH. If finding a good breaking point in the string does
21329 not work, the string is just chopped off in the middle of a word
21330 if necessary."
21331 (if (<= (length s) maxlength)
21333 (let* ((n (max (- maxlength 4) 1))
21334 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21335 (if (string-match re s)
21336 (concat (match-string 1 s) "...")
21337 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21339 (defun org-get-indentation (&optional line)
21340 "Get the indentation of the current line, interpreting tabs.
21341 When LINE is given, assume it represents a line and compute its indentation."
21342 (if line
21343 (if (string-match "^ *" (org-remove-tabs line))
21344 (match-end 0))
21345 (save-excursion
21346 (beginning-of-line 1)
21347 (skip-chars-forward " \t")
21348 (current-column))))
21350 (defun org-get-string-indentation (s)
21351 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21352 (let ((n -1) (i 0) (w tab-width) c)
21353 (catch 'exit
21354 (while (< (setq n (1+ n)) (length s))
21355 (setq c (aref s n))
21356 (cond ((= c ?\ ) (setq i (1+ i)))
21357 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21358 (t (throw 'exit t)))))
21361 (defun org-remove-tabs (s &optional width)
21362 "Replace tabulators in S with spaces.
21363 Assumes that s is a single line, starting in column 0."
21364 (setq width (or width tab-width))
21365 (while (string-match "\t" s)
21366 (setq s (replace-match
21367 (make-string
21368 (- (* width (/ (+ (match-beginning 0) width) width))
21369 (match-beginning 0)) ?\ )
21370 t t s)))
21373 (defun org-fix-indentation (line ind)
21374 "Fix indentation in LINE.
21375 IND is a cons cell with target and minimum indentation.
21376 If the current indentation in LINE is smaller than the minimum,
21377 leave it alone. If it is larger than ind, set it to the target."
21378 (let* ((l (org-remove-tabs line))
21379 (i (org-get-indentation l))
21380 (i1 (car ind)) (i2 (cdr ind)))
21381 (if (>= i i2) (setq l (substring line i2)))
21382 (if (> i1 0)
21383 (concat (make-string i1 ?\ ) l)
21384 l)))
21386 (defun org-remove-indentation (code &optional n)
21387 "Remove the maximum common indentation from the lines in CODE.
21388 N may optionally be the number of spaces to remove."
21389 (with-temp-buffer
21390 (insert code)
21391 (org-do-remove-indentation n)
21392 (buffer-string)))
21394 (defun org-do-remove-indentation (&optional n)
21395 "Remove the maximum common indentation from the buffer."
21396 (untabify (point-min) (point-max))
21397 (let ((min 10000) re)
21398 (if n
21399 (setq min n)
21400 (goto-char (point-min))
21401 (while (re-search-forward "^ *[^ \n]" nil t)
21402 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21403 (unless (or (= min 0) (= min 10000))
21404 (setq re (format "^ \\{%d\\}" min))
21405 (goto-char (point-min))
21406 (while (re-search-forward re nil t)
21407 (replace-match "")
21408 (end-of-line 1))
21409 min)))
21411 (defun org-fill-template (template alist)
21412 "Find each %key of ALIST in TEMPLATE and replace it."
21413 (let ((case-fold-search nil)
21414 entry key value)
21415 (setq alist (sort (copy-sequence alist)
21416 (lambda (a b) (< (length (car a)) (length (car b))))))
21417 (while (setq entry (pop alist))
21418 (setq template
21419 (replace-regexp-in-string
21420 (concat "%" (regexp-quote (car entry)))
21421 (or (cdr entry) "") template t t)))
21422 template))
21424 (defun org-base-buffer (buffer)
21425 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21426 (if (not buffer)
21427 buffer
21428 (or (buffer-base-buffer buffer)
21429 buffer)))
21431 (defun org-trim (s)
21432 "Remove whitespace at beginning and end of string."
21433 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21434 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21437 (defun org-wrap (string &optional width lines)
21438 "Wrap string to either a number of lines, or a width in characters.
21439 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21440 that costs. If there is a word longer than WIDTH, the text is actually
21441 wrapped to the length of that word.
21442 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21443 many lines, whatever width that takes.
21444 The return value is a list of lines, without newlines at the end."
21445 (let* ((words (org-split-string string "[ \t\n]+"))
21446 (maxword (apply 'max (mapcar 'org-string-width words)))
21447 w ll)
21448 (cond (width
21449 (org-do-wrap words (max maxword width)))
21450 (lines
21451 (setq w maxword)
21452 (setq ll (org-do-wrap words maxword))
21453 (if (<= (length ll) lines)
21455 (setq ll words)
21456 (while (> (length ll) lines)
21457 (setq w (1+ w))
21458 (setq ll (org-do-wrap words w)))
21459 ll))
21460 (t (error "Cannot wrap this")))))
21462 (defun org-do-wrap (words width)
21463 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21464 (let (lines line)
21465 (while words
21466 (setq line (pop words))
21467 (while (and words (< (+ (length line) (length (car words))) width))
21468 (setq line (concat line " " (pop words))))
21469 (setq lines (push line lines)))
21470 (nreverse lines)))
21472 (defun org-split-string (string &optional separators)
21473 "Splits STRING into substrings at SEPARATORS.
21474 No empty strings are returned if there are matches at the beginning
21475 and end of string."
21476 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21477 (start 0)
21478 notfirst
21479 (list nil))
21480 (while (and (string-match rexp string
21481 (if (and notfirst
21482 (= start (match-beginning 0))
21483 (< start (length string)))
21484 (1+ start) start))
21485 (< (match-beginning 0) (length string)))
21486 (setq notfirst t)
21487 (or (eq (match-beginning 0) 0)
21488 (and (eq (match-beginning 0) (match-end 0))
21489 (eq (match-beginning 0) start))
21490 (setq list
21491 (cons (substring string start (match-beginning 0))
21492 list)))
21493 (setq start (match-end 0)))
21494 (or (eq start (length string))
21495 (setq list
21496 (cons (substring string start)
21497 list)))
21498 (nreverse list)))
21500 (defun org-quote-vert (s)
21501 "Replace \"|\" with \"\\vert\"."
21502 (while (string-match "|" s)
21503 (setq s (replace-match "\\vert" t t s)))
21506 (defun org-uuidgen-p (s)
21507 "Is S an ID created by UUIDGEN?"
21508 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21510 (defun org-in-src-block-p (&optional inside)
21511 "Whether point is in a code source block.
21512 When INSIDE is non-nil, don't consider we are within a src block
21513 when point is at #+BEGIN_SRC or #+END_SRC."
21514 (let ((case-fold-search t) ov)
21515 (or (and (setq ov (overlays-at (point)))
21516 (memq 'org-block-background
21517 (overlay-properties (car ov))))
21518 (and (not inside)
21519 (save-match-data
21520 (save-excursion
21521 (beginning-of-line)
21522 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21524 (defun org-context ()
21525 "Return a list of contexts of the current cursor position.
21526 If several contexts apply, all are returned.
21527 Each context entry is a list with a symbol naming the context, and
21528 two positions indicating start and end of the context. Possible
21529 contexts are:
21531 :headline anywhere in a headline
21532 :headline-stars on the leading stars in a headline
21533 :todo-keyword on a TODO keyword (including DONE) in a headline
21534 :tags on the TAGS in a headline
21535 :priority on the priority cookie in a headline
21536 :item on the first line of a plain list item
21537 :item-bullet on the bullet/number of a plain list item
21538 :checkbox on the checkbox in a plain list item
21539 :table in an org-mode table
21540 :table-special on a special filed in a table
21541 :table-table in a table.el table
21542 :clocktable in a clocktable
21543 :src-block in a source block
21544 :link on a hyperlink
21545 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21546 :target on a <<target>>
21547 :radio-target on a <<<radio-target>>>
21548 :latex-fragment on a LaTeX fragment
21549 :latex-preview on a LaTeX fragment with overlaid preview image
21551 This function expects the position to be visible because it uses font-lock
21552 faces as a help to recognize the following contexts: :table-special, :link,
21553 and :keyword."
21554 (let* ((f (get-text-property (point) 'face))
21555 (faces (if (listp f) f (list f)))
21556 (case-fold-search t)
21557 (p (point)) clist o)
21558 ;; First the large context
21559 (cond
21560 ((org-at-heading-p t)
21561 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21562 (when (progn
21563 (beginning-of-line 1)
21564 (looking-at org-todo-line-tags-regexp))
21565 (push (org-point-in-group p 1 :headline-stars) clist)
21566 (push (org-point-in-group p 2 :todo-keyword) clist)
21567 (push (org-point-in-group p 4 :tags) clist))
21568 (goto-char p)
21569 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21570 (if (looking-at "\\[#[A-Z0-9]\\]")
21571 (push (org-point-in-group p 0 :priority) clist)))
21573 ((org-at-item-p)
21574 (push (org-point-in-group p 2 :item-bullet) clist)
21575 (push (list :item (point-at-bol)
21576 (save-excursion (org-end-of-item) (point)))
21577 clist)
21578 (and (org-at-item-checkbox-p)
21579 (push (org-point-in-group p 0 :checkbox) clist)))
21581 ((org-at-table-p)
21582 (push (list :table (org-table-begin) (org-table-end)) clist)
21583 (if (memq 'org-formula faces)
21584 (push (list :table-special
21585 (previous-single-property-change p 'face)
21586 (next-single-property-change p 'face)) clist)))
21587 ((org-at-table-p 'any)
21588 (push (list :table-table) clist)))
21589 (goto-char p)
21591 (let ((case-fold-search t))
21592 ;; New the "medium" contexts: clocktables, source blocks
21593 (cond ((org-in-clocktable-p)
21594 (push (list :clocktable
21595 (and (or (looking-at "#\\+BEGIN: clocktable")
21596 (search-backward "#+BEGIN: clocktable" nil t))
21597 (match-beginning 0))
21598 (and (re-search-forward "#\\+END:?" nil t)
21599 (match-end 0))) clist))
21600 ((org-in-src-block-p)
21601 (push (list :src-block
21602 (and (or (looking-at "#\\+BEGIN_SRC")
21603 (search-backward "#+BEGIN_SRC" nil t))
21604 (match-beginning 0))
21605 (and (search-forward "#+END_SRC" nil t)
21606 (match-beginning 0))) clist))))
21607 (goto-char p)
21609 ;; Now the small context
21610 (cond
21611 ((org-at-timestamp-p)
21612 (push (org-point-in-group p 0 :timestamp) clist))
21613 ((memq 'org-link faces)
21614 (push (list :link
21615 (previous-single-property-change p 'face)
21616 (next-single-property-change p 'face)) clist))
21617 ((memq 'org-special-keyword faces)
21618 (push (list :keyword
21619 (previous-single-property-change p 'face)
21620 (next-single-property-change p 'face)) clist))
21621 ((org-at-target-p)
21622 (push (org-point-in-group p 0 :target) clist)
21623 (goto-char (1- (match-beginning 0)))
21624 (if (looking-at org-radio-target-regexp)
21625 (push (org-point-in-group p 0 :radio-target) clist))
21626 (goto-char p))
21627 ((setq o (car (delq nil
21628 (mapcar
21629 (lambda (x)
21630 (if (memq x org-latex-fragment-image-overlays) x))
21631 (overlays-at (point))))))
21632 (push (list :latex-fragment
21633 (overlay-start o) (overlay-end o)) clist)
21634 (push (list :latex-preview
21635 (overlay-start o) (overlay-end o)) clist))
21636 ((org-inside-LaTeX-fragment-p)
21637 ;; FIXME: positions wrong.
21638 (push (list :latex-fragment (point) (point)) clist)))
21640 (setq clist (nreverse (delq nil clist)))
21641 clist))
21643 ;; FIXME: Compare with at-regexp-p Do we need both?
21644 (defun org-in-regexp (re &optional nlines visually)
21645 "Check if point is inside a match of regexp.
21646 Normally only the current line is checked, but you can include NLINES extra
21647 lines both before and after point into the search.
21648 If VISUALLY is set, require that the cursor is not after the match but
21649 really on, so that the block visually is on the match."
21650 (catch 'exit
21651 (let ((pos (point))
21652 (eol (point-at-eol (+ 1 (or nlines 0))))
21653 (inc (if visually 1 0)))
21654 (save-excursion
21655 (beginning-of-line (- 1 (or nlines 0)))
21656 (while (re-search-forward re eol t)
21657 (if (and (<= (match-beginning 0) pos)
21658 (>= (+ inc (match-end 0)) pos))
21659 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21661 (defun org-at-regexp-p (regexp)
21662 "Is point inside a match of REGEXP in the current line?"
21663 (catch 'exit
21664 (save-excursion
21665 (let ((pos (point)) (end (point-at-eol)))
21666 (beginning-of-line 1)
21667 (while (re-search-forward regexp end t)
21668 (if (and (<= (match-beginning 0) pos)
21669 (>= (match-end 0) pos))
21670 (throw 'exit t)))
21671 nil))))
21673 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21674 "Non-nil when point is between matches of START-RE and END-RE.
21676 Also return a non-nil value when point is on one of the matches.
21678 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21679 buffer positions. Default values are the positions of headlines
21680 surrounding the point.
21682 The functions returns a cons cell whose car (resp. cdr) is the
21683 position before START-RE (resp. after END-RE)."
21684 (save-match-data
21685 (let ((pos (point))
21686 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21687 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21688 beg end)
21689 (save-excursion
21690 ;; Point is on a block when on START-RE or if START-RE can be
21691 ;; found before it...
21692 (and (or (org-at-regexp-p start-re)
21693 (re-search-backward start-re limit-up t))
21694 (setq beg (match-beginning 0))
21695 ;; ... and END-RE after it...
21696 (goto-char (match-end 0))
21697 (re-search-forward end-re limit-down t)
21698 (> (setq end (match-end 0)) pos)
21699 ;; ... without another START-RE in-between.
21700 (goto-char (match-beginning 0))
21701 (not (re-search-backward start-re (1+ beg) t))
21702 ;; Return value.
21703 (cons beg end))))))
21705 (defun org-in-block-p (names)
21706 "Non-nil when point belongs to a block whose name belongs to NAMES.
21708 NAMES is a list of strings containing names of blocks.
21710 Return first block name matched, or nil. Beware that in case of
21711 nested blocks, the returned name may not belong to the closest
21712 block from point."
21713 (save-match-data
21714 (catch 'exit
21715 (let ((case-fold-search t)
21716 (lim-up (save-excursion (outline-previous-heading)))
21717 (lim-down (save-excursion (outline-next-heading))))
21718 (mapc (lambda (name)
21719 (let ((n (regexp-quote name)))
21720 (when (org-between-regexps-p
21721 (concat "^[ \t]*#\\+begin_" n)
21722 (concat "^[ \t]*#\\+end_" n)
21723 lim-up lim-down)
21724 (throw 'exit n))))
21725 names))
21726 nil)))
21728 (defun org-in-drawer-p ()
21729 "Is point within a drawer?"
21730 (save-match-data
21731 (let ((case-fold-search t)
21732 (lim-up (save-excursion (outline-previous-heading)))
21733 (lim-down (save-excursion (outline-next-heading))))
21734 (org-between-regexps-p
21735 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21736 "^[ \t]*:end:.*$"
21737 lim-up lim-down))))
21739 (defun org-occur-in-agenda-files (regexp &optional nlines)
21740 "Call `multi-occur' with buffers for all agenda files."
21741 (interactive "sOrg-files matching: \np")
21742 (let* ((files (org-agenda-files))
21743 (tnames (mapcar 'file-truename files))
21744 (extra org-agenda-text-search-extra-files)
21746 (when (eq (car extra) 'agenda-archives)
21747 (setq extra (cdr extra))
21748 (setq files (org-add-archive-files files)))
21749 (while (setq f (pop extra))
21750 (unless (member (file-truename f) tnames)
21751 (add-to-list 'files f 'append)
21752 (add-to-list 'tnames (file-truename f) 'append)))
21753 (multi-occur
21754 (mapcar (lambda (x)
21755 (with-current-buffer
21756 (or (get-file-buffer x) (find-file-noselect x))
21757 (widen)
21758 (current-buffer)))
21759 files)
21760 regexp)))
21762 (if (boundp 'occur-mode-find-occurrence-hook)
21763 ;; Emacs 23
21764 (add-hook 'occur-mode-find-occurrence-hook
21765 (lambda ()
21766 (when (derived-mode-p 'org-mode)
21767 (org-reveal))))
21768 ;; Emacs 22
21769 (defadvice occur-mode-goto-occurrence
21770 (after org-occur-reveal activate)
21771 (and (derived-mode-p 'org-mode) (org-reveal)))
21772 (defadvice occur-mode-goto-occurrence-other-window
21773 (after org-occur-reveal activate)
21774 (and (derived-mode-p 'org-mode) (org-reveal)))
21775 (defadvice occur-mode-display-occurrence
21776 (after org-occur-reveal activate)
21777 (when (derived-mode-p 'org-mode)
21778 (let ((pos (occur-mode-find-occurrence)))
21779 (with-current-buffer (marker-buffer pos)
21780 (save-excursion
21781 (goto-char pos)
21782 (org-reveal)))))))
21784 (defun org-occur-link-in-agenda-files ()
21785 "Create a link and search for it in the agendas.
21786 The link is not stored in `org-stored-links', it is just created
21787 for the search purpose."
21788 (interactive)
21789 (let ((link (condition-case nil
21790 (org-store-link nil)
21791 (error "Unable to create a link to here"))))
21792 (org-occur-in-agenda-files (regexp-quote link))))
21794 (defun org-reverse-string (string)
21795 "Return the reverse of STRING."
21796 (apply 'string (reverse (string-to-list string))))
21798 (defsubst org-uniquify (list)
21799 "Non-destructively remove duplicate elements from LIST."
21800 (let ((res (copy-sequence list))) (delete-dups res)))
21802 (defun org-uniquify-alist (alist)
21803 "Merge elements of ALIST with the same key.
21805 For example, in this alist:
21807 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21808 => '((a 1 3) (b 2))
21810 merge (a 1) and (a 3) into (a 1 3).
21812 The function returns the new ALIST."
21813 (let (rtn)
21814 (mapc
21815 (lambda (e)
21816 (let (n)
21817 (if (not (assoc (car e) rtn))
21818 (push e rtn)
21819 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21820 (setq rtn (assq-delete-all (car e) rtn))
21821 (push n rtn))))
21822 alist)
21823 rtn))
21825 (defun org-delete-all (elts list)
21826 "Remove all elements in ELTS from LIST."
21827 (while elts
21828 (setq list (delete (pop elts) list)))
21829 list)
21831 (defun org-count (cl-item cl-seq)
21832 "Count the number of occurrences of ITEM in SEQ.
21833 Taken from `count' in cl-seq.el with all keyword arguments removed."
21834 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21835 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21836 (while (< cl-start cl-end)
21837 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21838 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21839 (setq cl-start (1+ cl-start)))
21840 cl-count))
21842 (defun org-remove-if (predicate seq)
21843 "Remove everything from SEQ that fulfills PREDICATE."
21844 (let (res e)
21845 (while seq
21846 (setq e (pop seq))
21847 (if (not (funcall predicate e)) (push e res)))
21848 (nreverse res)))
21850 (defun org-remove-if-not (predicate seq)
21851 "Remove everything from SEQ that does not fulfill PREDICATE."
21852 (let (res e)
21853 (while seq
21854 (setq e (pop seq))
21855 (if (funcall predicate e) (push e res)))
21856 (nreverse res)))
21858 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21859 "Reduce two-argument FUNCTION across SEQ.
21860 Taken from `reduce' in cl-seq.el with all keyword arguments but
21861 \":initial-value\" removed."
21862 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21863 (cadr (memq :initial-value cl-keys)))
21864 (cl-seq (pop cl-seq))
21865 (t (funcall cl-func)))))
21866 (while cl-seq
21867 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21868 cl-accum))
21870 (defun org-every (pred seq)
21871 "Return true if PREDICATE is true of every element of SEQ.
21872 Adapted from `every' in cl.el."
21873 (catch 'org-every
21874 (mapc (lambda (e) (unless (funcall pred e) (throw 'org-every nil))) seq)
21877 (defun org-some (pred seq)
21878 "Return true if PREDICATE is true of any element of SEQ.
21879 Adapted from `some' in cl.el."
21880 (catch 'org-some
21881 (mapc (lambda (e) (when (funcall pred e) (throw 'org-some t))) seq)
21882 nil))
21884 (defun org-back-over-empty-lines ()
21885 "Move backwards over whitespace, to the beginning of the first empty line.
21886 Returns the number of empty lines passed."
21887 (let ((pos (point)))
21888 (if (cdr (assoc 'heading org-blank-before-new-entry))
21889 (skip-chars-backward " \t\n\r")
21890 (unless (eobp)
21891 (forward-line -1)))
21892 (beginning-of-line 2)
21893 (goto-char (min (point) pos))
21894 (count-lines (point) pos)))
21896 (defun org-skip-whitespace ()
21897 (skip-chars-forward " \t\n\r"))
21899 (defun org-point-in-group (point group &optional context)
21900 "Check if POINT is in match-group GROUP.
21901 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21902 match. If the match group does not exist or point is not inside it,
21903 return nil."
21904 (and (match-beginning group)
21905 (>= point (match-beginning group))
21906 (<= point (match-end group))
21907 (if context
21908 (list context (match-beginning group) (match-end group))
21909 t)))
21911 (defun org-switch-to-buffer-other-window (&rest args)
21912 "Switch to buffer in a second window on the current frame.
21913 In particular, do not allow pop-up frames.
21914 Returns the newly created buffer."
21915 (org-no-popups
21916 (apply 'switch-to-buffer-other-window args)))
21918 (defun org-combine-plists (&rest plists)
21919 "Create a single property list from all plists in PLISTS.
21920 The process starts by copying the first list, and then setting properties
21921 from the other lists. Settings in the last list are the most significant
21922 ones and overrule settings in the other lists."
21923 (let ((rtn (copy-sequence (pop plists)))
21924 p v ls)
21925 (while plists
21926 (setq ls (pop plists))
21927 (while ls
21928 (setq p (pop ls) v (pop ls))
21929 (setq rtn (plist-put rtn p v))))
21930 rtn))
21932 (defun org-replace-escapes (string table)
21933 "Replace %-escapes in STRING with values in TABLE.
21934 TABLE is an association list with keys like \"%a\" and string values.
21935 The sequences in STRING may contain normal field width and padding information,
21936 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21937 so values can contain further %-escapes if they are define later in TABLE."
21938 (let ((tbl (copy-alist table))
21939 (case-fold-search nil)
21940 (pchg 0)
21941 e re rpl)
21942 (while (setq e (pop tbl))
21943 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21944 (when (and (cdr e) (string-match re (cdr e)))
21945 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21946 (safe "SREF"))
21947 (add-text-properties 0 3 (list 'sref sref) safe)
21948 (setcdr e (replace-match safe t t (cdr e)))))
21949 (while (string-match re string)
21950 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21951 (cdr e)))
21952 (setq string (replace-match rpl t t string))))
21953 (while (setq pchg (next-property-change pchg string))
21954 (let ((sref (get-text-property pchg 'sref string)))
21955 (when (and sref (string-match "SREF" string pchg))
21956 (setq string (replace-match sref t t string)))))
21957 string))
21959 (defun org-sublist (list start end)
21960 "Return a section of LIST, from START to END.
21961 Counting starts at 1."
21962 (let (rtn (c start))
21963 (setq list (nthcdr (1- start) list))
21964 (while (and list (<= c end))
21965 (push (pop list) rtn)
21966 (setq c (1+ c)))
21967 (nreverse rtn)))
21969 (defun org-find-base-buffer-visiting (file)
21970 "Like `find-buffer-visiting' but always return the base buffer and
21971 not an indirect buffer."
21972 (let ((buf (or (get-file-buffer file)
21973 (find-buffer-visiting file))))
21974 (if buf
21975 (or (buffer-base-buffer buf) buf)
21976 nil)))
21978 (defun org-image-file-name-regexp (&optional extensions)
21979 "Return regexp matching the file names of images.
21980 If EXTENSIONS is given, only match these."
21981 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21982 (image-file-name-regexp)
21983 (let ((image-file-name-extensions
21984 (or extensions
21985 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21986 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21987 (concat "\\."
21988 (regexp-opt (nconc (mapcar 'upcase
21989 image-file-name-extensions)
21990 image-file-name-extensions)
21992 "\\'"))))
21994 (defun org-file-image-p (file &optional extensions)
21995 "Return non-nil if FILE is an image."
21996 (save-match-data
21997 (string-match (org-image-file-name-regexp extensions) file)))
21999 (defun org-get-cursor-date (&optional with-time)
22000 "Return the date at cursor in as a time.
22001 This works in the calendar and in the agenda, anywhere else it just
22002 returns the current time.
22003 If WITH-TIME is non-nil, returns the time of the event at point (in
22004 the agenda) or the current time of the day."
22005 (let (date day defd tp tm hod mod)
22006 (when with-time
22007 (setq tp (get-text-property (point) 'time))
22008 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22009 (setq hod (string-to-number (match-string 1 tp))
22010 mod (string-to-number (match-string 2 tp))))
22011 (or tp (setq hod (nth 2 (decode-time (current-time)))
22012 mod (nth 1 (decode-time (current-time))))))
22013 (cond
22014 ((eq major-mode 'calendar-mode)
22015 (setq date (calendar-cursor-to-date)
22016 defd (encode-time 0 (or mod 0) (or hod 0)
22017 (nth 1 date) (nth 0 date) (nth 2 date))))
22018 ((eq major-mode 'org-agenda-mode)
22019 (setq day (get-text-property (point) 'day))
22020 (if day
22021 (setq date (calendar-gregorian-from-absolute day)
22022 defd (encode-time 0 (or mod 0) (or hod 0)
22023 (nth 1 date) (nth 0 date) (nth 2 date))))))
22024 (or defd (current-time))))
22026 (defun org-mark-subtree (&optional up)
22027 "Mark the current subtree.
22028 This puts point at the start of the current subtree, and mark at
22029 the end. If a numeric prefix UP is given, move up into the
22030 hierarchy of headlines by UP levels before marking the subtree."
22031 (interactive "P")
22032 (org-with-limited-levels
22033 (cond ((org-at-heading-p) (beginning-of-line))
22034 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22035 (t (outline-previous-visible-heading 1))))
22036 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
22037 (if (org-called-interactively-p 'any)
22038 (call-interactively 'org-mark-element)
22039 (org-mark-element)))
22042 ;;; Indentation
22044 (defun org-indent-line ()
22045 "Indent line depending on context."
22046 (interactive)
22047 (let* ((pos (point))
22048 (itemp (org-at-item-p))
22049 (case-fold-search t)
22050 (org-drawer-regexp (or org-drawer-regexp "\000"))
22051 (inline-task-p (and (featurep 'org-inlinetask)
22052 (org-inlinetask-in-task-p)))
22053 (inline-re (and inline-task-p
22054 (org-inlinetask-outline-regexp)))
22055 column)
22056 (if (and orgstruct-is-++ (eq pos (point)))
22057 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
22058 (indent-according-to-mode))
22059 (beginning-of-line 1)
22060 (cond
22061 ;; Headings
22062 ((looking-at org-outline-regexp) (setq column 0))
22063 ;; Footnote definition
22064 ((looking-at org-footnote-definition-re) (setq column 0))
22065 ;; Literal examples
22066 ((looking-at "[ \t]*:\\( \\|$\\)")
22067 (setq column (org-get-indentation))) ; do nothing
22068 ;; Lists
22069 ((ignore-errors (goto-char (org-in-item-p)))
22070 (setq column (if itemp
22071 (org-get-indentation)
22072 (org-list-item-body-column (point))))
22073 (goto-char pos))
22074 ;; Drawers
22075 ((and (looking-at "[ \t]*:END:")
22076 (save-excursion (re-search-backward org-drawer-regexp nil t)))
22077 (save-excursion
22078 (goto-char (1- (match-beginning 1)))
22079 (setq column (current-column))))
22080 ;; Special blocks
22081 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
22082 (save-excursion
22083 (re-search-backward
22084 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
22085 (setq column (org-get-indentation (match-string 0))))
22086 ((and (not (looking-at "[ \t]*#\\+begin_"))
22087 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
22088 (save-excursion
22089 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
22090 (setq column
22091 (cond ((equal (downcase (match-string 1)) "src")
22092 ;; src blocks: let `org-edit-src-exit' handle them
22093 (org-get-indentation))
22094 ((equal (downcase (match-string 1)) "example")
22095 (max (org-get-indentation)
22096 (org-get-indentation (match-string 0))))
22098 (org-get-indentation (match-string 0))))))
22099 ;; This line has nothing special, look at the previous relevant
22100 ;; line to compute indentation
22102 (beginning-of-line 0)
22103 (while (and (not (bobp))
22104 (not (looking-at org-table-line-regexp))
22105 (not (looking-at org-drawer-regexp))
22106 ;; When point started in an inline task, do not move
22107 ;; above task starting line.
22108 (not (and inline-task-p (looking-at inline-re)))
22109 ;; Skip drawers, blocks, empty lines, verbatim,
22110 ;; comments, tables, footnotes definitions, lists,
22111 ;; inline tasks.
22112 (or (and (looking-at "[ \t]*:END:")
22113 (re-search-backward org-drawer-regexp nil t))
22114 (and (looking-at "[ \t]*#\\+end_")
22115 (re-search-backward "[ \t]*#\\+begin_"nil t))
22116 (looking-at "[ \t]*[\n:#|]")
22117 (looking-at org-footnote-definition-re)
22118 (and (not inline-task-p)
22119 (featurep 'org-inlinetask)
22120 (org-inlinetask-in-task-p)
22121 (or (org-inlinetask-goto-beginning) t))))
22122 (beginning-of-line 0))
22123 (cond
22124 ;; There was a list item above.
22125 ((ignore-errors (goto-char (org-in-item-p)))
22126 (goto-char (org-list-get-top-point (org-list-struct)))
22127 (setq column (org-get-indentation)))
22128 ;; There was an heading above.
22129 ((looking-at "\\*+[ \t]+")
22130 (if (not org-adapt-indentation)
22131 (setq column 0)
22132 (goto-char (match-end 0))
22133 (setq column (current-column))))
22134 ;; A drawer had started and is unfinished
22135 ((looking-at org-drawer-regexp)
22136 (goto-char (1- (match-beginning 1)))
22137 (setq column (current-column)))
22138 ;; Else, nothing noticeable found: get indentation and go on.
22139 (t (setq column (org-get-indentation))))))
22140 ;; Now apply indentation and move cursor accordingly
22141 (goto-char pos)
22142 (if (<= (current-column) (current-indentation))
22143 (org-indent-line-to column)
22144 (save-excursion (org-indent-line-to column)))
22145 ;; Special polishing for properties, see `org-property-format'
22146 (setq column (current-column))
22147 (beginning-of-line 1)
22148 (if (looking-at org-property-re)
22149 (replace-match (concat (match-string 4)
22150 (format org-property-format
22151 (match-string 1) (match-string 3)))
22152 t t))
22153 (org-move-to-column column))))
22155 (defun org-indent-drawer ()
22156 "Indent the drawer at point."
22157 (interactive)
22158 (let ((p (point))
22159 (e (and (save-excursion (re-search-forward ":END:" nil t))
22160 (match-end 0)))
22161 (folded
22162 (save-excursion
22163 (end-of-line)
22164 (when (overlays-at (point))
22165 (member 'invisible (overlay-properties
22166 (car (overlays-at (point)))))))))
22167 (when folded (org-cycle))
22168 (indent-for-tab-command)
22169 (while (and (move-beginning-of-line 2) (< (point) e))
22170 (indent-for-tab-command))
22171 (goto-char p)
22172 (when folded (org-cycle)))
22173 (message "Drawer at point indented"))
22175 (defun org-indent-block ()
22176 "Indent the block at point."
22177 (interactive)
22178 (let ((p (point))
22179 (case-fold-search t)
22180 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22181 (match-end 0)))
22182 (folded
22183 (save-excursion
22184 (end-of-line)
22185 (when (overlays-at (point))
22186 (member 'invisible (overlay-properties
22187 (car (overlays-at (point)))))))))
22188 (when folded (org-cycle))
22189 (indent-for-tab-command)
22190 (while (and (move-beginning-of-line 2) (< (point) e))
22191 (indent-for-tab-command))
22192 (goto-char p)
22193 (when folded (org-cycle)))
22194 (message "Block at point indented"))
22196 (defun org-indent-region (start end)
22197 "Indent region."
22198 (interactive "r")
22199 (save-excursion
22200 (let ((line-end (org-current-line end)))
22201 (goto-char start)
22202 (while (< (org-current-line) line-end)
22203 (cond ((org-in-src-block-p t) (org-src-native-tab-command-maybe))
22204 (t (call-interactively 'org-indent-line)))
22205 (move-beginning-of-line 2)))))
22208 ;;; Filling
22210 ;; We use our own fill-paragraph and auto-fill functions.
22212 ;; `org-fill-paragraph' relies on adaptive filling and context
22213 ;; checking. Appropriate `fill-prefix' is computed with
22214 ;; `org-adaptive-fill-function'.
22216 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22217 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22218 ;; `org-adaptive-fill-function' value. Internally,
22219 ;; `org-comment-line-break-function' breaks the line.
22221 ;; `org-setup-filling' installs filling and auto-filling related
22222 ;; variables during `org-mode' initialization.
22224 (defvar org-element-paragraph-separate) ; org-element.el
22225 (defun org-setup-filling ()
22226 (require 'org-element)
22227 ;; Prevent auto-fill from inserting unwanted new items.
22228 (when (boundp 'fill-nobreak-predicate)
22229 (org-set-local
22230 'fill-nobreak-predicate
22231 (org-uniquify
22232 (append fill-nobreak-predicate
22233 '(org-fill-line-break-nobreak-p
22234 org-fill-paragraph-with-timestamp-nobreak-p)))))
22235 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22236 (org-set-local 'paragraph-start paragraph-ending)
22237 (org-set-local 'paragraph-separate paragraph-ending))
22238 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22239 (org-set-local 'auto-fill-inhibit-regexp nil)
22240 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22241 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22242 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22244 (defun org-fill-line-break-nobreak-p ()
22245 "Non-nil when a new line at point would create an Org line break."
22246 (save-excursion
22247 (skip-chars-backward "[ \t]")
22248 (skip-chars-backward "\\\\")
22249 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22251 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22252 "Non-nil when a new line at point would split a timestamp."
22253 (and (org-at-timestamp-p t)
22254 (not (looking-at org-ts-regexp-both))))
22256 (declare-function message-in-body-p "message" ())
22257 (defvar orgtbl-line-start-regexp) ; From org-table.el
22258 (defun org-adaptive-fill-function ()
22259 "Compute a fill prefix for the current line.
22260 Return fill prefix, as a string, or nil if current line isn't
22261 meant to be filled. For convenience, if `adaptive-fill-regexp'
22262 matches in paragraphs or comments, use it."
22263 (catch 'exit
22264 (when (derived-mode-p 'message-mode)
22265 (save-excursion
22266 (beginning-of-line)
22267 (cond ((or (not (message-in-body-p))
22268 (looking-at orgtbl-line-start-regexp))
22269 (throw 'exit nil))
22270 ((looking-at message-cite-prefix-regexp)
22271 (throw 'exit (match-string-no-properties 0)))
22272 ((looking-at org-outline-regexp)
22273 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22274 (org-with-wide-buffer
22275 (let* ((p (line-beginning-position))
22276 (element (save-excursion
22277 (beginning-of-line)
22278 (or (ignore-errors (org-element-at-point))
22279 (user-error "An element cannot be parsed line %d"
22280 (line-number-at-pos (point))))))
22281 (type (org-element-type element))
22282 (post-affiliated (org-element-property :post-affiliated element)))
22283 (unless (and post-affiliated (< p post-affiliated))
22284 (case type
22285 (comment
22286 (save-excursion
22287 (beginning-of-line)
22288 (looking-at "[ \t]*")
22289 (concat (match-string 0) "# ")))
22290 (footnote-definition "")
22291 ((item plain-list)
22292 (make-string (org-list-item-body-column
22293 (or post-affiliated
22294 (org-element-property :begin element)))
22295 ? ))
22296 (paragraph
22297 ;; Fill prefix is usually the same as the current line,
22298 ;; unless the paragraph is at the beginning of an item.
22299 (let ((parent (org-element-property :parent element)))
22300 (save-excursion
22301 (beginning-of-line)
22302 (cond ((eq (org-element-type parent) 'item)
22303 (make-string (org-list-item-body-column
22304 (org-element-property :begin parent))
22305 ? ))
22306 ((and adaptive-fill-regexp
22307 ;; Locally disable
22308 ;; `adaptive-fill-function' to let
22309 ;; `fill-context-prefix' handle
22310 ;; `adaptive-fill-regexp' variable.
22311 (let (adaptive-fill-function)
22312 (fill-context-prefix
22313 post-affiliated
22314 (org-element-property :end element)))))
22315 ((looking-at "[ \t]+") (match-string 0))
22316 (t "")))))
22317 (comment-block
22318 ;; Only fill contents if P is within block boundaries.
22319 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22320 (forward-line)
22321 (point)))
22322 (cend (save-excursion
22323 (goto-char (org-element-property :end element))
22324 (skip-chars-backward " \r\t\n")
22325 (line-beginning-position))))
22326 (when (and (>= p cbeg) (< p cend))
22327 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22328 (match-string 0)
22329 ""))))))))))
22331 (declare-function message-goto-body "message" ())
22332 (defvar message-cite-prefix-regexp) ; From message.el
22333 (defun org-fill-paragraph (&optional justify)
22334 "Fill element at point, when applicable.
22336 This function only applies to comment blocks, comments, example
22337 blocks and paragraphs. Also, as a special case, re-align table
22338 when point is at one.
22340 If JUSTIFY is non-nil (interactively, with prefix argument),
22341 justify as well. If `sentence-end-double-space' is non-nil, then
22342 period followed by one space does not end a sentence, so don't
22343 break a line there. The variable `fill-column' controls the
22344 width for filling.
22346 For convenience, when point is at a plain list, an item or
22347 a footnote definition, try to fill the first paragraph within."
22348 (interactive)
22349 (if (and (derived-mode-p 'message-mode)
22350 (or (not (message-in-body-p))
22351 (save-excursion (move-beginning-of-line 1)
22352 (looking-at message-cite-prefix-regexp))))
22353 ;; First ensure filling is correct in message-mode.
22354 (let ((fill-paragraph-function
22355 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22356 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22357 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22358 (paragraph-separate
22359 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22360 (fill-paragraph nil))
22361 (with-syntax-table org-mode-transpose-word-syntax-table
22362 ;; Move to end of line in order to get the first paragraph
22363 ;; within a plain list or a footnote definition.
22364 (let ((element (save-excursion
22365 (end-of-line)
22366 (or (ignore-errors (org-element-at-point))
22367 (user-error "An element cannot be parsed line %d"
22368 (line-number-at-pos (point)))))))
22369 ;; First check if point is in a blank line at the beginning of
22370 ;; the buffer. In that case, ignore filling.
22371 (case (org-element-type element)
22372 ;; Use major mode filling function is src blocks.
22373 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22374 ;; Align Org tables, leave table.el tables as-is.
22375 (table-row (org-table-align) t)
22376 (table
22377 (when (eq (org-element-property :type element) 'org)
22378 (save-excursion
22379 (goto-char (org-element-property :post-affiliated element))
22380 (org-table-align)))
22382 (paragraph
22383 ;; Paragraphs may contain `line-break' type objects.
22384 (let ((beg (max (point-min)
22385 (org-element-property :contents-begin element)))
22386 (end (min (point-max)
22387 (org-element-property :contents-end element))))
22388 ;; Do nothing if point is at an affiliated keyword.
22389 (if (< (line-end-position) beg) t
22390 (when (derived-mode-p 'message-mode)
22391 ;; In `message-mode', do not fill following citation
22392 ;; in current paragraph nor text before message body.
22393 (let ((body-start (save-excursion (message-goto-body))))
22394 (when body-start (setq beg (max body-start beg))))
22395 (when (save-excursion
22396 (re-search-forward
22397 (concat "^" message-cite-prefix-regexp) end t))
22398 (setq end (match-beginning 0))))
22399 ;; Fill paragraph, taking line breaks into account.
22400 ;; For that, slice the paragraph using line breaks as
22401 ;; separators, and fill the parts in reverse order to
22402 ;; avoid messing with markers.
22403 (save-excursion
22404 (goto-char end)
22405 (mapc
22406 (lambda (pos)
22407 (fill-region-as-paragraph pos (point) justify)
22408 (goto-char pos))
22409 ;; Find the list of ending positions for line breaks
22410 ;; in the current paragraph. Add paragraph
22411 ;; beginning to include first slice.
22412 (nreverse
22413 (cons beg
22414 (org-element-map
22415 (org-element--parse-objects
22416 beg end nil (org-element-restriction 'paragraph))
22417 'line-break
22418 (lambda (lb) (org-element-property :end lb)))))))
22419 t)))
22420 ;; Contents of `comment-block' type elements should be
22421 ;; filled as plain text, but only if point is within block
22422 ;; markers.
22423 (comment-block
22424 (let* ((case-fold-search t)
22425 (beg (save-excursion
22426 (goto-char (org-element-property :begin element))
22427 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22428 (forward-line)
22429 (point)))
22430 (end (save-excursion
22431 (goto-char (org-element-property :end element))
22432 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22433 (line-beginning-position))))
22434 (if (or (< (point) beg) (> (point) end)) t
22435 (fill-region-as-paragraph
22436 (save-excursion (end-of-line)
22437 (re-search-backward "^[ \t]*$" beg 'move)
22438 (line-beginning-position))
22439 (save-excursion (beginning-of-line)
22440 (re-search-forward "^[ \t]*$" end 'move)
22441 (line-beginning-position))
22442 justify))))
22443 ;; Fill comments.
22444 (comment
22445 (let ((begin (org-element-property :post-affiliated element))
22446 (end (org-element-property :end element)))
22447 (when (and (>= (point) begin) (<= (point) end))
22448 (let ((begin (save-excursion
22449 (end-of-line)
22450 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22451 (progn (forward-line) (point))
22452 begin)))
22453 (end (save-excursion
22454 (end-of-line)
22455 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22456 (1- (line-beginning-position))
22457 (skip-chars-backward " \r\t\n")
22458 (line-end-position)))))
22459 ;; Do not fill comments when at a blank line.
22460 (when (> end begin)
22461 (let ((fill-prefix
22462 (save-excursion
22463 (beginning-of-line)
22464 (looking-at "[ \t]*#")
22465 (let ((comment-prefix (match-string 0)))
22466 (goto-char (match-end 0))
22467 (if (looking-at adaptive-fill-regexp)
22468 (concat comment-prefix (match-string 0))
22469 (concat comment-prefix " "))))))
22470 (save-excursion
22471 (fill-region-as-paragraph begin end justify))))))
22473 ;; Ignore every other element.
22474 (otherwise t))))))
22476 (defun org-auto-fill-function ()
22477 "Auto-fill function."
22478 ;; Check if auto-filling is meaningful.
22479 (let ((fc (current-fill-column)))
22480 (when (and fc (> (current-column) fc))
22481 (let* ((fill-prefix (org-adaptive-fill-function))
22482 ;; Enforce empty fill prefix, if required. Otherwise, it
22483 ;; will be computed again.
22484 (adaptive-fill-mode (not (equal fill-prefix ""))))
22485 (when fill-prefix (do-auto-fill))))))
22487 (defun org-comment-line-break-function (&optional soft)
22488 "Break line at point and indent, continuing comment if within one.
22489 The inserted newline is marked hard if variable
22490 `use-hard-newlines' is true, unless optional argument SOFT is
22491 non-nil."
22492 (if soft (insert-and-inherit ?\n) (newline 1))
22493 (save-excursion (forward-char -1) (delete-horizontal-space))
22494 (delete-horizontal-space)
22495 (indent-to-left-margin)
22496 (insert-before-markers-and-inherit fill-prefix))
22499 ;;; Comments
22501 ;; Org comments syntax is quite complex. It requires the entire line
22502 ;; to be just a comment. Also, even with the right syntax at the
22503 ;; beginning of line, some some elements (i.e. verse-block or
22504 ;; example-block) don't accept comments. Usual Emacs comment commands
22505 ;; cannot cope with those requirements. Therefore, Org replaces them.
22507 ;; Org still relies on `comment-dwim', but cannot trust
22508 ;; `comment-only-p'. So, `comment-region-function' and
22509 ;; `uncomment-region-function' both point
22510 ;; to`org-comment-or-uncomment-region'. Eventually,
22511 ;; `org-insert-comment' takes care of insertion of comments at the
22512 ;; beginning of line.
22514 ;; `org-setup-comments-handling' install comments related variables
22515 ;; during `org-mode' initialization.
22517 (defun org-setup-comments-handling ()
22518 (interactive)
22519 (org-set-local 'comment-use-syntax nil)
22520 (org-set-local 'comment-start "# ")
22521 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22522 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22523 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22524 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22526 (defun org-insert-comment ()
22527 "Insert an empty comment above current line.
22528 If the line is empty, insert comment at its beginning."
22529 (beginning-of-line)
22530 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22531 (org-indent-line)
22532 (insert "# "))
22534 (defvar comment-empty-lines) ; From newcomment.el.
22535 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22536 "Comment or uncomment each non-blank line in the region.
22537 Uncomment each non-blank line between BEG and END if it only
22538 contains commented lines. Otherwise, comment them."
22539 (save-restriction
22540 ;; Restrict region
22541 (narrow-to-region (save-excursion (goto-char beg)
22542 (skip-chars-forward " \r\t\n" end)
22543 (line-beginning-position))
22544 (save-excursion (goto-char end)
22545 (skip-chars-backward " \r\t\n" beg)
22546 (line-end-position)))
22547 (let ((uncommentp
22548 ;; UNCOMMENTP is non-nil when every non blank line between
22549 ;; BEG and END is a comment.
22550 (save-excursion
22551 (goto-char (point-min))
22552 (while (and (not (eobp))
22553 (let ((element (org-element-at-point)))
22554 (and (eq (org-element-type element) 'comment)
22555 (goto-char (min (point-max)
22556 (org-element-property
22557 :end element)))))))
22558 (eobp))))
22559 (if uncommentp
22560 ;; Only blank lines and comments in region: uncomment it.
22561 (save-excursion
22562 (goto-char (point-min))
22563 (while (not (eobp))
22564 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22565 (replace-match "" nil nil nil 1))
22566 (forward-line)))
22567 ;; Comment each line in region.
22568 (let ((min-indent (point-max)))
22569 ;; First find the minimum indentation across all lines.
22570 (save-excursion
22571 (goto-char (point-min))
22572 (while (and (not (eobp)) (not (zerop min-indent)))
22573 (unless (looking-at "[ \t]*$")
22574 (setq min-indent (min min-indent (current-indentation))))
22575 (forward-line)))
22576 ;; Then loop over all lines.
22577 (save-excursion
22578 (goto-char (point-min))
22579 (while (not (eobp))
22580 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22581 ;; Don't get fooled by invisible text (e.g. link path)
22582 ;; when moving to column MIN-INDENT.
22583 (let ((buffer-invisibility-spec nil))
22584 (org-move-to-column min-indent t))
22585 (insert comment-start))
22586 (forward-line))))))))
22589 ;;; Planning
22591 ;; This section contains tools to operate on timestamp objects, as
22592 ;; returned by, e.g. `org-element-context'.
22594 (defun org-timestamp-has-time-p (timestamp)
22595 "Non-nil when TIMESTAMP has a time specified."
22596 (org-element-property :hour-start timestamp))
22598 (defun org-timestamp-format (timestamp format &optional end utc)
22599 "Format a TIMESTAMP element into a string.
22601 FORMAT is a format specifier to be passed to
22602 `format-time-string'.
22604 When optional argument END is non-nil, use end of date-range or
22605 time-range, if possible.
22607 When optional argument UTC is non-nil, time will be expressed as
22608 Universal Time."
22609 (format-time-string
22610 format
22611 (apply 'encode-time
22612 (cons 0
22613 (mapcar
22614 (lambda (prop) (or (org-element-property prop timestamp) 0))
22615 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22616 '(:minute-start :hour-start :day-start :month-start
22617 :year-start)))))
22618 utc))
22620 (defun org-timestamp-split-range (timestamp &optional end)
22621 "Extract a timestamp object from a date or time range.
22623 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22624 the end of the range. Otherwise, extract its start.
22626 Return a new timestamp object sharing the same parent as
22627 TIMESTAMP."
22628 (let ((type (org-element-property :type timestamp)))
22629 (if (memq type '(active inactive diary)) timestamp
22630 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22631 ;; Set new type.
22632 (org-element-put-property
22633 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22634 ;; Copy start properties over end properties if END is
22635 ;; non-nil. Otherwise, copy end properties over `start' ones.
22636 (let ((p-alist '((:minute-start . :minute-end)
22637 (:hour-start . :hour-end)
22638 (:day-start . :day-end)
22639 (:month-start . :month-end)
22640 (:year-start . :year-end))))
22641 (dolist (p-cell p-alist)
22642 (org-element-put-property
22643 split-ts
22644 (funcall (if end 'car 'cdr) p-cell)
22645 (org-element-property
22646 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22647 ;; Eventually refresh `:raw-value'.
22648 (org-element-put-property split-ts :raw-value nil)
22649 (org-element-put-property
22650 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22652 (defun org-timestamp-translate (timestamp &optional boundary)
22653 "Apply `org-translate-time' on a TIMESTAMP object.
22654 When optional argument BOUNDARY is non-nil, it is either the
22655 symbol `start' or `end'. In this case, only translate the
22656 starting or ending part of TIMESTAMP if it is a date or time
22657 range. Otherwise, translate both parts."
22658 (if (and (not boundary)
22659 (memq (org-element-property :type timestamp)
22660 '(active-range inactive-range)))
22661 (concat
22662 (org-translate-time
22663 (org-element-property :raw-value
22664 (org-timestamp-split-range timestamp)))
22665 "--"
22666 (org-translate-time
22667 (org-element-property :raw-value
22668 (org-timestamp-split-range timestamp t))))
22669 (org-translate-time
22670 (org-element-property
22671 :raw-value
22672 (if (not boundary) timestamp
22673 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22677 ;;; Other stuff.
22679 (defun org-toggle-fixed-width-section (arg)
22680 "Toggle the fixed-width export.
22681 If there is no active region, the QUOTE keyword at the current headline is
22682 inserted or removed. When present, it causes the text between this headline
22683 and the next to be exported as fixed-width text, and unmodified.
22684 If there is an active region, this command adds or removes a colon as the
22685 first character of this line. If the first character of a line is a colon,
22686 this line is also exported in fixed-width font."
22687 (interactive "P")
22688 (let* ((cc 0)
22689 (regionp (org-region-active-p))
22690 (beg (if regionp (region-beginning) (point)))
22691 (end (if regionp (region-end)))
22692 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22693 (case-fold-search nil)
22694 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22695 off)
22696 (if regionp
22697 (save-excursion
22698 (goto-char beg)
22699 (setq cc (current-column))
22700 (beginning-of-line 1)
22701 (setq off (looking-at re))
22702 (while (> nlines 0)
22703 (setq nlines (1- nlines))
22704 (beginning-of-line 1)
22705 (cond
22706 (arg
22707 (org-move-to-column cc t)
22708 (insert ": \n")
22709 (forward-line -1))
22710 ((and off (looking-at re))
22711 (replace-match "" t t nil 1))
22712 ((not off) (org-move-to-column cc t) (insert ": ")))
22713 (forward-line 1)))
22714 (save-excursion
22715 (org-back-to-heading)
22716 (cond
22717 ((looking-at (format org-heading-keyword-regexp-format
22718 org-quote-string))
22719 (goto-char (match-end 1))
22720 (looking-at (concat " +" org-quote-string))
22721 (replace-match "" t t)
22722 (when (eolp) (insert " ")))
22723 ((looking-at org-outline-regexp)
22724 (goto-char (match-end 0))
22725 (insert org-quote-string " ")))))))
22727 (defun org-reftex-citation ()
22728 "Use reftex-citation to insert a citation into the buffer.
22729 This looks for a line like
22731 #+BIBLIOGRAPHY: foo plain option:-d
22733 and derives from it that foo.bib is the bibliography file relevant
22734 for this document. It then installs the necessary environment for RefTeX
22735 to work in this buffer and calls `reftex-citation' to insert a citation
22736 into the buffer.
22738 Export of such citations to both LaTeX and HTML is handled by the contributed
22739 package ox-bibtex by Taru Karttunen."
22740 (interactive)
22741 (let ((reftex-docstruct-symbol 'rds)
22742 (reftex-cite-format "\\cite{%l}")
22743 rds bib)
22744 (save-excursion
22745 (save-restriction
22746 (widen)
22747 (let ((case-fold-search t)
22748 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22749 (if (not (save-excursion
22750 (or (re-search-forward re nil t)
22751 (re-search-backward re nil t))))
22752 (error "No bibliography defined in file")
22753 (setq bib (concat (match-string 1) ".bib")
22754 rds (list (list 'bib bib)))))))
22755 (call-interactively 'reftex-citation)))
22757 ;;;; Functions extending outline functionality
22759 (defun org-beginning-of-line (&optional arg)
22760 "Go to the beginning of the current line. If that is invisible, continue
22761 to a visible line beginning. This makes the function of C-a more intuitive.
22762 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22763 first attempt, and only move to after the tags when the cursor is already
22764 beyond the end of the headline."
22765 (interactive "P")
22766 (let ((pos (point))
22767 (special (if (consp org-special-ctrl-a/e)
22768 (car org-special-ctrl-a/e)
22769 org-special-ctrl-a/e))
22770 deactivate-mark refpos)
22771 (if (org-bound-and-true-p visual-line-mode)
22772 (beginning-of-visual-line 1)
22773 (beginning-of-line 1))
22774 (if (and arg (fboundp 'move-beginning-of-line))
22775 (call-interactively 'move-beginning-of-line)
22776 (if (bobp)
22778 (backward-char 1)
22779 (if (org-truely-invisible-p)
22780 (while (and (not (bobp)) (org-truely-invisible-p))
22781 (backward-char 1)
22782 (beginning-of-line 1))
22783 (forward-char 1))))
22784 (when special
22785 (cond
22786 ((and (looking-at org-complex-heading-regexp)
22787 (= (char-after (match-end 1)) ?\ ))
22788 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22789 (point-at-eol)))
22790 (goto-char
22791 (if (eq special t)
22792 (cond ((> pos refpos) refpos)
22793 ((= pos (point)) refpos)
22794 (t (point)))
22795 (cond ((> pos (point)) (point))
22796 ((not (eq last-command this-command)) (point))
22797 (t refpos)))))
22798 ((org-at-item-p)
22799 ;; Being at an item and not looking at an the item means point
22800 ;; was previously moved to beginning of a visual line, which
22801 ;; doesn't contain the item. Therefore, do nothing special,
22802 ;; just stay here.
22803 (when (looking-at org-list-full-item-re)
22804 ;; Set special position at first white space character after
22805 ;; bullet, and check-box, if any.
22806 (let ((after-bullet
22807 (let ((box (match-end 3)))
22808 (if (not box) (match-end 1)
22809 (let ((after (char-after box)))
22810 (if (and after (= after ? )) (1+ box) box))))))
22811 ;; Special case: Move point to special position when
22812 ;; currently after it or at beginning of line.
22813 (if (eq special t)
22814 (when (or (> pos after-bullet) (= (point) pos))
22815 (goto-char after-bullet))
22816 ;; Reversed case: Move point to special position when
22817 ;; point was already at beginning of line and command is
22818 ;; repeated.
22819 (when (and (= (point) pos) (eq last-command this-command))
22820 (goto-char after-bullet))))))))
22821 (org-no-warnings
22822 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22823 (setq disable-point-adjustment
22824 (or (not (invisible-p (point)))
22825 (not (invisible-p (max (point-min) (1- (point))))))))
22827 (defun org-end-of-line (&optional arg)
22828 "Go to the end of the line.
22829 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22830 tags on the first attempt, and only move to after the tags when
22831 the cursor is already beyond the end of the headline."
22832 (interactive "P")
22833 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22834 org-special-ctrl-a/e))
22835 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22836 'end-of-visual-line)
22837 ((fboundp 'move-end-of-line) 'move-end-of-line)
22838 (t 'end-of-line)))
22839 deactivate-mark)
22840 (if (or (not special) arg) (call-interactively move-fun)
22841 (let* ((element (save-excursion (beginning-of-line)
22842 (org-element-at-point)))
22843 (type (org-element-type element)))
22844 (cond
22845 ((memq type '(headline inlinetask))
22846 (let ((pos (point)))
22847 (beginning-of-line 1)
22848 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22849 (if (eq special t)
22850 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22851 (goto-char (match-beginning 1))
22852 (goto-char (match-end 0)))
22853 (if (or (< pos (match-end 0))
22854 (not (eq this-command last-command)))
22855 (goto-char (match-end 0))
22856 (goto-char (match-beginning 1))))
22857 (call-interactively move-fun))))
22858 ((org-element-property :hiddenp element)
22859 ;; If element is hidden, `move-end-of-line' would put point
22860 ;; after it. Use `end-of-line' to stay on current line.
22861 (call-interactively 'end-of-line))
22862 (t (call-interactively move-fun)))))
22863 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22864 (setq disable-point-adjustment
22865 (or (not (invisible-p (point)))
22866 (not (invisible-p (max (point-min) (1- (point))))))))
22868 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22869 (define-key org-mode-map "\C-e" 'org-end-of-line)
22871 (defun org-backward-sentence (&optional arg)
22872 "Go to beginning of sentence, or beginning of table field.
22873 This will call `backward-sentence' or `org-table-beginning-of-field',
22874 depending on context."
22875 (interactive "P")
22876 (cond
22877 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22878 (t (call-interactively 'backward-sentence))))
22880 (defun org-forward-sentence (&optional arg)
22881 "Go to end of sentence, or end of table field.
22882 This will call `forward-sentence' or `org-table-end-of-field',
22883 depending on context."
22884 (interactive "P")
22885 (cond
22886 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22887 (t (call-interactively 'forward-sentence))))
22889 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22890 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22892 (defun org-kill-line (&optional arg)
22893 "Kill line, to tags or end of line."
22894 (interactive "P")
22895 (cond
22896 ((or (not org-special-ctrl-k)
22897 (bolp)
22898 (not (org-at-heading-p)))
22899 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22900 org-ctrl-k-protect-subtree)
22901 (if (or (eq org-ctrl-k-protect-subtree 'error)
22902 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22903 (user-error "C-k aborted as it would kill a hidden subtree")))
22904 (call-interactively
22905 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22906 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22907 (kill-region (point) (match-beginning 1))
22908 (org-set-tags nil t))
22909 (t (kill-region (point) (point-at-eol)))))
22911 (define-key org-mode-map "\C-k" 'org-kill-line)
22913 (defun org-yank (&optional arg)
22914 "Yank. If the kill is a subtree, treat it specially.
22915 This command will look at the current kill and check if is a single
22916 subtree, or a series of subtrees[1]. If it passes the test, and if the
22917 cursor is at the beginning of a line or after the stars of a currently
22918 empty headline, then the yank is handled specially. How exactly depends
22919 on the value of the following variables, both set by default.
22921 org-yank-folded-subtrees
22922 When set, the subtree(s) will be folded after insertion, but only
22923 if doing so would now swallow text after the yanked text.
22925 org-yank-adjusted-subtrees
22926 When set, the subtree will be promoted or demoted in order to
22927 fit into the local outline tree structure, which means that the level
22928 will be adjusted so that it becomes the smaller one of the two
22929 *visible* surrounding headings.
22931 Any prefix to this command will cause `yank' to be called directly with
22932 no special treatment. In particular, a simple \\[universal-argument] prefix \
22933 will just
22934 plainly yank the text as it is.
22936 \[1] The test checks if the first non-white line is a heading
22937 and if there are no other headings with fewer stars."
22938 (interactive "P")
22939 (org-yank-generic 'yank arg))
22941 (defun org-yank-generic (command arg)
22942 "Perform some yank-like command.
22944 This function implements the behavior described in the `org-yank'
22945 documentation. However, it has been generalized to work for any
22946 interactive command with similar behavior."
22948 ;; pretend to be command COMMAND
22949 (setq this-command command)
22951 (if arg
22952 (call-interactively command)
22954 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22955 (and (org-kill-is-subtree-p)
22956 (or (bolp)
22957 (and (looking-at "[ \t]*$")
22958 (string-match
22959 "\\`\\*+\\'"
22960 (buffer-substring (point-at-bol) (point)))))))
22961 swallowp)
22962 (cond
22963 ((and subtreep org-yank-folded-subtrees)
22964 (let ((beg (point))
22965 end)
22966 (if (and subtreep org-yank-adjusted-subtrees)
22967 (org-paste-subtree nil nil 'for-yank)
22968 (call-interactively command))
22970 (setq end (point))
22971 (goto-char beg)
22972 (when (and (bolp) subtreep
22973 (not (setq swallowp
22974 (org-yank-folding-would-swallow-text beg end))))
22975 (org-with-limited-levels
22976 (or (looking-at org-outline-regexp)
22977 (re-search-forward org-outline-regexp-bol end t))
22978 (while (and (< (point) end) (looking-at org-outline-regexp))
22979 (hide-subtree)
22980 (org-cycle-show-empty-lines 'folded)
22981 (condition-case nil
22982 (outline-forward-same-level 1)
22983 (error (goto-char end))))))
22984 (when swallowp
22985 (message
22986 "Inserted text not folded because that would swallow text"))
22988 (goto-char end)
22989 (skip-chars-forward " \t\n\r")
22990 (beginning-of-line 1)
22991 (push-mark beg 'nomsg)))
22992 ((and subtreep org-yank-adjusted-subtrees)
22993 (let ((beg (point-at-bol)))
22994 (org-paste-subtree nil nil 'for-yank)
22995 (push-mark beg 'nomsg)))
22997 (call-interactively command))))))
22999 (defun org-yank-folding-would-swallow-text (beg end)
23000 "Would hide-subtree at BEG swallow any text after END?"
23001 (let (level)
23002 (org-with-limited-levels
23003 (save-excursion
23004 (goto-char beg)
23005 (when (or (looking-at org-outline-regexp)
23006 (re-search-forward org-outline-regexp-bol end t))
23007 (setq level (org-outline-level)))
23008 (goto-char end)
23009 (skip-chars-forward " \t\r\n\v\f")
23010 (if (or (eobp)
23011 (and (bolp) (looking-at org-outline-regexp)
23012 (<= (org-outline-level) level)))
23013 nil ; Nothing would be swallowed
23014 t))))) ; something would swallow
23016 (define-key org-mode-map "\C-y" 'org-yank)
23018 (defun org-truely-invisible-p ()
23019 "Check if point is at a character currently not visible.
23020 This version does not only check the character property, but also
23021 `visible-mode'."
23022 ;; Early versions of noutline don't have `outline-invisible-p'.
23023 (if (org-bound-and-true-p visible-mode)
23025 (outline-invisible-p)))
23027 (defun org-invisible-p2 ()
23028 "Check if point is at a character currently not visible."
23029 (save-excursion
23030 (if (and (eolp) (not (bobp))) (backward-char 1))
23031 ;; Early versions of noutline don't have `outline-invisible-p'.
23032 (outline-invisible-p)))
23034 (defun org-back-to-heading (&optional invisible-ok)
23035 "Call `outline-back-to-heading', but provide a better error message."
23036 (condition-case nil
23037 (outline-back-to-heading invisible-ok)
23038 (error (error "Before first headline at position %d in buffer %s"
23039 (point) (current-buffer)))))
23041 (defun org-before-first-heading-p ()
23042 "Before first heading?"
23043 (save-excursion
23044 (end-of-line)
23045 (null (re-search-backward org-outline-regexp-bol nil t))))
23047 (defun org-at-heading-p (&optional ignored)
23048 (outline-on-heading-p t))
23049 ;; Compatibility alias with Org versions < 7.8.03
23050 (defalias 'org-on-heading-p 'org-at-heading-p)
23052 (defun org-at-comment-p nil
23053 "Is cursor in a line starting with a # character?"
23054 (save-excursion
23055 (beginning-of-line)
23056 (looking-at "^#")))
23058 (defun org-at-drawer-p nil
23059 "Is cursor at a drawer keyword?"
23060 (save-excursion
23061 (move-beginning-of-line 1)
23062 (looking-at org-drawer-regexp)))
23064 (defun org-at-block-p nil
23065 "Is cursor at a block keyword?"
23066 (save-excursion
23067 (move-beginning-of-line 1)
23068 (looking-at org-block-regexp)))
23070 (defun org-point-at-end-of-empty-headline ()
23071 "If point is at the end of an empty headline, return t, else nil.
23072 If the heading only contains a TODO keyword, it is still still considered
23073 empty."
23074 (and (looking-at "[ \t]*$")
23075 (when org-todo-line-regexp
23076 (save-excursion
23077 (beginning-of-line 1)
23078 (let ((case-fold-search nil))
23079 (looking-at org-todo-line-regexp)
23080 (string= (match-string 3) ""))))))
23082 (defun org-at-heading-or-item-p ()
23083 (or (org-at-heading-p) (org-at-item-p)))
23085 (defun org-at-target-p ()
23086 (or (org-in-regexp org-radio-target-regexp)
23087 (org-in-regexp org-target-regexp)))
23088 ;; Compatibility alias with Org versions < 7.8.03
23089 (defalias 'org-on-target-p 'org-at-target-p)
23091 (defun org-up-heading-all (arg)
23092 "Move to the heading line of which the present line is a subheading.
23093 This function considers both visible and invisible heading lines.
23094 With argument, move up ARG levels."
23095 (if (fboundp 'outline-up-heading-all)
23096 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23097 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23099 (defun org-up-heading-safe ()
23100 "Move to the heading line of which the present line is a subheading.
23101 This version will not throw an error. It will return the level of the
23102 headline found, or nil if no higher level is found.
23104 Also, this function will be a lot faster than `outline-up-heading',
23105 because it relies on stars being the outline starters. This can really
23106 make a significant difference in outlines with very many siblings."
23107 (let (start-level re)
23108 (org-back-to-heading t)
23109 (setq start-level (funcall outline-level))
23110 (if (equal start-level 1)
23112 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
23113 (if (re-search-backward re nil t)
23114 (funcall outline-level)))))
23116 (defun org-first-sibling-p ()
23117 "Is this heading the first child of its parents?"
23118 (interactive)
23119 (let ((re org-outline-regexp-bol)
23120 level l)
23121 (unless (org-at-heading-p t)
23122 (user-error "Not at a heading"))
23123 (setq level (funcall outline-level))
23124 (save-excursion
23125 (if (not (re-search-backward re nil t))
23127 (setq l (funcall outline-level))
23128 (< l level)))))
23130 (defun org-goto-sibling (&optional previous)
23131 "Goto the next sibling, even if it is invisible.
23132 When PREVIOUS is set, go to the previous sibling instead. Returns t
23133 when a sibling was found. When none is found, return nil and don't
23134 move point."
23135 (let ((fun (if previous 're-search-backward 're-search-forward))
23136 (pos (point))
23137 (re org-outline-regexp-bol)
23138 level l)
23139 (when (condition-case nil (org-back-to-heading t) (error nil))
23140 (setq level (funcall outline-level))
23141 (catch 'exit
23142 (or previous (forward-char 1))
23143 (while (funcall fun re nil t)
23144 (setq l (funcall outline-level))
23145 (when (< l level) (goto-char pos) (throw 'exit nil))
23146 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23147 (goto-char pos)
23148 nil))))
23150 (defun org-show-siblings ()
23151 "Show all siblings of the current headline."
23152 (save-excursion
23153 (while (org-goto-sibling) (org-flag-heading nil)))
23154 (save-excursion
23155 (while (org-goto-sibling 'previous)
23156 (org-flag-heading nil))))
23158 (defun org-goto-first-child ()
23159 "Goto the first child, even if it is invisible.
23160 Return t when a child was found. Otherwise don't move point and
23161 return nil."
23162 (let (level (pos (point)) (re org-outline-regexp-bol))
23163 (when (condition-case nil (org-back-to-heading t) (error nil))
23164 (setq level (outline-level))
23165 (forward-char 1)
23166 (if (and (re-search-forward re nil t) (> (outline-level) level))
23167 (progn (goto-char (match-beginning 0)) t)
23168 (goto-char pos) nil))))
23170 (defun org-show-hidden-entry ()
23171 "Show an entry where even the heading is hidden."
23172 (save-excursion
23173 (org-show-entry)))
23175 (defun org-flag-heading (flag &optional entry)
23176 "Flag the current heading. FLAG non-nil means make invisible.
23177 When ENTRY is non-nil, show the entire entry."
23178 (save-excursion
23179 (org-back-to-heading t)
23180 ;; Check if we should show the entire entry
23181 (if entry
23182 (progn
23183 (org-show-entry)
23184 (save-excursion
23185 (and (outline-next-heading)
23186 (org-flag-heading nil))))
23187 (outline-flag-region (max (point-min) (1- (point)))
23188 (save-excursion (outline-end-of-heading) (point))
23189 flag))))
23191 (defun org-get-next-sibling ()
23192 "Move to next heading of the same level, and return point.
23193 If there is no such heading, return nil.
23194 This is like outline-next-sibling, but invisible headings are ok."
23195 (let ((level (funcall outline-level)))
23196 (outline-next-heading)
23197 (while (and (not (eobp)) (> (funcall outline-level) level))
23198 (outline-next-heading))
23199 (if (or (eobp) (< (funcall outline-level) level))
23201 (point))))
23203 (defun org-get-last-sibling ()
23204 "Move to previous heading of the same level, and return point.
23205 If there is no such heading, return nil."
23206 (let ((opoint (point))
23207 (level (funcall outline-level)))
23208 (outline-previous-heading)
23209 (when (and (/= (point) opoint) (outline-on-heading-p t))
23210 (while (and (> (funcall outline-level) level)
23211 (not (bobp)))
23212 (outline-previous-heading))
23213 (if (< (funcall outline-level) level)
23215 (point)))))
23217 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23218 "Goto to the end of a subtree."
23219 ;; This contains an exact copy of the original function, but it uses
23220 ;; `org-back-to-heading', to make it work also in invisible
23221 ;; trees. And is uses an invisible-ok argument.
23222 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23223 ;; Furthermore, when used inside Org, finding the end of a large subtree
23224 ;; with many children and grandchildren etc, this can be much faster
23225 ;; than the outline version.
23226 (org-back-to-heading invisible-ok)
23227 (let ((first t)
23228 (level (funcall outline-level)))
23229 (if (and (derived-mode-p 'org-mode) (< level 1000))
23230 ;; A true heading (not a plain list item), in Org-mode
23231 ;; This means we can easily find the end by looking
23232 ;; only for the right number of stars. Using a regexp to do
23233 ;; this is so much faster than using a Lisp loop.
23234 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23235 (forward-char 1)
23236 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23237 ;; something else, do it the slow way
23238 (while (and (not (eobp))
23239 (or first (> (funcall outline-level) level)))
23240 (setq first nil)
23241 (outline-next-heading)))
23242 (unless to-heading
23243 (if (memq (preceding-char) '(?\n ?\^M))
23244 (progn
23245 ;; Go to end of line before heading
23246 (forward-char -1)
23247 (if (memq (preceding-char) '(?\n ?\^M))
23248 ;; leave blank line before heading
23249 (forward-char -1))))))
23250 (point))
23252 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23253 "Use Org version in org-mode, for dramatic speed-up."
23254 (if (derived-mode-p 'org-mode)
23255 (progn
23256 (org-end-of-subtree nil t)
23257 (unless (eobp) (backward-char 1)))
23258 ad-do-it))
23260 (defun org-end-of-meta-data-and-drawers ()
23261 "Jump to the first text after meta data and drawers in the current entry.
23262 This will move over empty lines, lines with planning time stamps,
23263 clocking lines, and drawers."
23264 (org-back-to-heading t)
23265 (let ((end (save-excursion (outline-next-heading) (point)))
23266 (re (concat "\\(" org-drawer-regexp "\\)"
23267 "\\|" "[ \t]*" org-keyword-time-regexp)))
23268 (forward-line 1)
23269 (while (re-search-forward re end t)
23270 (if (not (match-end 1))
23271 ;; empty or planning line
23272 (forward-line 1)
23273 ;; a drawer, find the end
23274 (re-search-forward "^[ \t]*:END:" end 'move)
23275 (forward-line 1)))
23276 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23277 (point)))
23279 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23280 "Move forward to the ARG'th subheading at same level as this one.
23281 Stop at the first and last subheadings of a superior heading.
23282 Normally this only looks at visible headings, but when INVISIBLE-OK is
23283 non-nil it will also look at invisible ones."
23284 (interactive "p")
23285 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23286 (if (and arg (< arg 0))
23287 (goto-char (point-min))
23288 (outline-next-heading))
23289 (org-at-heading-p)
23290 (let ((level (- (match-end 0) (match-beginning 0) 1))
23291 (f (if (and arg (< arg 0))
23292 're-search-backward
23293 're-search-forward))
23294 (count (if arg (abs arg) 1))
23295 (result (point)))
23296 (while (and (prog1 (> count 0)
23297 (forward-char (if (and arg (< arg 0)) -1 1)))
23298 (funcall f org-outline-regexp-bol nil 'move))
23299 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23300 (cond ((< l level) (setq count 0))
23301 ((and (= l level)
23302 (or invisible-ok
23303 (progn
23304 (goto-char (line-beginning-position))
23305 (not (outline-invisible-p)))))
23306 (setq count (1- count))
23307 (when (eq l level)
23308 (setq result (point)))))))
23309 (goto-char result))
23310 (beginning-of-line 1)))
23312 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23313 "Move backward to the ARG'th subheading at same level as this one.
23314 Stop at the first and last subheadings of a superior heading."
23315 (interactive "p")
23316 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23318 (defun org-next-block (arg &optional backward block-regexp)
23319 "Jump to the next block.
23320 With a prefix argument ARG, jump forward ARG many source blocks.
23321 When BACKWARD is non-nil, jump to the previous block.
23322 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23323 (interactive "p")
23324 (let ((re (or block-regexp org-block-regexp))
23325 (re-search-fn (or (and backward 're-search-backward)
23326 're-search-forward)))
23327 (if (looking-at re) (forward-char 1))
23328 (condition-case nil
23329 (funcall re-search-fn re nil nil arg)
23330 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23331 (goto-char (match-beginning 0)) (org-show-context)))
23333 (defun org-previous-block (arg &optional block-regexp)
23334 "Jump to the previous block.
23335 With a prefix argument ARG, jump backward ARG many source blocks.
23336 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23337 (interactive "p")
23338 (org-next-block arg t block-regexp))
23340 (defun org-forward-paragraph ()
23341 "Move forward to beginning of next paragraph or equivalent.
23343 The function moves point to the beginning of the next visible
23344 structural element, which can be a paragraph, a table, a list
23345 item, etc. It also provides some special moves for convenience:
23347 - On an affiliated keyword, jump to the beginning of the
23348 relative element.
23349 - On an item or a footnote definition, move to the second
23350 element inside, if any.
23351 - On a table or a property drawer, jump after it.
23352 - On a verse or source block, stop after blank lines."
23353 (interactive)
23354 (when (eobp) (user-error "Cannot move further down"))
23355 (let* ((deactivate-mark nil)
23356 (element (org-element-at-point))
23357 (type (org-element-type element))
23358 (post-affiliated (org-element-property :post-affiliated element))
23359 (contents-begin (org-element-property :contents-begin element))
23360 (contents-end (org-element-property :contents-end element))
23361 (end (let ((end (org-element-property :end element)) (parent element))
23362 (while (and (setq parent (org-element-property :parent parent))
23363 (= (org-element-property :contents-end parent) end))
23364 (setq end (org-element-property :end parent)))
23365 end)))
23366 (cond ((not element)
23367 (skip-chars-forward " \r\t\n")
23368 (or (eobp) (beginning-of-line)))
23369 ;; On affiliated keywords, move to element's beginning.
23370 ((and post-affiliated (< (point) post-affiliated))
23371 (goto-char post-affiliated))
23372 ;; At a table row, move to the end of the table. Similarly,
23373 ;; at a node property, move to the end of the property
23374 ;; drawer.
23375 ((memq type '(node-property table-row))
23376 (goto-char (org-element-property
23377 :end (org-element-property :parent element))))
23378 ((memq type '(property-drawer table)) (goto-char end))
23379 ;; Consider blank lines as separators in verse and source
23380 ;; blocks to ease editing.
23381 ((memq type '(src-block verse-block))
23382 (when (eq type 'src-block)
23383 (setq contents-end
23384 (save-excursion (goto-char end)
23385 (skip-chars-backward " \r\t\n")
23386 (line-beginning-position))))
23387 (beginning-of-line)
23388 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23389 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23390 (goto-char end)
23391 (skip-chars-forward " \r\t\n")
23392 (if (= (point) contents-end) (goto-char end)
23393 (beginning-of-line))))
23394 ;; With no contents, just skip element.
23395 ((not contents-begin) (goto-char end))
23396 ;; If contents are invisible, skip the element altogether.
23397 ((outline-invisible-p (line-end-position))
23398 (case type
23399 (headline
23400 (org-with-limited-levels (outline-next-visible-heading 1)))
23401 ;; At a plain list, make sure we move to the next item
23402 ;; instead of skipping the whole list.
23403 (plain-list (forward-char)
23404 (org-forward-paragraph))
23405 (otherwise (goto-char end))))
23406 ((>= (point) contents-end) (goto-char end))
23407 ((>= (point) contents-begin)
23408 ;; This can only happen on paragraphs and plain lists.
23409 (case type
23410 (paragraph (goto-char end))
23411 ;; At a plain list, try to move to second element in
23412 ;; first item, if possible.
23413 (plain-list (end-of-line)
23414 (org-forward-paragraph))))
23415 ;; When contents start on the middle of a line (e.g. in
23416 ;; items and footnote definitions), try to reach first
23417 ;; element starting after current line.
23418 ((> (line-end-position) contents-begin)
23419 (end-of-line)
23420 (org-forward-paragraph))
23421 (t (goto-char contents-begin)))))
23423 (defun org-backward-paragraph ()
23424 "Move backward to start of previous paragraph or equivalent.
23426 The function moves point to the beginning of the current
23427 structural element, which can be a paragraph, a table, a list
23428 item, etc., or to the beginning of the previous visible one if
23429 point is already there. It also provides some special moves for
23430 convenience:
23432 - On an affiliated keyword, jump to the first one.
23433 - On a table or a property drawer, move to its beginning.
23434 - On a verse or source block, stop before blank lines."
23435 (interactive)
23436 (when (bobp) (user-error "Cannot move further up"))
23437 (let* ((deactivate-mark nil)
23438 (element (org-element-at-point))
23439 (type (org-element-type element))
23440 (contents-begin (org-element-property :contents-begin element))
23441 (contents-end (org-element-property :contents-end element))
23442 (post-affiliated (org-element-property :post-affiliated element))
23443 (begin (org-element-property :begin element)))
23444 (cond
23445 ((not element) (goto-char (point-min)))
23446 ((= (point) begin)
23447 (backward-char)
23448 (org-backward-paragraph))
23449 ((and post-affiliated (<= (point) post-affiliated)) (goto-char begin))
23450 ((memq type '(node-property table-row))
23451 (goto-char (org-element-property
23452 :post-affiliated (org-element-property :parent element))))
23453 ((memq type '(property-drawer table)) (goto-char begin))
23454 ((memq type '(src-block verse-block))
23455 (when (eq type 'src-block)
23456 (setq contents-begin
23457 (save-excursion (goto-char begin) (forward-line) (point))))
23458 (if (= (point) contents-begin) (goto-char post-affiliated)
23459 ;; Inside a verse block, see blank lines as paragraph
23460 ;; separators.
23461 (let ((origin (point)))
23462 (skip-chars-backward " \r\t\n" contents-begin)
23463 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23464 (skip-chars-forward " \r\t\n" origin)
23465 (if (= (point) origin) (goto-char contents-begin)
23466 (beginning-of-line))))))
23467 ((not contents-begin) (goto-char (or post-affiliated begin)))
23468 ((eq type 'paragraph)
23469 (goto-char contents-begin)
23470 ;; When at first paragraph in an item or a footnote definition,
23471 ;; move directly to beginning of line.
23472 (let ((parent-contents
23473 (org-element-property
23474 :contents-begin (org-element-property :parent element))))
23475 (when (and parent-contents (= parent-contents contents-begin))
23476 (beginning-of-line))))
23477 ;; At the end of a greater element, move to the beginning of the
23478 ;; last element within.
23479 ((>= (point) contents-end)
23480 (goto-char (1- contents-end))
23481 (org-backward-paragraph))
23482 (t (goto-char (or post-affiliated begin))))
23483 ;; Ensure we never leave point invisible.
23484 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
23486 (defun org-forward-element ()
23487 "Move forward by one element.
23488 Move to the next element at the same level, when possible."
23489 (interactive)
23490 (cond ((eobp) (user-error "Cannot move further down"))
23491 ((org-with-limited-levels (org-at-heading-p))
23492 (let ((origin (point)))
23493 (goto-char (org-end-of-subtree nil t))
23494 (unless (org-with-limited-levels (org-at-heading-p))
23495 (goto-char origin)
23496 (user-error "Cannot move further down"))))
23498 (let* ((elem (org-element-at-point))
23499 (end (org-element-property :end elem))
23500 (parent (org-element-property :parent elem)))
23501 (cond ((and parent (= (org-element-property :contents-end parent) end))
23502 (goto-char (org-element-property :end parent)))
23503 ((integer-or-marker-p end) (goto-char end))
23504 (t (message "No element at point")))))))
23506 (defun org-backward-element ()
23507 "Move backward by one element.
23508 Move to the previous element at the same level, when possible."
23509 (interactive)
23510 (cond ((bobp) (user-error "Cannot move further up"))
23511 ((org-with-limited-levels (org-at-heading-p))
23512 ;; At a headline, move to the previous one, if any, or stay
23513 ;; here.
23514 (let ((origin (point)))
23515 (org-with-limited-levels (org-backward-heading-same-level 1))
23516 ;; When current headline has no sibling above, move to its
23517 ;; parent.
23518 (when (= (point) origin)
23519 (or (org-with-limited-levels (org-up-heading-safe))
23520 (progn (goto-char origin)
23521 (user-error "Cannot move further up"))))))
23523 (let* ((trail (org-element-at-point 'keep-trail))
23524 (elem (car trail))
23525 (prev-elem (nth 1 trail))
23526 (beg (org-element-property :begin elem)))
23527 (cond
23528 ;; Move to beginning of current element if point isn't
23529 ;; there already.
23530 ((null beg) (message "No element at point"))
23531 ((/= (point) beg) (goto-char beg))
23532 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23533 ((org-before-first-heading-p) (goto-char (point-min)))
23534 (t (org-back-to-heading)))))))
23536 (defun org-up-element ()
23537 "Move to upper element."
23538 (interactive)
23539 (if (org-with-limited-levels (org-at-heading-p))
23540 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23541 (let* ((elem (org-element-at-point))
23542 (parent (org-element-property :parent elem)))
23543 (if parent (goto-char (org-element-property :begin parent))
23544 (if (org-with-limited-levels (org-before-first-heading-p))
23545 (user-error "No surrounding element")
23546 (org-with-limited-levels (org-back-to-heading)))))))
23548 (defvar org-element-greater-elements)
23549 (defun org-down-element ()
23550 "Move to inner element."
23551 (interactive)
23552 (let ((element (org-element-at-point)))
23553 (cond
23554 ((memq (org-element-type element) '(plain-list table))
23555 (goto-char (org-element-property :contents-begin element))
23556 (forward-char))
23557 ((memq (org-element-type element) org-element-greater-elements)
23558 ;; If contents are hidden, first disclose them.
23559 (when (org-element-property :hiddenp element) (org-cycle))
23560 (goto-char (or (org-element-property :contents-begin element)
23561 (user-error "No content for this element"))))
23562 (t (user-error "No inner element")))))
23564 (defun org-drag-element-backward ()
23565 "Move backward element at point."
23566 (interactive)
23567 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23568 (let* ((trail (org-element-at-point 'keep-trail))
23569 (elem (car trail))
23570 (prev-elem (nth 1 trail)))
23571 ;; Error out if no previous element or previous element is
23572 ;; a parent of the current one.
23573 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23574 (user-error "Cannot drag element backward")
23575 (let ((pos (point)))
23576 (org-element-swap-A-B prev-elem elem)
23577 (goto-char (+ (org-element-property :begin prev-elem)
23578 (- pos (org-element-property :begin elem)))))))))
23580 (defun org-drag-element-forward ()
23581 "Move forward element at point."
23582 (interactive)
23583 (let* ((pos (point))
23584 (elem (org-element-at-point)))
23585 (when (= (point-max) (org-element-property :end elem))
23586 (user-error "Cannot drag element forward"))
23587 (goto-char (org-element-property :end elem))
23588 (let ((next-elem (org-element-at-point)))
23589 (when (or (org-element-nested-p elem next-elem)
23590 (and (eq (org-element-type next-elem) 'headline)
23591 (not (eq (org-element-type elem) 'headline))))
23592 (goto-char pos)
23593 (user-error "Cannot drag element forward"))
23594 ;; Compute new position of point: it's shifted by NEXT-ELEM
23595 ;; body's length (without final blanks) and by the length of
23596 ;; blanks between ELEM and NEXT-ELEM.
23597 (let ((size-next (- (save-excursion
23598 (goto-char (org-element-property :end next-elem))
23599 (skip-chars-backward " \r\t\n")
23600 (forward-line)
23601 ;; Small correction if buffer doesn't end
23602 ;; with a newline character.
23603 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23604 (org-element-property :begin next-elem)))
23605 (size-blank (- (org-element-property :end elem)
23606 (save-excursion
23607 (goto-char (org-element-property :end elem))
23608 (skip-chars-backward " \r\t\n")
23609 (forward-line)
23610 (point)))))
23611 (org-element-swap-A-B elem next-elem)
23612 (goto-char (+ pos size-next size-blank))))))
23614 (defun org-drag-line-forward (arg)
23615 "Drag the line at point ARG lines forward."
23616 (interactive "p")
23617 (dotimes (n (abs arg))
23618 (let ((c (current-column)))
23619 (if (< 0 arg)
23620 (progn
23621 (beginning-of-line 2)
23622 (transpose-lines 1)
23623 (beginning-of-line 0))
23624 (transpose-lines 1)
23625 (beginning-of-line -1))
23626 (org-move-to-column c))))
23628 (defun org-drag-line-backward (arg)
23629 "Drag the line at point ARG lines backward."
23630 (interactive "p")
23631 (org-drag-line-forward (- arg)))
23633 (defun org-mark-element ()
23634 "Put point at beginning of this element, mark at end.
23636 Interactively, if this command is repeated or (in Transient Mark
23637 mode) if the mark is active, it marks the next element after the
23638 ones already marked."
23639 (interactive)
23640 (let (deactivate-mark)
23641 (if (and (org-called-interactively-p 'any)
23642 (or (and (eq last-command this-command) (mark t))
23643 (and transient-mark-mode mark-active)))
23644 (set-mark
23645 (save-excursion
23646 (goto-char (mark))
23647 (goto-char (org-element-property :end (org-element-at-point)))))
23648 (let ((element (org-element-at-point)))
23649 (end-of-line)
23650 (push-mark (org-element-property :end element) t t)
23651 (goto-char (org-element-property :begin element))))))
23653 (defun org-narrow-to-element ()
23654 "Narrow buffer to current element."
23655 (interactive)
23656 (let ((elem (org-element-at-point)))
23657 (cond
23658 ((eq (car elem) 'headline)
23659 (narrow-to-region
23660 (org-element-property :begin elem)
23661 (org-element-property :end elem)))
23662 ((memq (car elem) org-element-greater-elements)
23663 (narrow-to-region
23664 (org-element-property :contents-begin elem)
23665 (org-element-property :contents-end elem)))
23667 (narrow-to-region
23668 (org-element-property :begin elem)
23669 (org-element-property :end elem))))))
23671 (defun org-transpose-element ()
23672 "Transpose current and previous elements, keeping blank lines between.
23673 Point is moved after both elements."
23674 (interactive)
23675 (org-skip-whitespace)
23676 (let ((end (org-element-property :end (org-element-at-point))))
23677 (org-drag-element-backward)
23678 (goto-char end)))
23680 (defun org-unindent-buffer ()
23681 "Un-indent the visible part of the buffer.
23682 Relative indentation (between items, inside blocks, etc.) isn't
23683 modified."
23684 (interactive)
23685 (unless (eq major-mode 'org-mode)
23686 (user-error "Cannot un-indent a buffer not in Org mode"))
23687 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23688 unindent-tree ; For byte-compiler.
23689 (unindent-tree
23690 (function
23691 (lambda (contents)
23692 (mapc
23693 (lambda (element)
23694 (if (memq (org-element-type element) '(headline section))
23695 (funcall unindent-tree (org-element-contents element))
23696 (save-excursion
23697 (save-restriction
23698 (narrow-to-region
23699 (org-element-property :begin element)
23700 (org-element-property :end element))
23701 (org-do-remove-indentation)))))
23702 (reverse contents))))))
23703 (funcall unindent-tree (org-element-contents parse-tree))))
23705 (defun org-show-subtree ()
23706 "Show everything after this heading at deeper levels."
23707 (interactive)
23708 (outline-flag-region
23709 (point)
23710 (save-excursion
23711 (org-end-of-subtree t t))
23712 nil))
23714 (defun org-show-entry ()
23715 "Show the body directly following this heading.
23716 Show the heading too, if it is currently invisible."
23717 (interactive)
23718 (save-excursion
23719 (condition-case nil
23720 (progn
23721 (org-back-to-heading t)
23722 (outline-flag-region
23723 (max (point-min) (1- (point)))
23724 (save-excursion
23725 (if (re-search-forward
23726 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23727 (match-beginning 1)
23728 (point-max)))
23729 nil)
23730 (org-cycle-hide-drawers 'children))
23731 (error nil))))
23733 (defun org-make-options-regexp (kwds &optional extra)
23734 "Make a regular expression for keyword lines."
23735 (concat
23736 "^#\\+\\("
23737 (mapconcat 'regexp-quote kwds "\\|")
23738 (if extra (concat "\\|" extra))
23739 "\\):[ \t]*\\(.*\\)"))
23741 ;; Make isearch reveal the necessary context
23742 (defun org-isearch-end ()
23743 "Reveal context after isearch exits."
23744 (when isearch-success ; only if search was successful
23745 (if (featurep 'xemacs)
23746 ;; Under XEmacs, the hook is run in the correct place,
23747 ;; we directly show the context.
23748 (org-show-context 'isearch)
23749 ;; In Emacs the hook runs *before* restoring the overlays.
23750 ;; So we have to use a one-time post-command-hook to do this.
23751 ;; (Emacs 22 has a special variable, see function `org-mode')
23752 (unless (and (boundp 'isearch-mode-end-hook-quit)
23753 isearch-mode-end-hook-quit)
23754 ;; Only when the isearch was not quitted.
23755 (org-add-hook 'post-command-hook 'org-isearch-post-command
23756 'append 'local)))
23757 (org-fix-ellipsis-at-bol)))
23759 (defun org-isearch-post-command ()
23760 "Remove self from hook, and show context."
23761 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23762 (org-show-context 'isearch))
23765 ;;;; Integration with and fixes for other packages
23767 ;;; Imenu support
23769 (defvar org-imenu-markers nil
23770 "All markers currently used by Imenu.")
23771 (make-variable-buffer-local 'org-imenu-markers)
23773 (defun org-imenu-new-marker (&optional pos)
23774 "Return a new marker for use by Imenu, and remember the marker."
23775 (let ((m (make-marker)))
23776 (move-marker m (or pos (point)))
23777 (push m org-imenu-markers)
23780 (defun org-imenu-get-tree ()
23781 "Produce the index for Imenu."
23782 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23783 (setq org-imenu-markers nil)
23784 (let* ((n org-imenu-depth)
23785 (re (concat "^" (org-get-limited-outline-regexp)))
23786 (subs (make-vector (1+ n) nil))
23787 (last-level 0)
23788 m level head0 head)
23789 (save-excursion
23790 (save-restriction
23791 (widen)
23792 (goto-char (point-max))
23793 (while (re-search-backward re nil t)
23794 (setq level (org-reduced-level (funcall outline-level)))
23795 (when (and (<= level n)
23796 (looking-at org-complex-heading-regexp)
23797 (setq head0 (org-match-string-no-properties 4)))
23798 (setq head (org-link-display-format head0)
23799 m (org-imenu-new-marker))
23800 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23801 (if (>= level last-level)
23802 (push (cons head m) (aref subs level))
23803 (push (cons head (aref subs (1+ level))) (aref subs level))
23804 (loop for i from (1+ level) to n do (aset subs i nil)))
23805 (setq last-level level)))))
23806 (aref subs 1)))
23808 (eval-after-load "imenu"
23809 '(progn
23810 (add-hook 'imenu-after-jump-hook
23811 (lambda ()
23812 (if (derived-mode-p 'org-mode)
23813 (org-show-context 'org-goto))))))
23815 (defun org-link-display-format (link)
23816 "Replace a link with its the description.
23817 If there is no description, use the link target."
23818 (save-match-data
23819 (if (string-match org-bracket-link-analytic-regexp link)
23820 (replace-match (if (match-end 5)
23821 (match-string 5 link)
23822 (concat (match-string 1 link)
23823 (match-string 3 link)))
23824 nil t link)
23825 link)))
23827 (defun org-toggle-link-display ()
23828 "Toggle the literal or descriptive display of links."
23829 (interactive)
23830 (if org-descriptive-links
23831 (progn (org-remove-from-invisibility-spec '(org-link))
23832 (org-restart-font-lock)
23833 (setq org-descriptive-links nil))
23834 (progn (add-to-invisibility-spec '(org-link))
23835 (org-restart-font-lock)
23836 (setq org-descriptive-links t))))
23838 ;; Speedbar support
23840 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23841 "Overlay marking the agenda restriction line in speedbar.")
23842 (overlay-put org-speedbar-restriction-lock-overlay
23843 'face 'org-agenda-restriction-lock)
23844 (overlay-put org-speedbar-restriction-lock-overlay
23845 'help-echo "Agendas are currently limited to this item.")
23846 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23848 (defun org-speedbar-set-agenda-restriction ()
23849 "Restrict future agenda commands to the location at point in speedbar.
23850 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23851 (interactive)
23852 (require 'org-agenda)
23853 (let (p m tp np dir txt)
23854 (cond
23855 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23856 'org-imenu t))
23857 (setq m (get-text-property p 'org-imenu-marker))
23858 (with-current-buffer (marker-buffer m)
23859 (goto-char m)
23860 (org-agenda-set-restriction-lock 'subtree)))
23861 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23862 'speedbar-function 'speedbar-find-file))
23863 (setq tp (previous-single-property-change
23864 (1+ p) 'speedbar-function)
23865 np (next-single-property-change
23866 tp 'speedbar-function)
23867 dir (speedbar-line-directory)
23868 txt (buffer-substring-no-properties (or tp (point-min))
23869 (or np (point-max))))
23870 (with-current-buffer (find-file-noselect
23871 (let ((default-directory dir))
23872 (expand-file-name txt)))
23873 (unless (derived-mode-p 'org-mode)
23874 (user-error "Cannot restrict to non-Org-mode file"))
23875 (org-agenda-set-restriction-lock 'file)))
23876 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23877 (move-overlay org-speedbar-restriction-lock-overlay
23878 (point-at-bol) (point-at-eol))
23879 (setq current-prefix-arg nil)
23880 (org-agenda-maybe-redo)))
23882 (defvar speedbar-file-key-map)
23883 (declare-function speedbar-add-supported-extension "speedbar" (extension))
23884 (eval-after-load "speedbar"
23885 '(progn
23886 (speedbar-add-supported-extension ".org")
23887 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23888 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23889 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23890 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23891 (add-hook 'speedbar-visiting-tag-hook
23892 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23894 ;;; Fixes and Hacks for problems with other packages
23896 ;; Make flyspell not check words in links, to not mess up our keymap
23897 (defvar org-element-affiliated-keywords) ; From org-element.el
23898 (defvar org-element-block-name-alist) ; From org-element.el
23899 (defun org-mode-flyspell-verify ()
23900 "Don't let flyspell put overlays at active buttons, or on
23901 {todo,all-time,additional-option-like}-keywords."
23902 (require 'org-element) ; For `org-element-affiliated-keywords'
23903 (let ((pos (max (1- (point)) (point-min)))
23904 (word (thing-at-point 'word)))
23905 (and (not (get-text-property pos 'keymap))
23906 (not (get-text-property pos 'org-no-flyspell))
23907 (not (member word org-todo-keywords-1))
23908 (not (member word org-all-time-keywords))
23909 (not (member word org-options-keywords))
23910 (not (member word (mapcar 'car org-startup-options)))
23911 (not (member-ignore-case word org-element-affiliated-keywords))
23912 (not (member-ignore-case word (org-get-export-keywords)))
23913 (not (member-ignore-case
23914 word (mapcar 'car org-element-block-name-alist)))
23915 (not (member-ignore-case word '("BEGIN" "END" "ATTR")))
23916 (not (org-in-src-block-p)))))
23918 (defun org-remove-flyspell-overlays-in (beg end)
23919 "Remove flyspell overlays in region."
23920 (and (org-bound-and-true-p flyspell-mode)
23921 (fboundp 'flyspell-delete-region-overlays)
23922 (flyspell-delete-region-overlays beg end))
23923 (add-text-properties beg end '(org-no-flyspell t)))
23925 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23926 (eval-after-load "bookmark"
23927 '(if (boundp 'bookmark-after-jump-hook)
23928 ;; We can use the hook
23929 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23930 ;; Hook not available, use advice
23931 (defadvice bookmark-jump (after org-make-visible activate)
23932 "Make the position visible."
23933 (org-bookmark-jump-unhide))))
23935 ;; Make sure saveplace shows the location if it was hidden
23936 (eval-after-load "saveplace"
23937 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23938 "Make the position visible."
23939 (org-bookmark-jump-unhide)))
23941 ;; Make sure ecb shows the location if it was hidden
23942 (eval-after-load "ecb"
23943 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23944 "Make hierarchy visible when jumping into location from ECB tree buffer."
23945 (if (derived-mode-p 'org-mode)
23946 (org-show-context))))
23948 (defun org-bookmark-jump-unhide ()
23949 "Unhide the current position, to show the bookmark location."
23950 (and (derived-mode-p 'org-mode)
23951 (or (outline-invisible-p)
23952 (save-excursion (goto-char (max (point-min) (1- (point))))
23953 (outline-invisible-p)))
23954 (org-show-context 'bookmark-jump)))
23956 ;; Make session.el ignore our circular variable
23957 (defvar session-globals-exclude)
23958 (eval-after-load "session"
23959 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23961 ;;;; Finish up
23963 (provide 'org)
23965 (run-hooks 'org-load-hook)
23967 ;;; org.el ends here